JNTUH Computer Programming Study Materials

Page 1

ru m

Output Storage Area

fo

Primary or Main Memory (RAM)

ld

Register 1

tu

Register N

w

…… ……

Arithmetic and Logic Unit

or

Register 2

.jn

Input Devices

Program Storage Area Working Storage Area

w

Mouse

Input Storage Area

w w

Key board

.c om

Computer -- Hardware

Micro Processor

Secondary Storage Devices

Monitor Printer Output Devices


or w tu

read num Yes

w

w w

start

Flow chart:

.jn

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

ld

fo

ru m

.c om

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

If num%2=0

No

print num is odd

print num is even stop


Flow chart symbols Terminal

Parallegram

Input/output

Rectangle

Process

Document

Hard copy

Diamond

Decision

or

ld

fo

ru m

.c om

Oval

tu

w

Circle

Connector Sub program

Hexagon

Iteration

w w

w

.jn

Double sided Rectangle

Trapezoid

Manual Operation

Cylinder

Magnetic Disk Storage


Machine Language – Assembly Language – High-Level Language

.c om

entry main,^m<r2> sub12 #12,sp jsb C$MAIN_ARGS moveb $CHAR_STRING_CON pusha1 pusha1 calls pusha1 pusha1 calls mull3 pusha calls clrl ret

fo

ru m

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

ld

or

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

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

w

.jn

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

w w

1 2 3 4 5 6 7 8 9 1 0

tu

w

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

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


Structure of C program Documentation Section

.c om

Linkage Section Definition Section

ru m

Global Declaration Section

Local Declaration Part Executable Code Part

w

or

ld

fo

Main Function Section

w w

w

.jn

tu

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

Sub Program Section Function1() Function2() …………… FunctionN()


Program Development Steps

fo

ru m

.c om

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

ld

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

w w

w

.jn

tu

w

or

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


Executing a C program #include<stdio.h> int main() { …….

.c om

prog1.c

compiles

C-compiler

Yes

Syntax Errors?

010110 100 ……………. 01011 101

tu

.jn

prog1.exe

Executes Feeds

w

C-Runtime Runtime or Logic Errors ?

w w

Input

w

Executable machine code

machine code of library file

ld

prog1.obj

adds

or

00101010 …………. 01010101

fo

No Object machine code Linker

Output

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

ru m

Text Editor

Yes


Character Set of C-Language

ld

fo

ru m

.c om

Alphabets : A-Z and a-z Digits : 0-9 Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ; “ ‘ <>,.?/ White Spaces : space , Horizontal tab, Vertical tab, New Line Form Feed.

w

.jn

w

tu

double else enum extern float for goto if _Imaginary

w w

auto break case char const continue default do _Bool inline

or

C-Language Keywords(C99) int long register return short signed sizeof static restrict

struct switch typedef union unsigned void volatile while _Complex


C-Tokens

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


C-Tokens

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


Data Types ( pre defined )

w w

w

.jn

fo

ru m

.c om

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

ld or

tu

w

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


Conversion Specifiers

.c om

ru m

fo

ld

or

w

tu

.jn

w

%hd %ld %lf %%

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

w w

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


Back Slash ( Escape Sequence) Characters

.jn

.c om

tu

w

or

ld

fo

ru m

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

w

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

Meaning

w w

Code


Increment and Decrement Operators prefix increment (++a)

postfix increment (a++)

Executes all Prefix Operations

prefix decrement(decrement(- -a)

postfix decrement (a(a- -)

.c om

Before evaluation of expression

ru m

Evaluation of expression

After evaluation of expression and before leaving the statement

.jn

tu

w

or

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

w w

w

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

ld

fo

Executes all Postfix Operations

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


Bitwise Logical Operators B

A& B

| -- Bitwise OR

1

1

1

1

0

0

^ -- Bitwise XOR

0

1

0

~ -- Bitwise NOT

0

0

w w

fo

w

.jn

or w

tu

A (42) : 00000000 00101010 B (15) : 00000000 00001111 ----------------------------------& (10) : 00000000 00001010 -----------------------------------

Bitwise XOR

0

ld

Bitwise AND

A (42) : 00000000 00101010 B (15) : 00000000 00001111 ----------------------------------& (37) : 00000000 00100101 -----------------------------------

A| B

A^ B

~A

1

0

0

1

1

0

1

1

1

0

0

1

.c om

A

ru m

& -- Bitwise AND

Bitwise OR A (42) : 00000000 00101010 B (15) : 00000000 00001111 ----------------------------------| (47) : 00000000 00101111 ----------------------------------Bitwise NOT A (42) : 00000000 00101010 ----------------------------------~ ((-43) : 11111111 11010101 -----------------------------------


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

1.bool

w

2.char

(forcible)

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

. . .

.jn

(forcible)

(natural)

Gravity

w w

w

. . .

Explicit Type Conversion (casting)

or

ld

TYPE CONVERSION

tu

Opposite To Gravity

fo

ru m

.c om

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

Bitwise Left Shift ( << )

7.float 8.double 9.long double

(automatic)

Implicit Type Conversion (automatic)


Precedence and Associativity of Operators

Comma

Associativity

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

L R R L L R L R L R L R L R L R L R L R L R L R R L R L

.jn

tu

w

or

ld

fo

ru m

.c om

Operators

w

w w

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

L R


Test Expression ?

True

True

True StatementStatement-block

TrueTrue-block Statements

FalseFalse-block Statements

Next statement

w w

w

.jn

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

or

tu

w

/* check a citizen is eligible for voting */ #include<stdio.h> int main() { int age; printf(“Enter the age : ”); scanf(“%d”,&age); if(age >= 18) printf(“Eligible for voting…”); getch(); }

ld

fo

Next statement

False

Test Expression ?

.c om

False

Entry

if if--else:

Entry

ru m

simple if:


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

False

Test condition1 ?

.jn

w

Next statement

tu

w

or

Statement Statement--2

w w

Statement Statement--3

ld

fo

False

ru m

Entry

.c om

nested if‌else:


Entry

True

ru m

Test condition1 ?

Statement Statement--1

fo

False Statement Statement--2

tu

True

w

.jn

Statement Statement--N

Next statement

w w

Test conditionN ?

w

False

ld

True

or

Test condition2 ?

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

.c om

if‌else‌if :


switch statement :

value2

valueN ‌‌... associate statement

w

.jn

tu

w

or

associate statement

Exit

w w

associate statement

fo

value1

ld

switch expression ?

ru m

.c om

Entry

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

Next statement


Loop Statements

dodo-while – (Exit controlled )

while – (Entry controlled ) Entry

.c om

Test Condition ? true

Entry

False

ru m

Body of The loop

fo

Body of The loop

w w

or w tu .jn

w

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

ld

Following Statement

Test Condition ? True

False Following Statement

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


for -- Statement

Entry

Initialization Statement Test Condition ? True

ru m

False

.c om

Increment Statement

Body of The loop

fo

Following Statement

w w

w

.jn

tu

w

or

ld

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


Important Functions in math.h

.c om

ru m

fo

ld

or

w

tu

.jn

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

w

floor(x)

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

w w

abs(x) ceil(x)


.c om

www.alljntuworld.in

w w

w

.jn

tu

w

or

ld

fo

ru m

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.P PHARMACY, MBA, MCA of JNTUHYD,JNTU-KAKINADA & JNTUANANTAPUR visit www.alljntuworld.in


Modularizing and Reusing of code through Functions

w w

w

.jn

tu

w

ru m

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

fo

or

ld

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

.c om

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.


fo

ru m

.c om

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 data. A Called Function receives control from a Calling Function. When the called function completes its task, it returns control to the calling function. It may or may not return a value to the caller. The function main() is called by the operating system; main() calls other functions. When main() is complete, control returns to the operating system.

ld

or

w

float calcInterest(float loan , int terms , float iRate ) { The block is float interest; executed interest = ( loan * terms * iRate )/100; return ( interest ); }

w w

w

.jn

tu

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

value of ‘p’ is copied to loan’ value of ‘n’ is copied to terms’ value of ‘r’ is copied to ‘iRate’

Called Function

value of ‘interest’ is assigned to ‘si ’

Calling Function

Process of Execution for a Function Call


.c om ru m

1 3

7

fo

2

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

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

or

ld

8

w

6

w w

w

.jn

tu

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

5

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

Flow of Control in Multi-Function Program


Function-It’s Terminology

/* Program demonstrates function calls */ #include<stdio.h> int add ( int n1, int n2 ) ; int main(void) { int a, b, sum; printf(“Enter two integers : ”); scanf(“%d %d”, &a, &b);

.c om

Declaration (proto type) of Function

fo

ru m

Formal Parameters

or

ld

sum = add ( a , b ) ; printf(“%d + %d = %d\n”, a, b, sum); return 0;

Function Name

tu

w

}

Function Call

Actual Arguments

Return Type

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

)

w

add ( int x , int y

w w

int {

.jn

/* adds two numbers and return the sum */ Definition of Function Parameter List used in the Function

Return statement of the Function Return Value


Categories of Functions

ru m

.c om

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

or

ld

fo

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

.jn

tu

w

/* using different functions */ int main() { float radius, area; printMyLine(); printf(“\n\tUsage of functions\n”); printYourLine(‘-’,35); radius = readRadius(); area = calcArea ( radius ); printf(“Area of Circle = %f”, area); }

w w

w

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

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


void area() { static int num = 0;

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

}

ld

fo

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

or

w

tu

.jn

w

w w

ru m

.c om

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

External Global Variables Visible across multiple Scope: functions Lifetime: exists till the end of the program. Enter length, breadth : 6 4 Area of Rectangle 1 : 24.00 Perimeter of Rectangle 1 : 20.00 Enter length, breadth : 8 5 Area of Rectangle 2 : 40.00 Perimeter of Rectangle 1 : 26.00

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

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

Storage Classes – Scope & Lifetime


File2.c

File1.c

w w

w

.jn

tu

w

.c om

ru m

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

fo

or

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

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

ld

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

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

Storage Classes – Scope & Lifetime


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

Preprocessor Directives

A function

.c om

ru m

fo

showSquares(1)

w w

w

showSquares(2)

showSquares(3)

showSquares(4)

execution of function calls in reverse

showSquares(5) main()

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

ld or w .jn

tu

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

#define #undef #ifdef #ifndef

calling itself is Recursion

call-stack

Preprocessor is a program that processes the source code before it passes through the compiler.


w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


ld

fo

ru m

score0 score1 score2 score3 . . score59

.jn

w

w w

.c om

Array & its Advantage scores[0] scores[1] scores[2] scores[3] . . scores[59]

Sixty variables are replaced by one Array

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

or w

tu

/* Ranking of 60 students in a class */ int main() { /*declaring 60 varialbes */ int score0, score1,score2,……,score59; /* Reading scores for sixty times */ printf(“Enter the score : “); scanf(“%d”, &score0); …. …. …. …. printf(“Enter the score : “); scanf(“%d”, &score59); /* comparing & swapping for 1770 times * to arrange in descending order */ swap( score0, score1); swap( score1, score2); swap( score2, score3); …. …. …. …. swap( score0,score1); swap( score1,score2); swap( score0,score1); /*printing 60 scores after sorting */ printf(“%4d”, score0); printf(“%4d”, score1); … … … … } void swap ( int a, int b) { int temp; if( a < b) { temp = a ; a = b ; b = temp; } }


skyups media

4023

4025

4024

start here

scores[2]

scores[3]

4027

4026

4028

scores Array

scores[4]

.c om

4022

scores[1]

4029

4030

... 4031

( memory addresses)

ru m

scores[0]

or

ld

fo

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

w w

w

.jn

tu

w

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

}

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


.c om

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

w w

w

.jn

tu

w

or

ld

fo

ru m

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


.c om

Elements of Array [3] by [4]

ld

or

w

tu

.jn

w

w w

[0][1]

[0][2]

[0][3]

[1][0]

[1][1]

[1][2]

[1][3]

[2][0]

[2][1]

[2][2]

[2][3]

ru m

[0][0]

/*passing an array to function */ #define SIZE 10 int main() { float list[SIZE] ,avg; …………… avg = average(SIZE , list ); …………… } float average( int n , float x[]) { float sum=0,i; for( i = 0; i < n ; i++) sum = sum + x[i]; return ( sum / n ) ; }

fo

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


Strings - One Dimensional Character Arrays A String is sequence of characters. In ‘C’ strings are implemented by an array of characters terminated with a null character ‘\0’(back slash followed by zero ).

a

v

i

K

i

.c om

R

char name[] = “Ravi Kiran”;

r

a

n

\0

ru m

name ‘name’ is an array of characters has size of eleven characters including a null character ‘\0’(ascii code is zero).

w

or

ld

fo

char name[25] ; scanf(“%s”, name); /*reading a string until a white space is encountered ( & operator is not required )*/ printf(“%s”, name); /*printing a string in input window */ gets(name) ; /* reading a string including white spaces until ‘\n’ is encountered. */ puts(name); /* printing a string and moves cursor to new line */

w w

w

.jn

tu

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


.c om

Memory Address : Bit is a smallest unit of memory to store either ‘0’ or ‘1’ in memory. Byte is unit of memory of 8 bits. Memory is a sequence of a large number of memory locations , each of which has an address known as byte. Every byte in memory has a sequential address number to recognized by processor.

Memory Sections of C-Runtime

w w

w

.jn

tu

w

or

ld

fo

ru m

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


Two or more Permanent Manipulations using one Function Passing Parameters By Reference

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

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

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

Passing Parameters By Value

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

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


Pointer variable – A variable holds the address of another variable Value in ‘option’

Allots some memory location 4042 (for example) with a name option and stores value ‘Y’ in it

.c om

char option = ‘Y’;

ru m

Memory Address of variable ‘option’

ld

char *ptr = NULL;

ptr

or

w

Memory address of Variable ‘option’ Is copied to the Pointer ‘ptr’

4042 ptr

w w

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

‘Y’ option 4042

w

.jn

tu

ptr = &option;

*ptr = ‘N’;

4042

fo

Creates a pointer variable with a name ‘ptr’ Which can hold a Memory address

‘Y’ option

4042 ptr

‘N’ option 4042


Program with Using Pointers

ru m

Prints address of n1

ld

Prints 6 3

or

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

fo

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

p

n1

NULL

6

n2

3

q

p

n1

q NULL

6

p

n2

3

q

.jn

tu

w

pointer ‘q’ assigned with pointer ‘q’ p = q; printf (“ %d %d “, *p , *q ) ;

n2

n1

.c om

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

Prints 3 3

}

w w

w

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

Prints 7 7

n1 p

6

n2

7

q

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

.c om

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.

w w

w

q = p; printf("%d %d",*p,*q); b = a; /* error */ }

fo

ld

or

tu

.jn

Prints 12 12

Pointer is an address variable, having no initialized value by default. The address stored in the pointer can be changed time to time in the program.

w

Prints 12 12

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

ru m

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

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


Pointer Arithmetic and Arrays

Prints 12 31 56

w

or

ld

fo

ru m

.c om

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

12

p - 1

arr[1] or *( arr + 1 )

31

p

56

p +1

arr[3] or *( arr + 3 )

19

p +2

arr[4] or *( arr + 4 )

42

p +3

.jn

tu

arr[0] or *( arr + 0 )

w w

w

arr[2] or *( arr + 2 )

Subscript operator [ ] used to access an element of array implements address arithmetic, like pointer.


Array of Pointers

.c om

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

pa

ppa

25

fo

4024

4056

4024

4056

4078

w

or

ld

a

tu

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

ru m

Pointer to Pointer ( Double indirection )

a[0][1]

a[0][2]

a[1][0]

w w

a[0][0]

w

.jn

Two Dimensional Array -- Pointers

base_address

a[1][1]

a[1][2]

a[2][0]

a[2][1]

a[2][2]

a[3][0]

a[3][1]

Array name contains base address

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

a[3][2]


Function Pointers

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

.c om

ru m

fo

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

ld

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

w w

w

.jn

tu

w

or

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

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

Output : x contains 7 y contains 23.500000

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


Dynamic Memory Allocation (DMA) of pointers

.c om

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 ;

ru m

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.

}

w w

free ( p ); p = NULL;

w

.jn

tu

w

or

ld

fo

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

}; struct book b1 ; b1 *ptr ; ptr = (book *) calloc ( 10, sizeof ( book ) ); ptr = (book * ) realloc ( ptr , 35 * sizeof ( book ) ); Modifies the size of previously allocated memory to new size.


Standard Character Functions Classification of Characters

File Name : cmdline.c

.jn

tu

w

}

w

lower islower ()

Other character functions in <ctype.h>

w w

for ( i = 1; i < argc ; i++ ) printf(“\nUser value %d : %s “, i , argv [ i ] );

or

digit isdigit ()

ru m

punctuation ispunct ( )

fo

alpha-numeric isalnum ( )

upper isupper ( )

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

graphical isgraph ()

space isspace ( )

alphabetic isalpha( )

.c om

printable isprint ( )

ld

control iscntrl ( )

Command Line Arguments

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

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


Standard C-Library Functions <stdlib.h> Converts string s to an integer

long atol(s)

Converts string s to a long integer.

float atof(s)

Converts string s to a double-precision quantity.

void* calloc(u1,u2)

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

void exit(u)

Closes all files and buffers, and terminate the program.

void free (p)

Free block of memory.

void* malloc (u)

Allocate u bytes of memory.

int rand(void)

Return a random positive integer.

void* realloc(p,u)

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

void srand(u)

Initialize the random number generator.

void systerm(s)

Pass command string to the operating system.

.jn

tu

w

or

ld

fo

ru m

.c om

int atoi(s)

Returns clock ticks since program starts.

w

clock_t clock()

<time.h>

Converts date and time into ascii.

int stime(time_t *tp)

Sets time.

w w

char *asctime(stuct tm)

time_t time(time_t *timer)

Gets time of day.

double difftime(t1,t2)

Returns difference time between two times t1 and t2.


C Data Types: Primary data types Derived data types User-defined data types

.c om ru m

Pointer Type

Array Type

Structure Type

Union Type

ld

fo

Function Type

Derived Types

.jn

tu

w

or

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

w w

w

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


book

book_id title

title

price

fo

integer

float

40 bytes

2 bytes 4 bytes

w

or

price

Array of 40 characters

ld

pages

pages

50 bytes

Array of 50 characters

author

author

2 bytes

ru m

bookid

integer

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

.c om

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

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

tu

Memory occupied by a Structure variable

w w

w

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

.jn

STRUCTURE- BOOK

Structure tag

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


Declaring a Structure Variable

Declaring a Structure Type

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

fo

ru m

.c om

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

ld

Initialization of structure

w w

w

.jn

tu

w

or

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

membership operator

Reading values to members at runtime: struct student s3; printf(“\nEnter the roll no”); scanf(“%d”,&s3.roll_no); printf(“\nEnter the name”); scanf(“%s”,s3.name); printf(“\nEnter the percentage”); scanf(“%f”,&s3.percentage);


Declaration of Structure Type

ru m

Declaration of Structure variables Declaration and initialization of Structure variable

fo

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

.c om

Implementing a Structure

w w

w

.jn

tu

w

or

ld

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


Arrays And structures

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

w w

w

.jn

tu

w

fo

or

ld

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

ru m

.c om

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

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


Self referential structures

structures and functions struct fraction { int numerator ; int denominator ; };

.c om

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

fo

ru m

void show ( struct fraction f ) { printf ( “ %d / %d “, f.numerator, f.denominator ) ; }

ld

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

or

s1. next = & s2 ;

w

printf ( “ %s “, s1. name ) ;

tu

OUTPUT:

Prints P.Kiran

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

Prints B.Mahesh

}

w w

w

.jn

7 / 12

s2 node is linked to s1 node

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


Pointer to a structure

.c om

Accessing structure members through pointer :

ru m

i) Using . ( dot ) operator : ( *ptr ) . prodid = 111 ; strcpy ( ( *ptr ) . Name, “Pen”) ; ii) Using - > ( arrow ) operator : ptr - > prodid = 111 ; strcpy( ptr - > name , “Pencil”) ;

w w

w

.jn

tu

w

or

ld

fo

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

Read Product Details :

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


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

5001

5002

5003

5004

w w

5005

5006

or

ld

fo

Address 5000

ru m

Memory allotted to structure student

.jn

tu

w

avg rollno Total memory occupied : 7 bytes

Address

Memory allotted to union pupil 5000

5001

5002

5003

w

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

.c om

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

rollno avg grade Total memory occupied : 4 bytes

grade


.c om

www.alljntuworld.in

w w

w

.jn

tu

w

or

ld

fo

ru m

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-K KAKINADA & JNTU-ANANTAPUR visit www.alljntuworld.in


.c om

INTRODUCTION:

ru m

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

ld

fo

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

w

or

main()

rno

tu

{ struct student

.jn w w

int rno;

char gender; int age;

1

2

w

{

gender

ht

age 2

4

wt 4

13 bytes of memory is allocated in s1


13 bytes of memory is allocated to s2

2

ru m

float wt;

.c om

age

float ht;

};

age

2

1 ht

4

wt 4

ld

fo

struct student s1,s2;

gender

w

or

}

w

.jn

tu

When all these data items are grouped under on single variable name, we can get some meaningful information.

w w

struct is a keyword used to create a new user defined data type. In some other high level programming languages the structures are named as records


.c om

DEFINING A STRUCTURE: syntax:

fo

{

ru m

struct user defined datatype

or

ld

datatype member1;

tu

w

datatype member2;

.jn

…………….

w w

w

…………

datatype membern: };

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


.c om

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

ru m

An user defined data type name may be any valid ‘c’ identifier ( user defined name).

ld

fo

The data type may be a valid simple data type or compound data type.

tu

w

or

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

.jn

The variable rno, age, gender, ht, wt, are the structure members.

w w

w

All these structure members must be enclosed within a pair of curly braces. The structure definition should be terminated with semicolon.


.c om

DECLARING STRUCTURE VARIABLE:

ru m

Once a new user defined datatype is created by using the keyboard struct then we can create any no. of structure variables of that type.

ld

fo

syntax:

or

struct user defined_data type name

tu

w

structure var1, structure var2,……….. Struct varn;

w

.jn

Above statement is called declarative statement of structure variables and it allocates memory space to these variables.

w w

We can also declare structure variables immediately after structure definition.


.

.c om

ACCESSING STRUCTURE MEMBERS: Structure member accessing operator

ru m

s1.wt=60.2;

or

ld

S1.ht=5.5;

tu

w

Structure S1.rno=100 variable Structure member

fo

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

w w

w

.jn

•Two operators are used to access member of structure. The structure member operator(.) also called dot operator and the structure pointer operator ( ) also called the arrow operator. •The structure member operator accesses a structure member via structure variable name.


syntax:

.c om

Ex: s1.rno, s1.age, s1.gender, s1.ht, s1.wt S1.rno=100; s1.gender=M; s1.age=25; s1.ht=5.5; s1.wt=60.2

s2

rno 100

fo

gender

ld

wt

or

ht 5.5

rno

age

ht

wt

60.2

.jn

tu

25

gender M

w

age

ru m

s1

w

ASSIGNING VALUES TO STRUCTURE MEMBERS:

w w

By using the assignment operator(=) we can assign values to all structure members of a structure variable. Syntax: structure variable.member = value; Ex: s1.rno= 100; s1.age=25


INITIALIZING A STRUCTURE VARIABLE:

ru m

.c om

Structures can be initialized using initialize lists as with arrays. To initialize a structure follow the variable name in the structure declaration with an equal sign and brace enclosed comma separated list of initializes.

tu

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

w

int x = 10;

or

ld

fo

Ex: struct student s1={100, 25,’M’, 5.5,65.2};

.jn

READING AND DISPLAYING THE STRUCTURE VARIABLES:

w w

w

The ‘C’ will not read or write an entire structure as a single command. It will read or write the members of a structure as follows: ex: scanf(“ %d, %d, %c, %f” ,&s1.rno,&s1.age,&s1.gender,&s1.ht); printf(“ %d %d %c %f”, s1.rno, s1.age, s1.gender, s1.ht);


PROGRAM USING STRUCTURES:

#include<conio.h>

ld

fo

void main()

ru m

.c om

Reads the details of 2 students and calculate total and average marks of 2 students. #include<stdio.h>

or

{ /* defining a structure */

tu

w

struct student

w w

w

.jn

{ int rno; char name[30]; float m1,m2,m3; float tot, avg; };


struct student s1,s2; (1st executed) /* 3.reading 1st student details*/

.c om

/* 2. declaration of structure var*/

ru m

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

ld

fo

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

w

or

/* 4. reading 2nd student details*/

.jn

tu

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

w w

w

scanf(“ %d %s%f %f %f”, &s2.rno, &s2.name,&s2.m1,&s2.m2,&s2.m3); /* calculate total and avg of first student marks*/ s1.tot= s1.m1+s1.m2+s1.m3; s1.avg = s1.tot/3;


or

ld

fo

ru m

.c om

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

w

/* 8. displaying second student details*/

w w

w

.jn

tu

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


Array of Structures:

.c om

Perhaps the most common usage of structures is an array of structures.

ru m

->To declare an array of structures you must first define a structure and then declare an array variable of that type.

ld

fo

For example to declare a 100 element array of structures of type “student� write

or

struct student

tu

w

{

.jn

int rno;

w w

w

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

struct student s[100];-Structure Variable Declaration


DEMONSTRATING ARRAY OF STRUCTURES:

.c om

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

ru m

void main()

fo

{

or

ld

/*1.Defining an array of structures*/

w

struct student

w

int rno;

.jn

tu

{

w w

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


/*2.Creating an array of Structures*/

.c om

struct student s[100]; int i,n;

printf(“Enter n value\n”);

or

ld

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

fo

ru m

clrscr();

tu

w

scanf(“%d”,&n);

{

w

w w

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

.jn

/*4.Reading student details*/

printf(“Enter details of %d student\n”,i+1); scanf(“%d”,&s[i].rno);


scanf(“%d%d%d”,&s[i].m1,&s[i].m1,&s[i].m2,&s[i].m3);

.c om

/*5.Calculate tot,avg marks */ for(i=0;i<n;i++)

ru m

{

fo

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

or

ld

s[i].avg=s[i].tot/3;

w

}

w

{

w w

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

.jn

tu

/*6.Display the student details*/

printf(“The following are the %d student details\n”,i+1); printf(“Rollno:%d\n”,s[i].rno);


.c om

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

ru m

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

or

ld

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

fo

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

w

}

w w

w

.jn

tu

}


Arrays with in Structures:

ru m

.c om

A member of a structure may be either a simple or compound type.A simple member is one that is of any of the built-in datatypes such as integer or character.

ld

or

For example consider this Structure:

fo

->The compound datatypes include one dimensional and multidimensional arrays of other datatypes and structures.

w

struct x

.jn

tu

{

w

int rno;

w w

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


Nested Structures:

.c om

when a structure variable is a member of another structure, it is called a Nested structure.

w w

w

.jn

fo ld or

tu

w

Member to another structure. EX:struct Test { int a; int b; }; Struct Exam { int x; int y; struct Test z; };

ru m

->In the below example structure variable ‘z’ is declared as structure


Structures and Function:

ru m

.c om

A Structure can be passed to a function as a one variable or as an individual member. The scope of a structure declaration should be external storage class whenever a function in the main(). Program Using a Structure datatype:

ld

fo

#include<stdio.h>

or

/*Defining a Structure*/

tu

w

struct Test

int b; }; /*Prototype*/

w w w

int a;

.jn

{


struct Test Modify(struct Test s2);

.c om

void main() {

ru m

struct Test T1={10,20};

fo

T1=Modify(T1);

or

ld

printf(“After calling modify\n”);

w

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

.jn

tu

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

w

}

{

w w

Stuct Test Modify(struct Test s2)

s2.a=s2.a+10;


.c om

S2.b=s2.b+10; return s2;

fo

20

ld

10 1 200

or

b

a 10

w

a

ru m

}

w w

w

.jn

tu

30

10+10 =20

b 20 20+10

=30


Union:

ru m

.c om

Union is another datatype with two or more members,similar to structure.But in this case all the members share a common memory location.The members of a union can be refered by using dot operator as in the case of structure.

ld

fo

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

tu

w

or

The size of union corresponds to the length of the longest member.

.jn

Syntax:

{

w w

w

Union Userdefined_datatype

datatype member 1; datatype member n;};


.c om

Union Test {

ru m

char a;

fo

int b;

ld

float c;

w

or

};

w w

w

.jn

tu

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


.c om

ru m

FILE HANDLING IN ‘C’

Low level

Formatted

w

w w

Text

.jn

tu

w

or

High level

ld

fo

Disk I/O functions

Un formatted

Binary formatted

Un formatted


.c om

This works fine as long as the data is small.However, many real life problems involve large volumes of data and in such situations, the console oriented I/O operations pose two major problems.

ru m

1. It becomes cumbersome and time consuming to handle large volumes of data through terminals.

w

It is therefore necessary to have a more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data.

w

.jn

tu

o

or

ld

fo

2. The entire data is lost when either the program is terminated or computer is turned off.

w w

o The method employs the concept of files to store data. A file is place on the disk where a group of related data is stored.


.c om

Like most other languages, c supports a number of functions that have the ability to perform basic file operations, which include.

w

or

ld

fo

ru m

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

w w

w

.jn

tu

There are two distinct ways to perform file operations. --The first one is known as the low level I/O and uses UNIX system calls. --The second method is referred to as the high level operation and uses functions in c standard I/O library.


ru m

fopen () creates a new file for use.

.c om

HIGH LEVEL I/O FUNCTIONS

Opens an existing file for use.

ld

fo

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

or

getc() reads a character from a file .

tu

w

putc() writes a character to a file.

.jn

fprintf() writes a set of data values to a file.

w w

w

fscanf() reads a set of data value from a file. getw() reads an integer from a file.


putw() writes an integer to a file.

.c om

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

ru m

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

w

or

ld

fo

DEFINING AND OPENING A FILE: If we want to store data in a file in the secondary memory, we must specify certain thing about a file to operating system they are

tu

1.File name 2. data structure 3. purpose

w

.jn

For file name general format of declaring and opening a file is

w w

FILE *fp; specifies the file name. fp= fopen (“ Filename”, “mode”); specifies the purpose of file.


The mode does this job. Mode can be one of the following

w: opens the text file for writing only.

.c om

r: opens the text file for reading only.

ru m

a : open the file for appending data to it.

fo

r+: the existing file is opened for both reading and writing.

w

or

ld

w+ : this mode allow you to open a file as text file for reading as well as writing a data to a file.

.jn

tu

a+ : this mode allows you to open a file as a text file for both reading and writing to a file.

w w

w

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


.c om

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

ru m

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

ld

fo

ab: this mode allows to open a file as a binary file for appending data at the end of the file.

tu

w

or

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

w

.jn

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

w w

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


FILE *P1, *P2;

ru m

P1= fopen (“data.c”, “r”);

.c om

Example:

fo

P2= fopen (“result.c”, “w”);

ld

CLOSING A FILE:

w

.jn

tu

w

or

A file must be closed as soon as all operations on it have been completed. This ensures that all outstanding information associated with the file is flushed out from the buffer and all links to a file are broken.

w w

Syn: fclose ( file pointer); fclose (P1);


.c om

getc() and putc():

w w

w

.jn

tu

w

or

ld

fo

ru m

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


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

.c om

#include<stdio.h>

char ch;

fo

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

or w

while(1)

.jn

tu

{ ch=getc (fp);

noc++;

w

if ( ch== EOF) break;

ld

fp=fopen(“pri.c”, “r”);

w w

{

ru m

Void main()


if ( ch==‘ ‘)

.c om

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

ru m

not++;

fo

If ( ch==‘\n’)

or

ld

nol++;

tu

w

}

.jn

fclose (fp);

w w

w

printf (“ number of characters = %d”, noc); printf (“ number of blanks= %d \n”, nos); printf (“ number of tabs=%d \n” , not);


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

.c om

getch();

ru m

}

fo

OUTPUT:

or

ld

number of characters =125

tu

w

number of blanks =25

.jn

number of tabs =13

w w

w

number of lines =22


.c om

putw() and getw():

ru m

The putw() function is an output function and is used to write an integer into a file. Syntax: putw( integer, file pointer)

or

ld

fo

ex: putw (x,pf);

.jn

tu

w

The getw() function is an input function and is used to read an integer from a file.

w

Syntax: integervar =getw( file pointer);

w w

ex: x= getw(fp);


Program for demonstrating putw() and getw() function

.c om

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

ru m

Void main()

fo

{

or

ld

FILE *f;

w

int word1, word2;

w w

{

w

if(fp==NULL)

.jn

tu

fp=fopen ( “ number.c”, “w”);

printf (“ error opening file”);


exit(1);

.c om

} word1=94;

ru m

putw(word1,fp);

or

ld

printf(“ error writing to file \n”);

fo

if ( ferror(fp))

w

else

w

fclose(fp);

.jn

tu

printf( “ sucessful write \n” );

w w

/* reopen the file */

fp= fopen( “number.c”, “r”);


if ( fp== NULL)

.c om

{ printf(“ error opening file “);

ru m

exit(1);

fo

}

or

ld

/*extract the word */

w

Word =getw (fp);

.jn

tu

if (ferror (fp))

w w

else

w

printf(“ error reading file \n”);

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


/* clean up*/

.c om

fclose (fp);

ru m

return 0;

ld

fo

}

or

word1 94

tu w w

w

.jn

94 getw

Successfully wrote

w

Number file

word2 94

Successful read pf f()


fprintf() and fscanf() functions:

ru m

Syntax: fprintf( fp, “ control string “, list);

.c om

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

fo

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

or

ld

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

w

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

w

#include<stdio.h>

.jn

tu

Demonstrating frpintf () and fscanf() functions:

Void main()

w w

#include<conio.h>


{

.c om

FILE *fp; int rno;

or

fp=fopen(“ student.c”, “w”);

ld

float marks;

fo

ru m

char name[30];

tu

w

printf( “ enter student record \n”);

.jn

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

w w

w

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

fp= fopen(“ student.c”, “r”);


.c om

printf(“ the student record \n”); fscanf (fp, “%d %s %f”, &rno, name, &marks);

ru m

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

fo

fclose (fp);

scanf()

or

ld

}

w

H.D

Enter students

student

rno name marks 1 ravi 30.5

1.Ravi 30.5

w w

w

1. Ravi 30.5

.jn

tu

fprintf()

1 ravi 30.5 fscanf()

prinf()


RANDOM ACCESS TO FILES:

.c om

Sometimes it is required to access only a particular part of the file and not the complete file.

ru m

This can be accomplished by using following function.

or

ld

fo

fseek(): it is a file function. It positions file pointer on the stream. We can pass three arguments through this function.

tu

w

The general format of fseek function is as follows:

.jn

fseek( file pointer, offset, position);

w w

w

This function is used to move the file position to a desired location within the file.


1. Fileptr is a pointer to the file concerned.

.c om

2. Offset is a number or variable type long. 3. Position in an integer number.

or

ld

fo

ru m

Offset specifies the number of positions (bytes) to be moved from the location specified at position. integer Constant Location in file value

SEEK_SET Beginning of file

1

SEEK_CUR Current position of file

2

SEEK_END End of file

w w

w

.jn

tu

w

0

Ex: fseek(fp,10,0) or fseek(fp, 10,SEEK_SET) filepointer is repositioned in forward direction by 10 bytes


.c om

Program to read the text file containing some sentence. Using fseek() and read the text after skipping ‘n’ character from beginning of file. Void main()

ru m

{

fo

FILE *fp;

or

ld

int n, ch;

tu

w

clrscr();

.jn

fp=fopen( “ text.txt”, “r”);

w w

w

printf( “\n contents of file \n”); while ((ch=fgetc(fp))!=EOF) printf(“ %c”, ch);


.c om

printf( “ \n how many characters including spaces would you like to skip?”); scanf(“%d”, &n);

ru m

fseek ( fp, n, SEEK_SET)

or

ld

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

fo

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

w

printf(“%c”, ch);

.jn

tu

fclose(fp);

w w

w

}


bitfieds

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

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

.jn

tu

w

or

ld

fo

ru m

.c om

typedef – to define new datatype

w w

w

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


Enumeration – a set of named integers, makes program more readable

w w

w

.jn

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

ld or

tu

w

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

fo

ru m

.c om

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


Console I / O Vs File I / O

or

ld

fo

ru m

.c om

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

w

File Operations

w w

w

.jn

tu

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

1. 2. 3. 4. 5.

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


.c om

ru m

A Stream acts as an interface between a program and an input/output Device.

.jn

tu

w

or

ld

fo

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

w w

w

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


Steps involved using files

.c om

1. Declaring FILE pointer variable : Syntax : FILE *file_pointer1;

fo

ru m

2. Open a file using fopen() function : Syntax : fp= fopen(“filename”,“mode of access”); 3. fputc() – Used to write a character to the file. Syntax : fputc(character, file_pointer);

w w

w

.jn

tu

w

or

ld

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

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


file pointer used to handle files

.c om

filepointer=fopen(“filename”,”mode”);

w

.jn

tu

w

ld

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

w w

fclose(filepointer);

fo

ru m

putc(character,filepointer);

or

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

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


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

.c om

r -- open a file in read mode -- if file exits, the marker is positioned at beginning. -- if file does not exist, error returned.

ld

fo

ru m

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

or

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

w w

w

.jn

tu

w

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

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


File Input / Output Functions Open existing file / Create new file

fclose(fp)

Closes a file associated with file pointer.

closeall ( )

Closes all opened files with fopen()

fgetc(ch, fp)

Reads character from current position and advances the pointer to next character.

fprintf( )

Writes all types of data values to the file.

fscanf()

Reads all types of data values from a file.

gets()

Reads string from a file.

puts()

Writes string to a file.

getw()

Reads integer from a file.

putw()

Writes integer to a file.

fread()

Reads structured data written by fwrite() function

fwrite()

Writes block of structured data to the file.

fseek()

Sets the pointer position anywhere in the file

feof()

Detects the end of file.

ru m

fo

ld

or

w

tu

.jn

w

w w

rewind()

.c om

fopen(fp, mode)

Sets the record pointer at the beginning of the file.

ferror()

Reports error occurred while read/write operations

fflush()

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

ftell()

Returns the current pointer position.


Text files Vs Binary Files “rb”

/* Copying one binary file to other */

“ab”

open a file in append mode

ru m

“rb+” open a pre-existing file in read and write mode “wb+” open a file in read and write mode

fo

“ab+” open a file in read and append mode

ld

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

or

tu

.jn

w

w w

.c om

“wb” open a file in write mode

w

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

open a file in read mode


Random Access File

w w

w

.jn

tu

w

or

ld

.c om

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

ru m

fo

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

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


w w

w

.jn

tu

w

ru m

fo

or

ld

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

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

.c om

Formatted I / O


fputc()

fgetc()

fputs() fwrite()

.c om

Standard I / O

write()

fgets()

Character Strings

fscanf()

Formatted ASCII

fread()

Binary files

read()

Low-level binary

ld

fo

ru m

fprintf()

Individual characters

Predefined Streams

w w

w

.jn

tu

w

or

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

NAME

MEANING

stdin

Standard input (from keyboard)

stdout

Standard output (to monitor)

stderr

Standard error output (to monitor)

stdaux

Standard auxiliary (both input and output)

stdprn

Standard printer output(to printer)


Handling Records (structures) in a File

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


Error Handling:

ld

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

or

feof(fp) returns non-zero integer value if we reach end of the file otherwise zero.

fo

ru m

.c om

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

.jn

tu

w

ferror(fp) returns non-zero integer value if an error has been detected otherwise zero

w w

w

perror(string) prints the string, a colon and an error message specified by the compiler file pointer (fp) will return NULL if it cannot open the specified file.


fp will return NULL if unable to open the file

or

ld

fo

ru m

.c om

feof(fp) returns 1 if it reaches end of file otherwise 0.

w w

w

.jn

tu

w

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

Output:

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


Structure of FILE pointer

.c om

ru m

remove(“filename") -- It removes the file specified (macro)

fo

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

.jn

w w

w

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

ld

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

or

tu

File status functions

rename(“old-filename",”new-filename"); -- It renames the file with the new name

w

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

File Management Functions

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


w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-KAKINADA & JNTU-ANANTAPUR visit www.alljntuworld.in


Searching techniques

Linear_Search (A[ ], N, val , pos ) Step 1 : Set pos = -1 and k = 0 Step 2 : Repeat while k < N Begin Step 3 : if A[ k ] = val Set pos = k print pos Goto step 5 End while Step 4 : print “Value is not present” Step 5 : Exit

w w

w

.jn

tu

w

or

ld

fo

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

ru m

.c om

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

Searches -- for each item one by one in the list from the first, until the match is found. Efficiency of Linear search : -- Executes in O ( n ) times where n is the number of elements in the list.


Binary Searching

w w

w

.jn

tu

w

fo

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

ld

or

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

ru m

.c om

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


Sorting

w

or

ld

fo

ru m

.c om

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

.jn

tu

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

w w

w

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

Types of Internal Sortings

Bubble Sort

Insertion Sort

Selection Sort

Quick Sort

Merge Sort


Bubble Sort

.c om

Bubbles up the highest

Sorted

54

54

54

54

54

47

10

47

47

47

47

12

47

10

23

23

54

12

23

10

19

tu

19

19

23

12

19

10

12

23

19

19

12

10

After Pass 3

After Pass 4

After Pass 5

After Pass 2

ld

or 23

w

.jn

w w

Original After List Pass 1

12

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

fo

10

w

ru m

Unsorted

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

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


.c om

Bubble Sort

ru m

For pass = 1 to N - 1

For J = 1 to N - pass

A[J–1]>A[J]

F

w w

w

.jn

tu

w

or

ld

fo

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

Return

T

Temp = A [ J – 1 ] A[J–1]=A[J] A [ J ] = Temp


Insertion Sort 23 45

8

32

36

23

78

45

8

32

36

23

45

78

8

32

36

8

23

45

78

32

36

23

w

or

8

23

32

8

23

32

78

36

45

78

w w

w

36

45

.jn

8

tu

32

36

Complexity of Insertion Sort Best Case : O ( n ) Average Case : O ( n2 ) Worst Case : O ( n2 )

ld

fo

45

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

.c om

78

ru m

TEMP

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


Selection Sort ( Select the smallest and Exchange ) 78 45

8

32

56

23

8

78

45

23

32

56

32

8

23

45

78

32

56

45

8

23

32

78

45

56

56

8

23

32

45

78

8

23

32

45

.c om

23

or

w tu

.jn

w

w w

56

Complexity of Selection Sort Best Case : O ( n2 ) Average Case : O ( n2 ) Worst Case : O ( n2 )

ld

fo

8

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

ru m

Smallest

56

78

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


Selection sort

.c om

Insertion sort

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

ru m

k = 1; k < n ; k++

pos = j

tu

.jn

w w

w

a [ j + 1 ] = temp

a[ j ] < a[ pos ]

w

or

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

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

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

ld

fo

temp = a [ k ] j=k-1

pos = k

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

return

return


Bubble sort – Insertion sort – Selection sort

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


Quick Sort – A recursive process of sorting Original-list of 11 elements :

2 11 5 14 0

2

9

4 20

Set list [ 0 ] as pivot : pivot

3

2 11 5 14 0

2

9

4 20

5

0

or

2

8

11 9 14 20

w

2

Apply Quick-sort recursively on sub-list

w

Sub-list of greater elements

w w

Sub-list of lesser elements

.jn

tu

3

ld

Rearrange ( partition ) the elements into two sub lists : pivot

4

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

fo

8

Algorithm for Quick_Sort :

.c om

3

ru m

8

Apply Quick-sort recursively on sub-list

Complexity of Quick Sort Best Case : O ( n log n ) Average Case : O ( n log n ) Worst Case : O ( n2 )


Partitioning for ‘ One Step of Quick Sort ’

3

1

25 10

3

16

1

25 10

8

16

1

25 10 12

1

8

16

3

1

8

12

8

16

12

8

ru m

16

w

or

3

8

ld

9

12

.c om

25 10

9

fo

1

w

Pivot

w w

.jn

3

tu

3

25 10 12 16 25 10 12


Quick Sort – Program

ld

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

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


B

A

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

F

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

Flag == 0

ru m

pivot <= a [ right ] && loc != right

fo

right = right - 1

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

w

.jn

w w

left = left + 1

B

flag = 1

a[ loc ] = pivot return loc

ld

tu

flag = 1

pivot >= a [ left ] &&loc != left

A

T

or

loc == right

w

F

T

loc == left

.c om

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

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

loc == left

T

loc = partition( a , beg , end ) quick_sort ( a , beg , end ) quick_sort ( a , beg , end ) return


Merge Sort ( Divide and conquer ) Divide the array

39

9

81

45

90 27 27

90

72 18 18

72

ld

39

90 27 72 18

81 45 81 45

9

.c om

9

81 45 90 27 72 18

ru m

39

9

fo

39

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

39

45

45 81

90

27

27 90

39 45 81 9

18

18 72

w w

9

18 27 72 90

18 27 39 45 72 81 90

Merge_sort Algorithm 1. If the list is of length 0 or 1, then it is already sorted. Otherwise: 2. Divide the unsorted list into two sublists of about half the size. 3. Sort each sublist recursively by re-applying merge sort. 4. Merge the two sublists back into one sorted list.

or

72

tu

9

81

.jn

9

w

39

w

Merge the elements to sorted array

Time complexity Worst case - O(n log n) Best case - O(nlogn) typical, O(n) natural variant Average case - O( n log n )


fo

ru m

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

tu

w

or

ld

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

.c om

Merge Sort - Program

w w

w

.jn

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


merge

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

F

a[ i ] < a[ j ]

ru m

T

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

low < high

T

mid = ( low + high ) / 2

merge_sort (a, low, mid)

ld

fo

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

merge_sort (a, mid, high )

w

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

or

i <= mid

Merge (a, low,high , mid)

.jn

j <= high

tu

F

.c om

i <= mid && j <= high

w w

w

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

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

Return


.c om

www.alljntuworld.in

w w

w

.jn

tu

w

or

ld

fo

ru m

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.PHARMACY, MBA, MCA of JNTUHYD,JNTU-K KAKINADA & JNTU-ANANTAPUR visit www.alljntuworld.in


Data Structures

or

w

Data Structure

ld

fo

ru m

.c om

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

Non-Linear

Stacks

Queues

w

Linear Lists

.jn

tu

Linear

Trees

w w

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

Graphs

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


Arrays – Linked Lists

w w

5)

w

.jn

4)

tu

w

.c om

ru m

or

3)

fo

2)

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

ld

1)

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

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


Creating a Singly Linked List /* deleting n2 node */ n1->next = n4; free(n2);

.c om

}

w

NULL

head

150

n1-node

720

102

ru m

101

fo ld

150

101

101

720

101

head

150 n1-node

400

102

NULL

720 n2-node

150 n1-node

102

910

720 n2-node

150 n1-node

150

.jn

tu

150

150

or

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

104 NULL 910 n3-node

104 NULL

720

400 n2-node

103

910

910 n3-node

w w

w

720 n4-node

150

101

head

150

103

720

n1-node

102

720

400 n2-node

910 720 n4-node

104 NULL 910 n3-node


Implementing Singly Linked List }

w w

w

.jn

tu

w

fo

ru m

.c om

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

ld

or

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


Implementing Singly Linked List ( continued ) if(temp!=NULL) { prev->next = temp->next; free(temp); }

.c om

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

w w

w

.jn

tu

w

ru m

fo ld

or

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

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


Implementing Singly Linked List ( continued )

ld

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

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

/* function to count number of node in the list */ int count ( struct node *h) { int i; for( i=0 ; h!=NULL ; h=h->next) i++; return i; }


Algorithm for adding two polynomials in linked lists

w w

w

.jn

tu

w

or

ld

fo

ru m

.c om

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


Doubly Linked List

.c om

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

head

tail

B

C

.jn

tu

A

w

or

ld

fo

ru m

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

w w

w

/* a node in doubly linked list */ struct node { struct node *prev; int data ; struct node *next; }

B

D

A C

Tree structure using Doubly Linked List


Insertion of node in Doubly Linked List

q

B C

q

fo

B

C

D

ld

A

ru m

p

D

.c om

A

B

C

p

w w

w

A

.jn

tu

w

or

Deletion of node in Doubly Linked List

D

A

B

C


Implementing Doubly Linked List

ld

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

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


Implementing Doubly Linked List ( continued )

ld

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

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


Implementing Doubly Linked List ( continued )

ld

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

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


101

Circular Singly Linked List

400

720

400 n2-node

910

104 150

720 n3-node

910 n4-node

103

910 tail

.c om

150 n1-node

102

or

ld

fo

ru m

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

data

next

prev

data

next

prev

data

next

prev

data

next

w

.jn

prev

tu

w

Circular Doubly Linked List

w w

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


Implementing Circular Singly Linked List

w w

w

.jn

tu

w

fo

ru m

.c om

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

ld

or

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


Implementing Circular Singly Linked List ( continued )

fo

ru m

.c om

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

w w

w

.jn

tu

w

or

ld

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


ru m

Types of Data Structures

w w

w

.jn

fo

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

ld or

tu

w

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

.c om

Implementing Circular Singly Linked List ( continued )


Stacks

ru m

.c om

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

w

.jn

fo or

tu

w

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

ld

Applications of stack

w w

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


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

Pop( ) Push(d) Push(e)

Pop( )

Pop( )

Pop( )

c

d

b

b

b

b

b

a

a

a

a

a

d

ru m

a

d

.c om

e b

b

a

a

a

Operation

ld

or

.jn

tu

w

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

w

w w

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

Stack’s contents

fo

Operations on Stack

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

Output

c c c ce ced cedb cedba

Pop( )


Implementing Stack ADT using Array

w w

w

.jn

fo

ru m

.c om

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

ld or w

tu

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


Implementing Stack ADT using Linked List

.c om

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

w w

w

.jn

tu

w

fo

ru m

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

ld

or

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


Queues

ld

rear

front

6

8

2

5

w

3

or

4

fo

ru m

.c om

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

delq ( )

7

w

.jn

tu

addq (4)

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

w w

Applications of Queues Execution of Threads Job Scheduling Event queuing Message Queueing

Types of Queues circular queues priority queues double-ended queues


Implementing Queue ADT using Array

}

.jn

w

w w

.c om

printf("\nElements are : \n"); for (i=front;i<=rear;i++) printf("%5d",queue[i]);

fo

ru m

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

ld or w

tu

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


Implementing Queue ADT using Liked List

.c om

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

w w

w

.jn

tu

w

fo

ru m

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

ld

or

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


ru m

.c om

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

Algorithm to Infix to Postfix Conversion

w w

w

.jn

tu

w

or

ld

fo

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


In-Fix To Post-Fix convertion

tu

w

or

ld

fo

ru m

.c om

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

w w

w

.jn

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

}


Evaluation of Post-Fix Expression

} } j++;

w

w w

.c om

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

ru m

} return pop();

fo

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

ld or w tu

.jn

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


.c om

ru m

fo

ld

or

w

tu

.jn

w

w w


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.