167
Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area Working Storage Area Primary or Main Memory (RAM) Register 1 Arithmetic Secondary Storage Devices Arithmetic and Logic Unit Register 2 …… …… Register N Micro Processor JNTU World www.alljntuworld.in JNTU World JNTU World

Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Computer -- Hardware

Key board

Mouse

Input Devices

Monitor

Printer

Output Devices

Input Storage

Area

Program Storage AreaOutput Storage

AreaWorking Storage Area

Primary or Main Memory (RAM)

Register 1Arithmetic

Secondary Storage Devices

Arithmeticand

Logic Unit

Register 2

……

……

Register N

Micro Processor

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 2: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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: STARTStep2: Take a number Step2: Read numStep3: if the number is divisible by2 then Step3: if(num%2=0) then

print that number is even print num is evenotherwise print that number is odd otherwise

print num is oddStep4: End Step4: STOP(Algorithm in natural language) (Algorithm by using pseudo code)

start#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)

start

read num

print num is even

stop

If If num%2=0num%2=0

print num is odd

Flow chart:Flow chart:

YesYes NoNo

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 3: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Flow chart symbolsOval Terminal

Parallegram Input/output

Rectangle Process

Document Hard copy

Diamond Decision

Circle Connector

Double sided Rectangle Sub program

Hexagon Iteration

Trapezoid Manual Operation

Cylinder Magnetic Disk StorageJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 4: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Machine Language – Assembly Language – High-Level Language

1234567891011121314

entry main,^m<r2>sub12 #12,spjsb C$MAIN_ARGSmoveb $CHAR_STRING_CON

pusha1 -8(fp)pusha1 (r2)calls #2,SCANFpusha1 -12(fp)pusha1 3(r2)calls #2,SCANFmull3 -8(fp),-12(fp),-pusha 6(fp)calls #2,PRINTF

123456789

1011121314

00000000 00000100 000000000000000001011110 00001100 11000010 0000000000000010

11101111 00010110 000000000000010111101111 10111110 0000000000001011

11111000 10101101 11011111 000000000001001001100010 11011111 0000000000010101

11101111 00000010 11111011 000000000001011111110100 10101101 11011111 000000000001111000000011 10100010 11011111 000000000010000111101111 00000010 11011111 000000000010010001111110 11110100 1010110111111000 10101110 11000101 000000000010101100000110 10100010 11111011 000000000011000111101111 00000010 11111011 0000000000110100 14

1516

calls #2,PRINTFclrl r0ret

141516

11101111 00000010 11111011 000000000011010001010000 11010100 0000000000111011

00000100 0000000000111101

12345678910

#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;

}

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 machine-language 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. JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 5: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Structure of C program/*Program to find /*Program to find

area and perimeter of Circle */area and perimeter of Circle */#include<#include<stdio.hstdio.h>>#define PI 3.1415#define PI 3.1415float radius;float radius;float area();float area();float perimeter();float perimeter();intint main()main(){{

float a, p;float a, p;printfprintf(“Enter radius : “);(“Enter radius : “);scanfscanf(“%(“%f”,&radiusf”,&radius););

Documentation SectionDocumentation Section

Linkage SectionLinkage Section

Definition SectionDefinition Section

Global Declaration SectionGlobal Declaration Section

Main Function SectionMain Function Section

Local Declaration PartLocal Declaration PartExecutable Code PartExecutable Code Parta = area();a = area();

p = perimeter();p = perimeter();printfprintf(“Area of Circle : %(“Area of Circle : %f”,af”,a););printfprintf(“Perimeter : %(“Perimeter : %f”,pf”,p););

}}float area()float area(){{

return (PI * radius * radius);return (PI * radius * radius);}}float perimeter()float perimeter(){{

return (2 * PI return (2 * PI * radius);* radius);}}

Executable Code PartExecutable Code Part

Sub Program SectionSub Program Section

Function1()Function1()Function2()Function2()…………………………FunctionN()FunctionN()JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 6: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Program Development Steps1)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.

4.a)CompilationTranslate 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+bThere is a syntax error in this statement, since, each and every statement in C language ends with a semicolon (;).

4.b)Executionresults 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.

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 7: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Executing a C program

compiles

SyntaxErrors?

Yes

Object machine code

010110 100…………….01011 101

C-compiler

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

…….

TextEditor

prog1.c

prog1.objLinker adds

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,

No

Linker

Executable machine code

00101010………….01010101

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.

machine code oflibrary file

Input

prog1.exe

C-RuntimeExecutes

FeedsRuntimeor Logic Errors ?

Yes

OutputJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 8: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

C-Language Keywords(C99)

Character Set of C-Language

Alphabets : A-Z and a-zDigits : 0-9Special Symbols : ~ ! @ # $ % ^ & ( ) _ - + = | \ { } [ ] : ; “ ‘

< > , . ? /White Spaces : space , Horizontal tab, Vertical tab, New Line

Form Feed.

C-Language Keywords(C99)auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while_Bool _Imaginary restrict _Complexinline JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 9: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

C-Tokens

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 scorea) First character must be alphabetic character or under scoreb) Second character onwards alphabetic character of digit or under

score.c) First 63 characters of an identifier are significant.d) Cannot duplicate a key word.e) May not have a space or any other special symbol except under

score.f) C – language is Case-sensitive.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 10: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

C-TokensConstants :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, 124567856UL54764U, 124356578L, 124567856UL

Float constants :0.2 , 876.345, .345623 , 23.4E+8, 47.45e+6String 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 )JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 11: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Data Types ( pre defined )

Type Typical Size in Bits Minimal Range

char 8 –127 to 127

unsigned char 8 0 to 255

signed char 8 –127 to 127

int 16 or 32 –32,767 to 32,767

unsigned int 16 or 32 0 to 65,535

signed int 16 or 32 Same as int

short int 16 –32,767 to 32,767

unsigned short int 16 0 to 65,535

signed short int 16 Same as short int

long int 32 –2,147,483,647 to 2,147,483,647

long long int 64 –(263) to 263 – 1 (Added by C99)

signed long int 32 Same as long int

unsigned long int 32 0 to 4,294,967,295

unsigned long long int 64 264 – 1 (Added by C99)

float 32 3.4e-38 to 3.4e+38

double 64 1.7e-308 to 1.7e+308

long double 80 3.4e-4932 to 1.1e+4932void -- data type that not return any valueJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 12: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Conversion Specifiers

Code Format%a Hexa decimal output in the form of 0xh.hhhhp+d(C99 only)%s String of characters (until null zero is reached )%c Character%d Decimal integer%f Floating-point numbers%e Exponential notation floating-point numbers%g Use the shorter of %f or %e%u Unsigned integer%o Octal integer%o Octal integer%x Hexadecimal integer%i Signed decimal integer%p Display a pointer%n The associated argument must be a pointer to integer, This sepecifier causes

the number of characters written in to be stored in that integer.%hd short integer%ld long integer%lf long double

%% Prints a percent sign (%)

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 13: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Back Slash ( Escape Sequence) Characters

Code Meaning\b Backspace\f Form feed\n New line\r Carriage return\t Horizontal tab\" Double quote\' Single quote\ \ Backslash\v Vertical tab\a Alert\? Question mark\N Octal constant (N is an octal constant)\xN Hexadecimal constant (N is a hexadecimal constant)JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 14: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Increment and Decrement OperatorsIncrement and Decrement Operatorsprefix increment (++a) postfix increment (a++) prefix decrement(prefix increment (++a) postfix increment (a++) prefix decrement(-- --a) postfix decrement (aa) postfix decrement (a-- --))

Before evaluation of expressionBefore evaluation of expression

Evaluation of expressionEvaluation of expression

After evaluation of expressionAfter evaluation of expressionand before leaving the statementand before leaving the statement

Executes all Prefix OperationsExecutes all Prefix Operations

Executes all Postfix OperationsExecutes all Postfix Operations

/* prefix operators *//* prefix operators */ /* prefix and postfix operators *//* prefix and postfix operators */ /* postfix operators *//* postfix operators *//* prefix operators *//* prefix operators */#include<stdio.h>#include<stdio.h>int main() {int main() {

int a = 7, b = 12, c;int a = 7, b = 12, c;c = b * (++a) + 5 * (++a);c = b * (++a) + 5 * (++a);printf(“ a = %d”, a);printf(“ a = %d”, a);printf(“printf(“\\n b = %d”,b);n b = %d”,b);printf(“printf(“\\n c = %d”,c);n c = %d”,c);

}}Output:Output:

a = 9a = 9b = 12b = 12c = 153 ( 12 * 9 + 5 * 9)c = 153 ( 12 * 9 + 5 * 9)

/* prefix and postfix operators *//* prefix and postfix operators */#include<stdio.h>#include<stdio.h>int main() {int main() {

int a = 7, b = 12, c;int a = 7, b = 12, c;c = b * (a++) + 5 * (++a);c = b * (a++) + 5 * (++a);printf(“ a = %d”, a);printf(“ a = %d”, a);printf(“printf(“\\n b = %d”,b);n b = %d”,b);printf(“printf(“\\n c = %d”,c);n c = %d”,c);

}}Output:Output:

a = 9a = 9b = 12b = 12c = 136 ( 12 * 8 + 5 * 8)c = 136 ( 12 * 8 + 5 * 8)

/* postfix operators *//* postfix operators */#include<stdio.h>#include<stdio.h>int main() {int main() {

int a = 7, b = 12, c;int a = 7, b = 12, c;c = b * (a++) + 5 * (a++);c = b * (a++) + 5 * (a++);printf(“ a = %d”, a);printf(“ a = %d”, a);printf(“printf(“\\n b = %d”,b);n b = %d”,b);printf(“printf(“\\n c = %d”,c);n c = %d”,c);

}}Output:Output:

a = 9a = 9b = 12b = 12c = 119 ( 12 * 7 + 5 * 7)c = 119 ( 12 * 7 + 5 * 7)JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 15: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Bitwise Logical OperatorsBitwise Logical Operators

& & ---- Bitwise ANDBitwise AND

| | ---- Bitwise ORBitwise OR

^ ^ ---- Bitwise XORBitwise XOR

~ ~ ---- Bitwise NOTBitwise NOT

A B A & B A | B A ^ B ~A

1 1 1 1 0 0

1 0 0 1 1 0

0 1 0 1 1 1

0 0 0 0 0 1

Bitwise ANDBitwise AND

A (42) : 00000000 00101010A (42) : 00000000 00101010

Bitwise ORBitwise OR

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

A (42) : 00000000 00101010A (42) : 00000000 00101010B (15) : 00000000 00001111B (15) : 00000000 00001111----------------------------------------------------------------------| (47) : 00000000 00101111| (47) : 00000000 00101111----------------------------------------------------------------------

Bitwise XORBitwise XOR

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

Bitwise NOTBitwise NOT

A (42) : 00000000 00101010A (42) : 00000000 00101010----------------------------------------------------------------------~ (~ (--43) : 11111111 1101010143) : 11111111 11010101----------------------------------------------------------------------JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 16: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

BITWISE SHIFT OPERATORSBITWISE SHIFT OPERATORS

Bitwise Left Shift ( << )Bitwise Left Shift ( << )

A (43) : 00000000 00101011A (43) : 00000000 00101011----------------------------------------------------------------------A << 2 : 00000000 10101100A << 2 : 00000000 10101100----------------------------------------------------------------------

Bitwise Right Shift ( >> )Bitwise Right Shift ( >> )(positive values)(positive values)

A (43) : 00000000 00101011A (43) : 00000000 00101011----------------------------------------------------------------------A >> 2 : 00000000 00001010A >> 2 : 00000000 00001010----------------------------------------------------------------------

Bitwise Right Shift ( >> )Bitwise Right Shift ( >> )(negetive values)(negetive values)

A (A (--44) : 11111111 1101010044) : 11111111 11010100----------------------------------------------------------------------A >> 2 : 11111111 11110101A >> 2 : 11111111 11110101----------------------------------------------------------------------

Note : Right shift operator fills the left vacant fieldsNote : Right shift operator fills the left vacant fields withwith ‘zeros’ for positive numbers, ‘zeros’ for positive numbers, with ‘ones’ for negative numbers.with ‘ones’ for negative numbers.

TYPE CONVERSIONTYPE CONVERSIONOppositeOppositeToTo

Explicit Type ConversionExplicit Type Conversion(casting)(casting)

1.bool1.bool

2.char2.char

3.short int3.short int4.int4.int5.long int 5.long int 6.long long int 6.long long int

7.float7.float8.double8.double9.long double9.long double

GravityGravity

GravityGravity

..

..

..

(forcible)(forcible)

(natural)(natural)

(casting)(casting)

Implicit Type ConversionImplicit Type Conversion(automatic)(automatic)

..

..

..

(forcible)(forcible)

(automatic)(automatic)

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 17: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Precedence and Associativity of OperatorsPrecdence Group Operators Associativity(Highest to Lowest )(param) subscript etc., ( ) [ ] –>. L ���� RUnary operators - + ! ~ ++ – – (type) * & sizeof R ���� LMultiplicative * / % L ���� RAdditive + – L ���� RBitwise shift << >> L ���� RRelational < <= > >= L ���� REquality = = != L ���� REquality = = != L ���� RBitwise AND & L ���� RBitwise exclusive OR ^ L ���� RBitwise OR | L ���� RLogical AND && L ���� RLogical OR | | L ���� RConditional ?: R ���� LAssignment = += –= *= /= %= &= ^= R ���� L

|= <<= >>=Comma , L ���� RJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 18: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Test Test ExpressionExpression

??

EntryEntry

FalseFalse

Next statementNext statement

True StatementTrue Statement--blockblock

TrueTrue

simple if:simple if:

Test Test ExpressionExpression

??

EntryEntry

TrueTrue--blockblockStatementsStatements

FalseFalse

FalseFalse--blockblockStatementsStatements

TrueTrue

Next statementNext statement

ifif--else:else:

/* check a citizen is eligible for voting *//* check a citizen is eligible for voting */ /* print a number is even or odd *//* print a number is even or odd *//* check a citizen is eligible for voting *//* check a citizen is eligible for voting */#include<stdio.h>#include<stdio.h>int main()int main(){{

int age;int age;printf(“Enter the age : ”);printf(“Enter the age : ”);scanf(“%d”,&age);scanf(“%d”,&age);if(age >= 18)if(age >= 18)

printf(“Eligible for voting…”);printf(“Eligible for voting…”);getch();getch();

}}

/* print a number is even or odd *//* print a number is even or odd */#include<stdio.h>#include<stdio.h>int main()int main(){{

int number;int number;printf(“Enter a number : “);printf(“Enter a number : “);scanf(“%d”, &number);scanf(“%d”, &number);if((number %2) == 0)if((number %2) == 0)

printf(“%d is even number.”,number);printf(“%d is even number.”,number);elseelse

printf(“%d is odd number.”,number);printf(“%d is odd number.”,number);}}JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 19: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Test Test condition1condition1

??

EntryEntry

TrueTrue

Test Test condition2condition2

??

FalseFalse

StatementStatement--11

TrueTrue

FalseFalse

nested if…else:nested if…else: /* check whether a year is leap year or not *//* check whether a year is leap year or not */#include<stdio.h>#include<stdio.h>int main() {int main() {

int year;int year;printf("Enter the year ?");printf("Enter the year ?");scanf("%d",&year);scanf("%d",&year);if((year %100) == 0)if((year %100) == 0){{

if((year % 400) == 0)if((year % 400) == 0)printf("%d is leap year.",year);printf("%d is leap year.",year);

elseelseprintf("%d is not leap year.",year);printf("%d is not leap year.",year);StatementStatement--33 StatementStatement--22 StatementStatement--11

Next statementNext statement

printf("%d is not leap year.",year);printf("%d is not leap year.",year);} else {} else {

if((year % 4) == 0)if((year % 4) == 0)printf("%d is leap year.",year);printf("%d is leap year.",year);

elseelseprintf("%d is not leap year.",year);printf("%d is not leap year.",year);

}}getch();getch();

}}

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 20: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

if…else…if :if…else…if :

EntryEntry

Test Test condition1condition1

??

TrueTrueStatementStatement--11

TrueTrueStatementStatement--22

Test Test condition2condition2

FalseFalse

/* program to print the grade of student *//* program to print the grade of student */#include<stdio.h>#include<stdio.h>int main() {int main() {

int marks;int marks;printf("Enter marks ? ");printf("Enter marks ? ");scanf("%d", &marks);scanf("%d", &marks);if(marks >= 75)if(marks >= 75)

printf("Distinction");printf("Distinction");else if(marks >= 60)else if(marks >= 60)StatementStatement--22condition2condition2

??

TrueTrueTest Test conditionNconditionN

??

FalseFalse

StatementStatement--NN

Next statementNext statement

else if(marks >= 60)else if(marks >= 60)printf("First class");printf("First class");

else if(marks >= 50)else if(marks >= 50)printf("Second class");printf("Second class");

else if(marks >= 35)else if(marks >= 35)printf("Third class");printf("Third class");

elseelseprintf("Failed");printf("Failed");

}}

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 21: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

switch statement :switch statement :

EntryEntry

switch switch expressionexpression

??

/* program to simulate a simple calculator *//* program to simulate a simple calculator */#include<stdio.h>#include<stdio.h>int main() {int main() {

float a,b;float a,b;char opr;char opr;printf("Enter number1 operator number2 : ");printf("Enter number1 operator number2 : ");scanf("%f %c %f",&a,&opr,&b); scanf("%f %c %f",&a,&opr,&b); switch(opr)switch(opr){{

case '+':case '+':printf("Sum : %f",(a + b));printf("Sum : %f",(a + b));break;break;

case 'case '--':':

associateassociatestatementstatement

associateassociatestatementstatement

associateassociatestatementstatement

associateassociatestatementstatement

value1value1 value2value2 valueNvalueN defaultdefault……...……...

Next statementNext statement

case 'case '--':':printf("Difference : %f",(a printf("Difference : %f",(a -- b));b));break;break;

case '*':case '*':printf("Product : %f",(a * b));printf("Product : %f",(a * b));break;break;

case '/':case '/':printf("Quotient : %f",(a / b));printf("Quotient : %f",(a / b));break;break;

default:default:printf("Invalid Operation!");printf("Invalid Operation!");

}}}}

ExitExit

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 22: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

TestCondition

?

Body of The loop

False

truetrue

while while –– (Entry controlled )(Entry controlled )EntryEntry

Loop StatementsLoop Statements

Following Statement

TestCondition

?

Body of The loop

False

TrueTrue

EntryEntry

Following Statement

dodo--while while –– (Exit controlled )(Exit controlled )

TrueTrue Following Statement

/* sum of 1 to 10 numbers *//* sum of 1 to 10 numbers */#include<stdio.h>#include<stdio.h>int main() {int main() {

int i = 1,sum = 0;int i = 1,sum = 0;while(i<=10){while(i<=10){

sum = sum + i;sum = sum + i;i = i + 1;i = i + 1;

} } printf(“Total : %d “,sum);printf(“Total : %d “,sum);

} }

/* average of 5 numbers *//* average of 5 numbers */#include<stdio.h>#include<stdio.h>int main() {int main() {

int count = 1;int count = 1;float x, sum = 0;float x, sum = 0;do {do {

printf(“x = “);printf(“x = “);scanf(“%f”,&x);scanf(“%f”,&x);sum += x;sum += x;++ count;++ count;

} while(count <= 5);} while(count <= 5);printf(“Average = %f “, (sum/5))printf(“Average = %f “, (sum/5))

} } JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 23: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

for for ---- StatementStatement

Initialization StatementIncrement Statement

TestCondition

?

Body of The loop

EntryEntry

TrueTrue

Following Statement

False

/* check whether a number is prime or not *//* check whether a number is prime or not */#include<stdio.h>#include<stdio.h>#include<stdio.h>#include<stdio.h>int main() {int main() {

int n,i,factors = 0;int n,i,factors = 0;printf("Enter a number : ");printf("Enter a number : ");scanf("%d",&n);scanf("%d",&n);for(i = 1; i <= n; i++) {for(i = 1; i <= n; i++) {

if((n % i)==0) ++factors;if((n % i)==0) ++factors;}}if (factors == 2)if (factors == 2)

printf("%d is prime number.",n);printf("%d is prime number.",n);elseelse

printf("%d is not prime number.",n);printf("%d is not prime number.",n);}}JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 24: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Important Functions in math.h

abs(x) absolute value of integer xceil(x) rounds up and returns the smallest integer greater than or

equal to xfloor(x) rounds down and returns the largest integer less than or equal

to xlog(x) returns natural logarithmpow(x,y) returns the value of xy

sqrt(x) returns square root of xsqrt(x) returns square root of xexp(x) returns natural anti logarithmsin(x) returns sine value where x in radianscos(x) returns cosine value where x in radianstan(x) returns tangent values where x in radiansfmod(x,y) calculate x modulo y, where x and y are doublehypot(x,y) calculate hypotenuse of right angle where x,y are sides.log10(x) returns logarithm base 10JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 25: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

www.alljntuworld.in

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH,B.PPHHAARRMMAACCYY,, MMBBAA,, MMCCAA ooff JJNNTTUU--HYD,JNTU-KAKINADA & JNTU-ANANTAPUR visit www.alljntuworld.in

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 26: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* program to find area of a ring */#include<stdio.h>int main(){

float a1,a2,a,r1,r2;

/* program to find area of a ring */#include<stdio.h>float area();int main(){

float a1,a2,a;a1 = area();

Modularizing and Reusing of code through Functions

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

Function DeclarationRepeated & Reusable

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); }

a1 = area();a2 = area();a = a1- a2;printf("Area of Ring : %.3f\n", a);

} float area(){

float r;printf("Enter the radius : ");scanf("%f", &r);return (3.14*r*r);

}

Function Definition

Function Calls

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 27: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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 thefunction, for any number of times and from anywhere in the program. The purpose of a functionis to receive zero or more pieces of data, operate on them, and return at most one piece ofdata.

A Called Function receives control from a Calling Function . When the called functioncompletes its task, it returns control to the calling function. It may or may not return a value tothe caller. The function main() is called by the operating system; main() calls other functions.When main() is complete, control returns to the operating system.

int main() { value of ‘n’ is copied to terms’value of ‘p’ is copied to loan’

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:“);

}

float calcInterest (float loan , int terms , float iRate ){

float interest;interest = ( loan * terms * iRate )/100;return ( interest );

}

value of ‘r’ is copied to ‘iRate’

value of ‘interest’ is assigned to ‘si ’

Called Function

Calling Function

The block is

executed

Process of Execution for a Function CallJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 28: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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);

12

3 7

8Flow of Control

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

void readPrintHexa(){

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

}

void printHexa(int n){

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

4

5

6

in Multi-Function

Program

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 29: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* Program demonstrates function calls */#include<stdio.h>int add ( int n1, int n2 ) ;int main(void){

int a, b, sum;printf(“Enter two integers : ”);scanf(“%d %d”, &a, &b);

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

Declaration (proto type) of Function

Formal Parameters

Function Call

Actual Arguments

Function-It’s Terminology

Function Name

return 0;}

/* adds two numbers and return the sum */

int add ( int x , int y ){

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

}

Actual Arguments

Definition of Function

Parameter List used in the Function

Return statement of the Function

Return Value

Return Type

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 30: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* using different functions */int main(){

float radius, area;printMyLine();printf(“\n\tUsage of functions\n”);printYourLine(‘-’,35);radius = readRadius();area = calcArea ( radius );

void printMyLine(){

int i;for(i=1; i<=35;i++) printf(“%c”, ‘-’);printf(“\n”);

}

Function with No parameters and No return value

void printYourLine(char ch, int n){

int i;

Function with parameters and No return value

Categories of Functions

area = calcArea ( radius );printf(“Area of Circle = %f”,

area);}

int i;for(i=1; i<=n ;i++) printf(“%c”, ch);printf(“\n”);

}

and No return value

float readRadius(){

float r;printf(“Enter the radius : “);scanf(“%f”, &r);return ( r );

}

Function with return value & No parameters

float calcArea(float r){

float a;a = 3.14 * r * r ;return ( a ) ;

}

Function with return value and parameters

Note: ‘void’ means “Containing nothing” JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 31: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#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();

}

void perimeter(){

int no = 0; float p;

void area(){

static int num = 0;

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

}

Static Local Variables Visible with in the function,created only once whenfunction is called at firsttime and exists betweenfunction calls.

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

}

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

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

External Global Variables Scope : Visible across multiplefunctions Lifetime : exists till the endof the program.

Storage Classes – Scope & LifetimeJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 32: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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);

extern float length, breadth ;/* extern base , height ; --- error */float rectanglePerimeter(){

float p;p = 2 *(length + breadth); return ( p );

}

File1.c File2.c

External Global Variables Scope : Visible to all functions across allfiles in the project .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);

}

files in the project .Lifetime : exists till the end of theprogram.

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

Storage Classes – Scope & LifetimeJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 33: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#include<stdio.h> void showSquares(int n){

if(n == 0)return;

elseshowSquares(n-1);

printf(“%d “, (n*n));}int main(){

showSquares(5);

A functioncalling itself

is Recursion

Preprocessor Directives

#define - Define a macro substitution#undef - Undefines a macro#ifdef - Test for a macro definition#ifndef - 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 #ifshowSquares(5);

}

Output : 1 4 9 16 25

showSquares(5)

showSquares(4)

showSquares(3)

showSquares(2)

showSquares(1)additionof

function calls

to call-

stack

call-stack

executionof

function calls

in reverse

#endif - Specifies the end of #if#pragma - Specifies certain instructions#error - Stops compilation when an error

occurs# - Stringizing operator## - Token-pasting operator

Preprocessor is a program that processes the source code before it

passes through the compiler.

main()JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 34: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH, B.PHARMACY, MBA, MCA of JNTU-HYD,JNTU-KAKINADA & JNTU-ANANTAPUR vivisisitt wwwwww..jalljntuworld.in

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 35: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* 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);

…. …. …. ….

score0

score1

score2

score3

.

.

score59

scores[0]

scores[1]

scores[2]

scores[3]

.

.

scores[59]

#include<stdio.h>

Sixty variables are replaced by one Array

Sixty input

Array & its Advantage

…. …. …. ….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;}

}

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

int scores[60] , i , j, temp;for(i = 0; i < 60 ;i++) {

printf("Enter the score : ");scanf("%d", &scores[i]);

}for(i=0;i<(60-1);i++)for( j=0; j <(60 -(i+1)); j++)

if(scores[ j ] < scores[ j +1]) {temp = scores[ j ]; scores[ j ] = scores[ j +1];scores[ j + 1] = temp;

}for( i = 0; i < 60; i ++) printf("%4d", scores[i]);

}

Sixty input

statements are

called by one loop

statement

1770 comparing

statements are

included in one

loop statement

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 36: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

scores[0] scores[1] scores[2] scores[3] scores[4]

scores Array

. . .

start here

4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 ( memoryaddresses)

#include<stdio.h>

#include<math.h>

printf("\nMean : %.2f",mean);

printf("\nDeviations : ");

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.

Declaration of ArrayAccessing

an element#include<math.h>

#define SIZE 10

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];

}

mean = (float)sum / SIZE;

printf("\nDeviations : ");

for(i=0;i<SIZE ; i++) {

deviation = scores[i] - mean;

printf("%.2f\t", deviation);

total=total + deviation*deviation;

}

variance = total / SIZE;

printf("\nVariance = %.2f\n", variance);

stddev = sqrt(variance);

printf("Standard Deviation : %f", stddev);

}

Initialization of Array

Declaration of Array

Processing on ArrayInput to an element

an element

skyups media

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 37: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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.

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

structure. It represents a collection of related data items of same type.

�An individual data item of an array is called as ‘element’. Every element is accessed by index or

subscript enclosed in square brackets followed after the array name.

� All its elements are stored in consecutive memory locations, referred under a common array name.

Ex : int marks[10] ; /* declaration of array */

� ‘0’ is first number in computer environment. The first element of array marks is marks[0] and last

element is marks[9]. (the address of first element is the address of the array)

� An array is a derived data type. It has additional operations for retrieve and update the individual

values.

� The lowest address corresponds to the first element and the highest address to the last element.

� Arrays can have from one to several dimensions. The most common array is the string, which is

simply an array of characters terminated by a null.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 38: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Declaration of One Dimensional ArraysSyntax :

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 ArraysSyntax :

arrayType arrayName [ Rows ][ Columns ];

[0][0] [0][1] [0][2] [0][3]

[1][0] [1][1] [1][2] [1][3]

[2][0] [2][1] [2][2] [2][3]

Elements of

Array [3] by [4]

/*passing an array to function */

#define SIZE 10

int main() {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 } };

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 ) ;

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 39: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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. */

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 ).

char name[] = “Ravi Kiran”; R a v i K i r a n \0

name‘name’ is an array of characters has size of eleven characters including a null

character ‘\0’(ascii code is zero).

gets(name) ; /* reading a string including white spaces until ‘\n’ is encountered. */

puts(name); /* printing a string and moves cursor to new line */

String Manipulation Functions in <string.h>

strlen(s1) - returns the length of string excluding the last ‘null’ character.

strcpy(s1,s2) - copies characters in s2 into s1.

strcat(s1,s2) - concatenates s2 to s1.

strcmp(s1,s2) -compares s1 with s2 lexicographically and returns ‘0’ if two strings are

same , returns -1 if s1 is before s2 and returns +1 if s1 is after s2.

strcmpi(s1,s2) -compares s1 with s2 like strcmp() but case of characters is ignored.

strchr(s1,ch) -returns pointer to first occurrence of the character ‘ch’ in s1.

strstr(s1,s2) -returns pointer to first occurrence s2 in s1.

strrev(s1) -returns pointer to the reversed string.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 40: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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.

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.

Memory Sections of C-Runtime

global variables, which is separate for each running instance of a program.

BSS (Below Stack Segment) : Memory area contains storage for uninitialized global

variables. It is also separate for each running instance of a program.

Stack : Area of memory image of a running program contains storage for automatic

variables of a function. It also stores memory address of the instruction

which is the function call, to return the value of called function.

Heap : This memory region is reserved for dynamically allocating memory for

variables at run time. Dynamic Memory Allocation calculate the required

memory size while program is being executed.

Shared Libraries: This region contains the executable image of shared libraries being used by

a program. JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 41: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Two or more Permanent Manipulations using one Function

/* 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()

{

Passing Parameters By Value 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);

}

Output :

Before swap() 25 37

In swap () 37 25

After swap() 25 37

{

int a = 25,b = 37;

printf(“Before swap() : %d %d”,a,b);

swap (&a , &b);

printf(“\nAfter swap() : %d %d“,a,b);

}

Output :

Before swap() 25 37

In swap () 37 25

After swap() 37 25JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 42: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Pointer variable – A variable holds the address of another variable

char option = ‘Y’;

Allots some memory location 4042 (for example)

with a name option and stores value ‘Y’ in it

‘Y’

option

4042

Value in ‘option’

Memory Address of variable ‘option’

char *ptr = NULL;

Creates a pointer variable

with a name ‘ptr’

Which can hold a

Memory address ptrMemory address ptr

Memory address of

Variable ‘option’

Is copied to the

Pointer ‘ptr’

4042

ptr

ptr = &option; ‘Y’

option

4042

*ptr = ‘N’;The value ‘N’ is

stored in the variable

which has the

memory address

4042

4042

ptr

‘N’

option

4042JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 43: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Program with Using Pointers

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

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

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

NULL NULL

n1 n2

p q

6 3n1 n2

p q

pointer variables are declared

Prints 6 3

Prints 6 6

Prints address of n1

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

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

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

}

6 3n1 n2

p qpointer ‘q’ assigned with pointer ‘q’

Prints 3 3

6 7n1 n2

p qPrints 7 7

When two pointers are referencing with one variable, both pointers contains address of the

same variable, and the value changed through with one pointer will reflect to both of them. JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 44: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Pointer and Arrays

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

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

int a[3] = { 12, 5 ,7}, b[3];int *p ,*q;

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.

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

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

b = a; /* error */}

Prints 12 12

Prints 12 12Array name is an address constant,

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

changed in the program.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 45: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Pointer Arithmetic and Arrays

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

int arr [5] = { 12, 31, 56, 19, 42 };int *p;p = arr + 1;printf("%d \n", *p);printf("%d %d %d\n", *(p-1), *(p), *(p + 1));--p;printf("%d", *p);

Prints 31 Prints 12 31 56

Prints 12

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

12

31

56

19

42

arr[0] or *( arr + 0 )

arr[1] or *( arr + 1 )

arr[2] or *( arr + 2 )

arr[3] or *( arr + 3 )

arr[4] or *( arr + 4 )

p - 1

p

p + 1

p + 2

p + 3

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 46: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Array of Pointers

The advantage of pointer array is that the length of each row in the array maybe different. The important application of pointer array is to store character stringsof different length. Example :

char *day[ ] = { “Sunday”, “Monday”, ”Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday” };

Pointer to Pointer ( Double indirection )

Example : int a = 25;int *pa = &a;int **ppa ;*ppa = &pa;

25

pa ppa

4024 4056

a

*ppa = &pa;printf(“%d”, *pa); ���� prints 25 printf(“%d”, **ppa); ���� prints 25

407840564024

Two Dimensional Array -- Pointers

a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]

base_address

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

Array name contains base address JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 47: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

void Pointer

int main( ) {void* p;int x = 7;float y = 23.5;

‘void’ type pointer is a genericpointer, which can be assigned to anydata type without cast duringcompilation or runtime. ‘void’ pointercannot be dereferenced unless it iscast.

Function Pointers

Function pointers are pointers, whichpoint to the address of a function.Declaration :

<return type> (* function_pointer)(type1 arg1, type2 arg2, ……. );

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

int (*fp ) (int, int ) ; /* function pointer */float y = 23.5;p = &x;printf(“x contains : %d\n”, *( ( int *)p) );p = &y;printf(“y contains : %f\n”, *( ( float *)p) );

}

Output :x contains 7y 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 = 9Difference = 4JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 48: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Dynamic Memory Allocation (DMA) of pointers

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

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 ofthese functions. Memory is assigned at run time.

int main(){

int *p, *q ;p = (int *) malloc ( sizeof( int ) );if( p == NULL )

Allocates memory in bytes and returns the address of first byte to the pointer variable

Releases previously allocated memory space.

if( p == NULL ){

printf(“Out of memory\n”);exit(-1);

}printf(“Address in p : %d“, p );

free ( p );p = NULL;

}

calloc ( ) is used for allocating memory spaceduring the program execution for derived data typessuch as arrays, structures etc.,Example :struct book {

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. JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 49: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Standard Character Functions Classification of Characters

control

iscntrl ( )

printable

isprint ( )

space

isspace ( )

graphical

isgraph ()

alpha-numeric

isalnum ( )

punctuation

ispunct ( )

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

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

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

i , argv [ i ] );

Command Line Arguments

File Name : cmdline.c

alphabetic

isalpha( )digit

isdigit ()

upper

isupper ( )

lower

islower ()

Other character functions in <ctype.h>

toupper( ) – converts to uppercase.tolower ( ) – converts to lowercase. toascii ( ) – converts greater than 127 to

with in the range 0 – 127

i , argv [ i ] ); }

Compile the program :c:\>tcc cmdline.cc:\>cmdline welcome to c-programmingc:\>Number of arguments : 4Name of Program : c:\cmdline.exeUser value 1 : welcomeUser value 2 : toUser value 3 : c-programming

output

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 50: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

<stdlib.h>int atoi(s) 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.

Standard C-Library Functions

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.

<time.h>clock_t clock() Returns clock ticks since program starts.

char *asctime(stuct tm) Converts date and time into ascii.

int stime(time_t *tp) Sets time.

time_t time(time_t *timer) Gets time of day.

double difftime(t1,t2) Returns difference time between two times t1 and t2.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 51: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

Derived

Types

Function

Type

Structure

TypeArray Type

Pointer

TypeUnion Type

Array – Collection of one or more related variables of similarArray – Collection of one or more related variables of similardata type grouped under a single name

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

In a Library, each book is an object , and its characteristics like title, author, no ofpages, price are grouped and represented by one record .

The characteristics are different types and grouped under a aggregate variable ofdifferent types.

A record is group of fields and each field represents one characteristic. In C, a recordis implemented with a derived data type called structure . The characteristics of record arecalled the members of the structure.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 52: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

bookbookid

title

author

pages

Book-1BookID: 1211Title : C Primer PlusAuthor : Stephen PrataPages : 984Price : Rs. 585.00

Book-2BookID: 1212Title : The ANSI C ProgrammingAuthor : Dennis RitchiePages : 214Price : Rs. 125.00

Book-3BookID: 1213Title : C By ExampleAuthor : Greg Perry

Pages : 498Price : Rs. 305.00

integerbook_id

Array of 50 characterstitle

Array of 40 charactersauthor

integerpages

floatprice

2 bytes

50 bytes

40 bytes2 bytes

4 bytesprice

STRUCTURE- BOOKstruct book {

int book_id ;char title[50] ; char author[40] ; int pages ;float price ;

};

Structure tag

floatprice 4 bytes

struct < structure_tag_name > {

data type < member 1 >data type < member 2 >

…. …. …. ….data type < member N >

} ;

Memory occupied by a Structure variable

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 53: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Initialization of structure

Declaring a Structure Type

struct student{

int roll_no;char name[30];float percentage;

};

Declaring a Structure Variable

struct student s1,s2,s3;(or)

struct student{

int roll_no;char name[30];float percentage;

}s1,s2,s3;

Reading values to members at runtime:

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 ;

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);

membership operatorJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 54: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

struct employee {int empid;char name[35];int age;float salary;

};int main() {

struct employee emp1,emp2 ;

struct employee emp3 = { 1213 , ” S.Murali ” , 31 , 32000.00 } ;emp1.empid=1211;

Implementing a Structure

Declaration of Structure Type

Declaration of Structure variables

Declaration and initialization of Structure variable

strcpy(emp1.name, “K.Ravi”);emp1.age = 27;emp1.salary=30000.00;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”);

printf(“Emp ID:%d\n Name:%s\n Age:%d\n Salary:%f”, emp1.empid,emp1.name,emp1.age,emp1.salary);

}

Initialization of Structure members individually

Reading values to members of Structure

Accessing members of Structure

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 55: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Nesting of structures

struct date {int day ;int month ;int year ;

} ;struct person {

char name[40];int age ;struct date b_day ;

};int main( ) {

struct person p1;strcpy ( p1.name , “S. Ramesh “ ) ;

Arrays And structures

struct student{

int sub[3] ;int total ;

} ;

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++) {

Outer Structure

Inner Structure

strcpy ( p1.name , “S. Ramesh “ ) ;p1. age = 32 ;p1.b_day.day = 25 ;p1.b_day. month = 8 ;p1.b_day. year = 1978 ;

}

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 );}

}

OUTPUT:Enter student 1 marks: 60 60 60Enter student 2 marks: 70 70 70Enter student 3 marks: 90 90 90

Total marks of student 1 is: 180Total marks of student 2 is: 240Total marks of student 3 is: 270

Accessing Inner Structure members

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 56: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

struct fraction {int numerator ;int denominator ;

};

void show ( struct fraction f ){

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

}

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

structures and functions Self referential structures

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 “ ) ;

s1. next = & s2 ; s2 node is linked to s1 nodeshow ( f1 ) ;

}

OUTPUT:7 / 12

s1. next = & s2 ;

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

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

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 datastructures such as linked -lists, trees and graphs .

s2 node is linked to s1 node

Prints P.Kiran

Prints B.Mahesh

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 57: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Pointer to a structure

Accessing structure members through pointer :

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

ii) Using - > ( arrow ) operator :ptr - > prodid = 111 ;strcpy( ptr - > name , “Pencil”) ;

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); Read Product Details :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 Pen112 Pencil113 Book

Print Product Details :

Product ID : 111Name : PenProduct ID : 112Name : PencilProduct ID : 113Name : BookJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 58: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

Union is a variable, which is similar to the structure and contains number of memberslike structure.

In the structure each member has its own memory location whereas, members of unionshare the same memory. The amount of storage allocated to a union is sufficient to hold itslargest member.

struct student {int rollno;float avg ;char grade ;

};union pupil {

int rollno;

Memory allotted to structure student

Address 5000 5001 5002 5003 5004 5005 5006

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

rollno avg gradeTotal memory occupied : 7 bytes

Memory allotted to union pupil

rollnoavg

gradeTotal memory occupied : 4 bytes

Address 5000 5001 5002 5003

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 59: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

www.alljntuworld.in

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH,

B.PHARMACY, MBA, MCA of JNTU-

HYD,JNTU-KKAAKKIINNAADDAA && JJNNTTUU--AANNAANNTTAAPPUURR

vviissiitt

www.alljntuworld.in

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 60: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

INTRODUCTION:

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

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

main()

{ struct student

{

int rno;

char gender;

int age;

rno gender

age ht wt

2 1

2 4 4

13 bytes of memory is allocated in s1JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 61: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

float ht;

float wt;

};

struct student s1,s2;

}

age gender

age ht wt

2 1

2 4 4

13 bytes of memory is allocated to s2

}

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

�struct is a keyword used to create a new user defined data type.

�In some other high level programming languages the structures are named as recordsJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 62: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

DEFINING A STRUCTURE:

syntax:

struct user defined datatype

{

datatype member1;

Example:struct student{int rno;int age;datatype member1;

datatype member2;

…………….

…………

datatype membern:

};

int age;char gender;float ht;float wt;

};

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 63: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

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

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

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

�All these structure members must be enclosed within a pair of curly braces.

�The structure definition should be terminated with semicolon.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 64: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

DECLARING STRUCTURE VARIABLE:

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

syntax:

struct user defined_data type namestruct user defined_data type name

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

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

�We can also declare structure variables immediately after structuredefinition.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 65: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

ACCESSING STRUCTURE MEMBERS:

.�

Structure member accessing operator

S1.rno=100Structure variable

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

S1.ht=5.5; s1.wt=60.2;variable

Structure member

•Two operators are used to access member of structure. The structuremember operator(.) also called dot operator and the structure pointeroperator (�) also called the arrow operator.

•The structure member operator accesses a structure member via structurevariable name.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 66: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

syntax:

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

rno gender

age ht wt

rno gender100 M

s1 s2

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

age ht wt wtage ht25 60.25.5

ASSIGNING VALUES TO STRUCTURE MEMBERS:

By using the assignment operator(=) we can assign values to all structure members of a structure variable.

Syntax: structure variable.member = value;

Ex: s1.rno= 100; s1.age=25 JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 67: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

INITIALIZING A STRUCTURE VARIABLE:

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

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

int x = 10;int x = 10;

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

READING AND DISPLAYING THE STRUCTURE VARIABLES:

The ‘C’ will not read or write an entire structure as a single command. It will read or write the members of a structure as follows:

ex: scanf(“ %d, %d, %c, %f” ,&s1.rno,&s1.age,&s1.gender,&s1.ht);

printf(“ %d %d %c %f”, s1.rno, s1.age, s1.gender, s1.ht);JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 68: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

PROGRAM USING STRUCTURES:

� Reads the details of 2 students and calculate total and average marks of 2 students.

#include<stdio.h>

#include<conio.h>

void main()

{ /* defining a structure */{ /* defining a structure */

struct student

{ int rno;

char name[30];

float m1,m2,m3;

float tot, avg;

};JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 69: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* 2. declaration of structure var*/

struct student s1,s2; (1st executed)

/* 3.reading 1st student details*/

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

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

/* 4. reading 2nd student details*/

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

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

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

s1.tot= s1.m1+s1.m2+s1.m3;

s1.avg = s1.tot/3;JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 70: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* 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);

/* 8. displaying second student details*/

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 71: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Array of Structures:

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

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

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

struct studentstruct student

{

int rno;

int m1,m2,m3;

int tot,avg;

}

struct student s[100];-Structure Variable Declaration JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 72: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

DEMONSTRATING ARRAY OF STRUCTURES:

#include<stdio.h>

#include <conio.h>

void main()

{

/*1.Defining an array of structures*/

struct student

{

int rno;

int m1,m2,m3;

int tot,avg;

}; JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 73: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/*2.Creating an array of Structures*/

struct student s[100];

int i,n;

clrscr();

printf(“Enter n value\n”);

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

scanf(“%d”,&n);

/*4.Reading student details*/

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

{

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

scanf(“%d”,&s[i].rno);JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 74: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

/*5.Calculate tot,avg marks */

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

{

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

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

}

/*6.Display the student details*/

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

{

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

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

orld

www.alljntuworld.in JNTU World

JNTU World

Page 75: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

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

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

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

}

}

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 76: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Arrays with in Structures:

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

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

For example consider this Structure:

struct x

{

int rno;

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

int tot,avg;

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 77: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Nested Structures:

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

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

Member to another structure.EX:struct Test{{

int a;int b;

};Struct Exam{

int x;int y;struct Test z;

}; JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 78: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Structures and Function:

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:

#include<stdio.h>

/*Defining a Structure*//*Defining a Structure*/

struct Test

{

int a;

int b;

};

/*Prototype*/JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 79: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

struct Test Modify(struct Test s2);

void main()

{

struct Test T1={10,20};

T1=Modify(T1);

printf(“After calling modify\n”);

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

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

}

Stuct Test Modify(struct Test s2)

{

s2.a=s2.a+10;JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 80: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

S2.b=s2.b+10;

return s2;

}

a

10

b

20

b

20

20+10

a10

10

10 20

302020+10

=30

10+10=20

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 81: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Union:

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

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

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

Syntax:

Union Userdefined_datatype

{

datatype member 1;

datatype member n;};JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 82: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Union Test

{

char a;

int b;

float c;

};

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 83: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

FILE HANDLING IN ‘C’

Disk I/O functions

High level Low level

Text Binary

Formatted Un formatted formatted Un formatted

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 84: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

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

o 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.

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 85: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

There are two distinct ways to perform file operations.--The first one is known as the low level I/O and uses

UNIX system calls. --The second method is referred to as the high level

operation and uses functions in c standard I/O library.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 86: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

HIGH LEVEL I/O FUNCTIONS

fopen () � creates a new file for use.

Opens an existing file for use.

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

getc() � reads a character from a file .getc() � reads a character from a file .

putc() � writes a character to a file.

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

fscanf() � reads a set of data value from a file.

getw() � reads an integer from a file.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 87: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

putw() � writes an integer to a file.

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

ftell() � gives the current position in file.

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

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

1.File name 2. data structure 3. purpose

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

FILE *fp; � specifies the file name.

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 88: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

r: opens the text file for reading only.

w: opens the text file for writing only.

a : open the file for appending data to it.

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

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

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

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 89: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

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

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

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

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 90: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

CLOSING A FILE:

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

Example:

FILE *P1, *P2;

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

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

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

Syn: fclose ( file pointer);

fclose (P1);

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 91: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

getc() and putc():

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.character into a file.Syntax : putc (charvar, file pointer);

putc (ch, fp);

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 92: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

#include<stdio.h>

Void main()

{ char ch;

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

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

while(1)

{ ch=getc (fp);

if ( ch== EOF)

break;

noc++;

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 93: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

if ( ch==‘ ‘)

nos++;

if (ch== ‘\t’)

not++;

If ( ch==‘\n’)

nol++;nol++;

}

fclose (fp);

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

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

printf (“ number of tabs=%d \n” , not);JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 94: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

getch();

}

OUTPUT:

number of characters =125number of characters =125

number of blanks =25

number of tabs =13

number of lines =22

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 95: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

putw() and getw():

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

Syntax: putw( integer, file pointer)

ex: putw (x,pf);

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

Syntax: integervar =getw( file pointer);

ex: x= getw(fp);

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 96: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Program for demonstrating putw() and getw() function

#include<stdio.h>

#include<stdlib.h>

Void main()

{

FILE *f;

int word1, word2;

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

if(fp==NULL)

{

printf (“ error opening file”);JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 97: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

exit(1);

}

word1=94;

putw(word1,fp);

if ( ferror(fp))

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

else

printf( “ sucessful write \n” );

fclose(fp);

/* reopen the file */

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

orld

www.alljntuworld.in JNTU World

JNTU World

Page 98: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

if ( fp== NULL)

{

printf(“ error opening file “);

exit(1);

}

/*extract the word */

Word =getw (fp);

if (ferror (fp))

printf(“ error reading file \n”);

else

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

orld

www.alljntuworld.in JNTU World

JNTU World

Page 99: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* clean up*/

fclose (fp);

return 0;

}

word1Number file

94

getw

word194

word2

94

Successfully wrote

Successful read

pf f()

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 100: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

fprintf() and fscanf() functions:

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

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

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

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

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

Demonstrating frpintf () and fscanf() functions:

#include<stdio.h>

#include<conio.h>

Void main()

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 101: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

{

FILE *fp;

int rno;

char name[30];

float marks;

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

printf( “ enter student record \n”);

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

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

fclose( fp);

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

orld

www.alljntuworld.in JNTU World

JNTU World

Page 102: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

printf(“ the student record \n”);

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

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

fclose (fp);

} scanf()

H.D

student

1. Ravi 30.5

rno name marks1 ravi 30.5

Enter students

1.Ravi 30.5

1 ravi 30.5

fprintf()

fscanf() prinf()JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 103: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

RANDOM ACCESS TO FILES:

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

This can be accomplished by using following function.

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

The general format of fseek function is as follows:

fseek( file pointer, offset, position);

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 104: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

1. Fileptr is a pointer to the file concerned.

2. Offset is a number or variable type long.

3. Position in an integer number.

Offset specifies the number of positions (bytes) to be moved from the location specified at position.

integervalue

Constant Location in filevalue

0

1

2

SEEK_SET

SEEK_CUR

SEEK_END

Beginning of file

Current position of file

End of file

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

filepointer is repositioned in forward direction by 10 bytesJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 105: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

Void main()

{

FILE *fp;

int n, ch;int n, ch;

clrscr();

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

printf( “\n contents of file \n”);

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

printf(“ %c”, ch);JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 106: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

printf( “ \n how many characters including spaces would you like to skip?”);

scanf(“%d”, &n);

fseek ( fp, n, SEEK_SET)

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

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

printf(“%c”, ch);

fclose(fp);

}

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 107: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

‘ 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);

typedef – to define new datatype bitfieds

struct playcard {unsigned pips ;unsigned suit ;

};Above structure occupies 4 bytes of

memory. But the member pips accepts avalue between 1 to 13 and the member suitaccepts 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;printf(“%d - %d = %d”, a, b, sub);

}

/* Defining structure with typedef to avoid

repeated usage of struct keyword */

typedef struct {

int hours;

int minutes;

} TIME ;

int main( ) {

TIME t1, t2 , *t;

t = (TIME *) calloc (10, sizeof( TIME ));

}

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-bitfield called suit that is capable of storingvalues 0, 1, 2, and 3. So the entire structurevariable occupies only one byte.Note : arrays of bit fields and a pointer toaddress a bit field is not permitted.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 108: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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

#include<stdio.h>enum color {RED = 1,ORANGE,GREEN };

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 */

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;

}}

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;

}}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 109: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

� scanf( ) and printf( ) functions read and write data which always uses theterminal (keyboard and screen) as the target.

� It becomes confusing and time consuming to use large volumes of datathrough terminals.

� The entire data is lost when either program terminates or computer isturned off.

� Some times it may be necessary to store data in a manner that can belater retrieved and processed.

This leads to employ the concept of FILES to store data permanentlyin the system.

Console I / O Vs File I / O

Record is logical group of data fields thatcomprise a single row of information, whichdescribes the characteristics of an object.

File is a set of records that can be accessedthrough the set of library functions.

A File is a place on disk where a group ofrelated data ( records ) can be stored

File Operations

1. Creating a new file2. Opening an existing file3. Reading from a file4. Writing to a file5. Moving to a specific

location in a file (seek)6. Closing a fileJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 110: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

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 .

Types of Files 1.Text file : It can be thought of as a stream of characters that can be processed sequentiallyand 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 totraverse 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 recorddirectly. Ex : files on disks.

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.

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 111: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/*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 ‘.’ ) : ”);

Steps involved using files

1. Declaring FILE pointer variable :Syntax :

FILE *file_pointer1;

2. Open a file using fopen() function :Syntax :

fp= fopen(“filename”,“mode of access”);

3. fputc() – Used to write a character to the file.

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);

}

the file.Syntax :

fputc(character, file_pointer);

4. fgetc() – Used to read a character to the file.Syntax :

fgetc(file_pointer);

5. Close a file using fclose() function :Syntax :

fclose(file_pointer); JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 112: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* 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);

}

file pointer used to handle files

fclose(filepointer);

putc(character,filepointer);

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

/* Reading the contents of existing file */#include<stdio.h>int main() {

FILE *fp;char ch;fp=fopen("str.txt","r");while((ch=getc(fp))!=EOF)

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

}

/* appending data to an existing file */int main() {

FILE *fp; char ch;printf("\nEnter the text\n");printf("\n\t(Press ctrl+Z after

completing text)\n");fp=fopen("str.txt","a");while((ch=getchar())!=EOF)

putc(ch,fp);fclose(fp);

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 113: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

r -- open a file in read mode -- if file exits, the marker is positioned at

beginning.-- if file does not exist, error returned.

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 write mode -- if file exits, all its data is erased.-- if file does not exist, it is created.

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 append mode

-- if file exits, the marker is positioned

at end.

-- 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.

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

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);

}

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

/* open a file in read and write mode */int main( ) {

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

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

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 114: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

File Input / Output Functions

fopen(fp, mode) Open existing file / Create new file

fclose(fp) Closes a file associated with file pointer.

closeall ( ) Closes all opened files with fopen()

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.

rewind() 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.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 115: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Text files Vs Binary Files

/* Copying one binary file to other */

#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);

“rb” ���� open a file in read mode

“wb” ���� open a file in write mode

“ab” ���� open a file in append mode

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

“wb+” ����open a file in read and write mode

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

Text File :i) Data are human readable characters.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);

}

i) Data are human readable characters.ii) Each line ends with a newline character.iii) Ctrl+z or Ctrl+d is end of file character.iv) Data is read in forward direction only.v) Data is converted into the internal format

before being stored in memory.Binary File :i) Data is in the form of sequence of bytes.ii) There are no lines or newline character.iii) An EOF marker is used.iv) Data may be read in any direction.v) Data stored in file are in same format that

they are stored in memory.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 116: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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);

Random Access File

ftell(file_pointer)-- returns the current position of file

pointer in terms of bytes from thebeginning.rewind(file-pointer)

-- moves the file pointer to thestarting of the file, and reset it.fseek(fileptr, offset, position)– moves the file pointer to the

location (position + offset)position :

SEEK_SET – beginning of filefseek(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 :

defghText from position 12 :

mnopqrText from position 16 :

qrstuCurrent position : 21Text from starting :

abcdefgh

SEEK_SET – beginning of fileSEEK_CUR – current positionSEEK_END – end of the file

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 117: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Formatted I / O

/* 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++) {

/*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){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);

}

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);

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 118: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

/* 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 );

fputc() fgetc() Individual characters

fputs() fgets() Character Strings

fprintf() fscanf() Formatted ASCII

fwrite() fread() Binary files

write() read() Low-level binary

Standard I / O

Predefined Streamsscanf ("%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)

Predefined Streams

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 119: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Handling Records (structures) in a File

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);scanf ("%s %d %d",p1.name, &p1.age,&p1.runs);fwrite(&p1,sizeof(p1),1,fp);

}fclose(fp);fp = fopen("player.txt","r");printf(“\nRecords Entered : \n");for(i=0;i<3;i++) {

fread(&p2,sizeof(p2),1,fp);printf("\nName : %s\nAge : %d\nRuns : %d",p2.name,p2.age,p2.runs);

}fclose(fp);

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 120: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Error Handling:While operating on files, there may be a chance of having certain errors which willcause 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 ofoperation.6)Attempting to write to a write-protected file.

feof(fp)���� returns non-zero integer value if

we reach end of the file otherwise zero.

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

#include<stdio.h>we reach end of the file otherwise zero.

ferror(fp)���� returns non-zero integer value

if an error has been detected otherwise

zero

perror(string)����prints the string, a colon

and an error message specified by the

compiler

file pointer (fp) will return NULL if it

cannot open the specified file.

#include<stdio.h>

int main(){

FILE *fp;

char ch;

fp=fopen("str.txt","w");

ch=getc(fp);

if(ferror(fp))

perror(“Error Raised : ");

else

printf("%c",ch);

fclose(fp);

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 121: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#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){

fp will return NULL if unable to open

the file

feof(fp) returns 1 if it reaches end of

file otherwise 0.

Output:Enter the filename

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);}

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.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 122: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Structure of FILE pointer

Type: FILEFile 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;

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

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

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

fcloseall();-- Closes all the opened streams in the

File Management Functions

short token;} FILE;

-- Closes all the opened streams in theprogram except standard streams.

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

feof(file_pointer)-- to check if end of file has been

reached.ferror(file_pointer)

-- to check the error status of the fileclearerr(file_pointer)

-- to reset the error status of the file

File status functions

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 123: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH,

B.PHARMACY, MBA, MCA of JNTU-

HYD,JNTU-KAKINADA & JNTU-ANANTAPUR

visit

www.alljntuworld.in

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 124: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Searching techniques

Searching : It is a process to find whether a particular value with specified properties is present or not

among a collection of items.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

Linear_Search (A[ ], N, val , pos )Step 1 : Set pos = -1 and k = 0Step 2 : Repeat while k < N

Begin

int main( ) {int arr [ 50 ] , num , i , n , pos = -1;printf ("How many elements to sort : ");scanf ("%d", &n); Begin

Step 3 : if A[ k ] = val Set pos = kprint posGoto step 5

End whileStep 4 : print “Value is not present”Step 5 : Exit

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);

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.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 125: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Binary_Search (A [ ], U_bound, VAL)Step 1 : set BEG = 0 , END = U_bound , POS = -1Step 2 : Repeat while (BEG <= END )Step 3 : set MID = ( BEG + END ) / 2

void binary_serch ( int a [], int n, int val ) {int end = n - 1, beg = 0, pos = -1;

Binary SearchingAlgorithm: • 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.

Step 3 : set MID = ( BEG + END ) / 2Step 4 : if A [ MID ] == VAL then

POS = MID print VAL “ is available at “, POSGoTo Step 6

End ifif A [ MID ] > VAL then

set END = MID – 1Elseset BEG = MID + 1

End ifEnd while

Step 5 : if POS = -1 thenprint VAL “ is not present “

End ifStep 6 : EXIT

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 );} JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 126: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Sorting is a technique to rearrange the elements of a list in ascending ordescending 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.

Sorting

Types of Internal Sortings

� Bubble Sort

� Insertion Sort

� Selection Sort

� Quick Sort

� Merge Sort

Internal Sorting :If all the data that is to be sorted can be accommodated

at a time in memory is called internal sorting.

External Sorting : It is applied to Huge amount of data that cannot be

accommodated in memory all at a time. So data in diskor file is loaded into memory part by part. Each part thatis loaded is sorted separately, and stored in anintermediate file and all parts are merged into one singlesorted list. JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 127: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Bubble Sort

Unsorted Sorted

Bubbles up the highest

10

47

54

10

54

47

54

47

54

47

54

47

Bubble_Sort ( A [ ] , N )Step 1 : Repeat For P = 1 to N – 1

BeginStep 2 : Repeat For J = 1 to N – P

Begin

12

54

19

23

47

12

23

19

AfterPass 1

10

23

12

19

23

10

19

12

23

19

10

12

After Pass 2

AfterPass 3

AfterPass 4

23

19

12

10

AfterPass 5

Step 3 : If ( A [ J ] < A [ J – 1 ] )Swap ( A [ J ] , A [ J – 1 ] )

End ForEnd For

Step 4 : Exit

Complexity of Bubble_SortThe 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 )

OriginalList

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 128: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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;

} }

}}

Bubble Sort

For pass = 1 to N - 1

For J = 1 to N - pass

A [ J – 1 ] > A [ J ]T

}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 );

}

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

A [ J ] = Temp

F

Return

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 129: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Insertion Sort

78 23 45 8 32 36

23 78 45 8 32 36

23

TEMP

23 45 78 8 32 36

45

8

Insertion_Sort ( A [ ] , N )Step 1 : Repeat For K = 1 to N – 1

BeginStep 2 : Set Temp = A [ K ]Step 3 : Set J = K – 1 Step 4 : Repeat while Temp < A [ J ] AND J >= 0

BeginSet A [ J + 1 ] = A [ J ]Set J = J - 1

End WhileStep 5 : Set A [ J + 1 ] = Temp

End ForStep 4 : Exit

8 23 45 78 32 36

8 23 32 45 78 36

8 23 32 36 45 78

32

36

Step 4 : Exit

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 ;

}}

Complexity of Insertion SortBest Case : O ( n )Average Case : O ( n 2 )Worst Case : O ( n 2 ) JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 130: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Selection Sort ( Select the smallest and Exchange )

23 78 45 8 32 56

8 78 45 23 32 56

8 23 45 78 32 56

8

Smallest

23

32

Selection_Sort ( A [ ] , N )Step 1 : Repeat For K = 0 to N – 2

BeginStep 2 : Set POS = K Step 3 : Repeat for J = K + 1 to N – 1

BeginIf A[ J ] < A [ POS ]

Set POS = J End For

Step 5 : Swap A [ K ] with A [ POS ]End For

Step 6 : Exit

8 23 32 78 45 56

8 23 32 45 78 56

8 23 32 45 56 78

45

56

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 ;

}}

Complexity of Selection SortBest Case : O ( n 2 )Average Case : O ( n 2 )Worst Case : O ( n 2 ) JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 131: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Insertion sort

k = 1; k < n ; k++

temp = a [ k ] j = k - 1

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

Selection sort

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

pos = k

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

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

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

a [ j + 1 ] = temp

return

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

return

a[ j ] < a[ pos ]

pos = j

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 132: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Bubble sort – Insertion sort – Selection sort

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-- It is said to be online sorting because it continues the sorting a list as and when it receives

new elements.-- it does not change the relative order of elements with equal keys.-- reduces unnecessary travel through the array.-- requires low and constant amount of extra memory space.-- less efficient for larger lists.

Selection sort :-- No of swappings will be minimized. i.e., one swap on one pass.-- generally used for sorting files with large objects and small keys.-- It is 60% more efficient than bubble sort and 40% less efficient than insertion sort.-- It is preferred over bubble sort for jumbled array as it requires less items to be exchanged.-- uses internal sorting that requires more memory space.-- It cannot recognize sorted list and carryout the sorting from the beginning, when new elements

are added to the list.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 133: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Quick Sort – A recursive process of sorting

Algorithm for Quick_Sort :

-- 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

8 3 2 11 5 14 0 2 9 4 20

Original-list of 11 elements :

8 3 2 11 5 14 0 2 9 4 20

Set list [ 0 ] as pivot : pivot

pivot

Rearrange ( partition ) the elements into two sub lists :

-- 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.

pivot

Sub-list of lesser elements

Sub-list of greater elements

Apply Quick-sort recursivelyon sub-list

Apply Quick-sort recursivelyon sub-list

Complexity of Quick Sort

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

4 3 2 2 5 0 8 11 9 14 20

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 134: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

9 12 8 16 1 25 10 39

12 8 16 1 25 10 3

3 12 8 16 1 25 10

Pivot

Partitioning for ‘ One Step of Quick Sort ’

3 8 16 1 25 10 12

3 1 8 16 25 10 12

3 1 8 16 25 10 12JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 135: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Quick Sort – Program

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 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 ; 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 );

}

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;

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 136: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

loc = left = beg flag = 0, right = end

pivot = a [ loc ]

Flag == 0

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

right = right - 1

T

BA

loc == left

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

loc = left;

flag = 1

F T

a[ loc ] = pivot

return loc

loc == right

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

flag = 1

F T

BA

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

left = left + 1

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

loc == leftT

loc = partition( a , beg , end )

quick_sort ( a , beg , end )

quick_sort ( a , beg , end )

F

returnJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 137: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Merge Sort ( Divide and conquer )

39 9 81 45 90 27 72 18

Divide the array

39 9 81 45 90 27 72 18

39 9 81 45 90 27 72 18

39 9 81 45 90 27 72 18

-- 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 .

Merge the elements to sorted array

39 9 81 45 90 27 72 18

9 39 45 81 27 90 18 72

9 39 45 81 18 27 72 90

9 18 27 39 45 72 81 90

Merge_sort Algorithm1. If the list is of length 0 or 1, then it is already

sorted. Otherwise:2. Divide the unsorted list into two sublists of

about half the size.3. Sort each sublist recursively by re-applying

merge sort.4. Merge the two sublists back into one

sorted list.

Time complexityWorst case - O(n log n) Best case - O(n log n) typical, O(n ) natural variant Average case - O( n log n )JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 138: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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++; }

Merge Sort - Program

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++ ) {

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 ];

}

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);

}}

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 );

}

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 139: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Merge_Sort

low < high

mid = ( low + high ) / 2

merge_sort (a, low, mid)

TF

merge

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

i <= mid && j <= high

a[ i ] < a[ j ]

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

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

i <= mid

F T

merge_sort (a, mid, high )

Merge (a, low,high , mid)

Return

i <= mid

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

j <= high

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

i = low ; i < k ; i ++

a[ i ] = c [ i ]

returnJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 140: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

www.alljntuworld.in

• For More Materials, Text Books, Previous Papers & Mobile updates of B.TECH,

B.PHARMACY, MBA, MCA of JNTU-

HYD,JNTU-KKAAKKIINNAADDAA && JJNNTTUU--AANNAANNTTAAPPUURR

vviissiitt

www.alljntuworld.in

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 141: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Data Structures

-- Data processing often involves in processing huge volumes of data. Many Companies handle millionrecords 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 complexentity.

-- An Abstract Data Type ( A D T ) not only represents a set of complex data objects, but also includes aset 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 becarried out between the logically related data elements.

Data Structure Some Data structures Data Structure

Linear Non-Linear

Stacks Queues Trees GraphsLinear Lists

Some Data structures ArraysStringsListsStacksQueuesTreesGraphsDictionariesMapsHash TablesSetsLatticeNeural-Nets

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.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 142: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Arrays – Linked Lists

What is a Linked ListThe elements of a linked list are not constrained to

be stored in adjacent locations. The individualelements are stored “somewhere” in memory, ratherlike a family dispersed, but still bound together. Theorder of the elements is maintained by explicit linksbetween them.

Limitations of Arrays1) Fixed in size :

Once an array is created, the size of arraycannot be increased or decreased.

2) Wastage of space :If no. of elements are less, leads to wastage ofspace.

3) Sequential Storage :Array elements are stored in contiguousmemory locations. At the times it might sohappen that enough contiguous locations mightnot be available. Even though the total spacerequirement of an array can be met through a

The Linked List is a collection of elements calledrequirement of an array can be met through acombination of non-contiguous blocks ofmemory, we would still not be allowed to createthe array.

4) Possibility of overflow :If program ever needs to process more than thesize of array, there is a possibility of overflowand code breaks.

5) Difficulty in insertion and deletion :In case of insertion of a new element, eachelement after the specified location has to beshifted one position to the right. In case ofdeletion of an element, each element after thespecified location has to be shifted one positionto the left.

The Linked List is a collection of elements callednodes, each node of which stores two items ofinformation, i.e., data part and link field.

-- The data part of each node consists the datarecord of an entity.

-- The link field is a pointer and contains theaddress of next node.

-- The beginning of the linked list is stored in apointer termed as head which points to the first node.

-- The head pointer will be passed as a parameterto any method, to perform an operation.

-- First node contains a pointer to second node,second node contains a pointer to the third node andso on.

-- The last node in the list has its next field set toNULL to mark the end of the list.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 143: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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 */

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

}

Creating a Singly Linked List

101 NULL

150 n1-node

150head

150 101 720

150n1-node

102 NULL

n2-node720

150 101 720

150

102 910

720

104 NULL

910/* 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 betweensecond node and third node */

n2->next = n4;n4->next = n3;

150head

101 400

150

102 720

400103 910

720

104 NULL

910n1-node n2-node

n4-node

n3-node

150n1-node n2-node

720 910n3-node

150head

101 720

150

102 720

400

103 910

720

104 NULL

910n1-node

n2-node

n4-noden3-nodeJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 144: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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) {

} }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;

Implementing Singly Linked List

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;

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; JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 145: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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

}if(temp!=NULL) {

new = createnode();new->next = temp;prev->next = new;

}}void delnode(struct node **h) {struct node *temp,*prev; int k;

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

}}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)

Implementing Singly Linked List ( continued )

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;

}

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******");

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 146: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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 : ");

/* 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;

Implementing Singly Linked List ( continued )

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 : ");

}}

}

(p->next)->data = t;sorted=0;

}p=p->next;

}}

}

/* 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;}JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 147: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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 polynomialwhile p != null and q != null

if p.exp > q.exp create a node storing p.coeff and p.expinsert at the end of list radvance p

else if q.exp > p.exp create a node storing q.coeff and q.expinsert at the end of list r

Algorithm for adding two polynomials in linked lists

insert at the end of list radvance q

else if p.exp == q.exp if p.coeff + q.coeff != 0

create a node storing p.coeff + q.coeff and p.expinsert at the end of list radvance p, q

end whileif p != null

copy the remaining terms of p to end of relse if q != null

copy the remaining terms of q to end of rJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 148: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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.

Doubly Linked List

A Doubly Linked List is a data structure having an ordered list of nodes, in which each node consistsof two pointers. One pointer is to store the address of next node like in singly linked list. The secondpointer 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.

A B C

head tail

/* a node in doubly linked list */struct node {

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

}

B

A D

C

Tree structure using Doubly Linked ListJNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 149: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

A B C D

A B D

C

q

p q

Insertion of node in Doubly Linked List

Deletion of node in Doubly Linked List

A B C

D

p

A B C

Deletion of node in Doubly Linked List

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 150: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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 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;

Implementing Doubly Linked List

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;

}

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;}

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 151: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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;

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;

Implementing Doubly Linked List ( continued )

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;

}}

(*h)->prev=NULL;free(temp);return;

}temp=*h;while(temp!=NULL && temp->data!=k){

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

}}JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 152: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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")

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 : ");

Implementing Doubly Linked List ( continued )

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******");

}

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 : ");

}}

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 153: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Circular SinglyLinked List

910tail

101 400

150

102 720

400

103 910

720

104 150

910n1-node n2-node n3-node n4-node

-- Singly Linked List has a major drawback. From a specified node, it is not possible to reach any ofthe preceding nodes in the list. To overcome the drawback, a small change is made to the SLL so that thenext field of the last node is pointing to the first node rather than NULL. Such a linked list is called acircular 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.

Circular Doubly Linked List

prev data next prev data next prev data next prev data next

-- A Circular Doubly Linked List ( CDL ) is a doubly linked list with first node linked to last node and vice-versa.

-- The ‘ prev ’ link of first node contains the address of last node and ‘ next ’ link of last node containsthe 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.JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 154: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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;

Implementing Circular Singly Linked List

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(); 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..");

}

new = createnode();if(*t == NULL) {

*t = new; new->next = *t;return;

}head = (*t)->next; (*t)->next = new;new->next = head; *t = new;

}void display(struct node *t) {struct node *temp = t->next, *head=t->next;printf("\nContents of the List : \n\n"); do {printf("\t%d",temp->data);temp = temp->next;

}while(temp!=head);printf(“\n”);

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 155: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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;

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;

}

Implementing Circular Singly Linked List ( continued )

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..");

}

}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..");

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 156: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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");

Implementing Circular SinglyLinked List ( continued )

Data structures are classified in several ways :Linear : Elements are arranged in sequential

fashion. Ex : Array, Linear list, stack, queueNon-Linear : Elements are not arranged in

sequence. Ex : trees, graphsHomogenous : All Elements are belongs to same

Types of Data Structures

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… “);}

}}

Homogenous : All Elements are belongs to samedata type. Ex : Arrays

Non-Homogenous : Different types of Elementsare grouped and form a data structure. Ex:classes

Dynamic : Memory allocation of each element inthe data structure is done before their usageusing D.M.A functions Ex : Linked Lists

Static : All elements of a data structure are createdat the beginning of the program. They cannotbe resized. Ex : Arrays

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 157: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Stacks

-- Stack is an ordered collection of data elements into which new elements may be inserted and fromwhich elements may be deleted at one end called the “TOP” of stack.

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

Applications of stackStack ADT

struct stackNode {int data; struct stackNode *next;

� 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

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

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 158: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

OperationOperation Stack’s contentsStack’s contents TOP valueTOP value OutputOutput

a a

b

d

e

a

b

a

b

c

a

b

a

b

d

a

b

d

a

b

a

Push(a) Push(b) Push(c) Pop( ) Push(d) Push(e) Pop( ) Pop( ) Pop( ) Pop( )

Operations on Stack

1. Init_stack( ) 1. Init_stack( ) <empty> <empty> --112. Push( ‘a’ )2. Push( ‘a’ ) aa 003. Push( ‘b’ )3. Push( ‘b’ ) a ba b 114. Push( ‘c’ )4. Push( ‘c’ ) a b ca b c 225. Pop( )5. Pop( ) a ba b 116. Push( ‘d’ )6. Push( ‘d’ ) a b da b d 227. Push( ‘e’ )7. Push( ‘e’ ) a b d ea b d e 338. Pop( )8. Pop( ) a b da b d 229. Pop( )9. Pop( ) a ba b 11

10. Pop( )10. Pop( ) aa 0011. Pop( )11. Pop( ) <empty><empty> --11

ccccccc ec ec e dc e dc e d bc e d bc e d b ac e d b aJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 159: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#define SIZE 50int 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--];

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;

Implementing Stack ADT using Array

} 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]; }

push(item); break; case 2:item = pop();

printf("\nElement poped : %d",item);printf("\nPress a key to continue...");getche(); break;

case 3:item = peek();printf("\nElement at top : %d",item);printf("\nPress a key to continue..."); getche(); break;

case 4:display();printf("\nPress a key to continue...");getche(); break;

case 5:exit(0);}

}while(1);}JN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 160: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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();

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

}}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:");

Implementing Stack ADT using Linked List

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;

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;

}}

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 161: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Queues

-- Queue is a linear data structure that permits insertion of new element at one end and deletion of anelement at the other end.

-- The end at which insertion of a new element can take place is called ‘ rear ‘ and the end at whichdeletion 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, HenceQueue 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.

Queue ADT struct queueNode {4 rear front struct queueNode {

int data; struct queueNode *next;};� init_queue( )� addq ( )� delq ( )� isEmpty ( )� printQueue ( )

Types of Queues

� circular queues� priority queues� double-ended queues

3 6 8 2 5

addq (4) delq ( )

rear front

7

Applications of Queues

� Execution of Threads� Job Scheduling� Event queuing� Message QueueingJN

TU Worl

dwww.alljntuworld.in JNTU World

JNTU World

Page 162: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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( ){

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

}} 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: ");

Implementing Queue ADT using Array

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 {

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);

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 163: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

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;

else {printf("\nElements in Queue :\n");while(temp!=NULL) {

printf("%5d",temp->data);temp=temp->next;

}}

}int main() {int ch,num;init_queue(); do { printf("\n\tMENU\n\n1. Add\n2. Delete");

Implementing Queue ADT using Liked List

}} 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.");

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);

} JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 164: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

Algorithm to Infix to Postfix Conversion

--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*+

In-To-Post ( infix-expression )Scan the Infix expression left to right

If the character x is an operandOutput the character into the Postfix ExpressionOutput the character into the Postfix Expression

If the character x is a left or right parenthesisIf the character is “(

Push it into the stackIf the character is “)”

Repeatedly pop and output all the operators/characters until “(“ is popped from the stack.If the character x is a is a regular operator

Check the character y currently at the top of the stack. If Stack is empty or y is ‘(‘ or y is an operator of lower precedence than x, then

Push x into stack.If y is an operator of higher or equal precedence than x,

Pop and output y and push x into the stack.When all characters in infix expression are processed

repeatedly pop the character(s) from the stack and output them until the stack is empty.JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 165: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#define STACKSIZE 20typedef 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);

} elsesptr->items[++sptr->top]= ps;

}char pop(STACK *sptr) {

if(sptr->top == -1) {printf("Stack is empty\n"); exit(1);

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));

In-Fix To Post-Fix convertion

printf("Stack is empty\n"); exit(1);} elsereturn 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 == ')‘ ){

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));

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 166: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

#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);

}

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

break;}

} j++;

}return pop();

}int main() {

int j=0;char expr[20];float number[20],result;

Evaluation of Post-Fix Expression

}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;

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);

}JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World

Page 167: Computer -- Hardware JNTU World · Computer -- Hardware Key board Mouse Input Devices Monitor Printer Output Devices Input Storage Area Program Storage Area Output Storage Area

JNTU W

orld

www.alljntuworld.in JNTU World

JNTU World