578
Why C? C is simple C is small C is fast C offers better interaction with hardware

C SLIDES PREPARED BY M V B REDDY

Embed Size (px)

DESCRIPTION

 

Citation preview

Why C? C is simple C is small C is fast C offers better interaction with

hardware

Introduction

Historical Development of C

1960 International Committee

1972 Dennis Ritchie, AT & T Bells Lab

1963 National Committee

1967 1 Man Committee

1970 Ken Thompson, AT & T Bells Lab

ALGOL 60

CPL

Martin Richards - BCPL

B

C

Where C Stands

Machine Oriented Problem Oriented

Computer Languages

Better Machine efficiency

Better Programming efficiency

Ex. Assembly, Machine

Ex. Basic, Fortran, Pascal,Cobol

LLL HLL

In The Beginning...

Alphabets, Digits

Words, Numbers

Sentences

Paragraph

Alphabets, Digits, Sp. Symbols

Constants, Variables, Keywords

Statements or Instructions

Program

English C

AlphabetsA - Z, a - z

Digits0 - 9

Sp. SymbolsTotal - 32

Alphabets, Digits, Special Symbols

Constants and Variables

3 x + 2 y = 20

Constants

Variables

Constants

C Constants

PointerInteger

Primary Secondary

RealCharacter

ArrayString

Enum

StructureUnion

etc.

Integer Constants

4. Valid Range: -32768 to +32767

Rules:Ex. 421 -62 +45 4096

72 72.01. No decimal point.

2. May be +ve or -ve. Default: +ve

32,500 4 7 3

3. No comma or

spaces

Real Constants

1. Must contain a decimal point.

2. May be +ve or -ve. Default: +ve

3. No comma or spaces.

4. Valid Range: -3.4x 1038 to +3.4 x 1038

Rules:

Ex. 427.62 +24.297 -0.00254

Fractional Form

Forms of Real Constants427.62

+24.295-0.00254

4.2762 2Mantissa Exponent

E

4.2762E2

Exponential Form

2.4295e1-2.54e-3

Rule : A single character enclosedwithin a pair of ’ ’.

Character Constants

‘Z’ ’Nagpur’

Ex. ’A’ ’m’ ’3’ ’+’

Are They OK?

PointerArrayStringStructureUnionEnumetc.

IntegerRealCharacter

Primary Secondary

C Variables

Is it necessary to identify types?Yes.

Variables

How many types?As many as the types of constants.

Why?

Why?

What Happens in Memory...

xy

z

x = 3

Memory

34

7

y = 4z = x + y

So A Variable is... An entity whose value can

change

A name given to a location in memory

33.0’3’

abc

How to Identify TypesInteger ConstantReal ConstantCharacter Constant

?

??

Different Languages, Different Rules

i...n - Integera - h, o - z - Real

a% - Integerb! - Realc$ - Character

BASIC FORTRAN

C’s Way of Identifying Variables

int a float b char ca = 3 b = 3.0 c = ’3’

First character must be an alphabet, restcan be alphabets, digits, or underscores.

Ex. pop98, si_int

Rules for Building Variable Names

Length <= 8 (Usually)

No commas or spaces

Variable names are case sensitiveEx. abc ABC Abc aBc AbC

_- si-int

si_int

C Keywords

How many?

What are Keywords?

What are Reserved words?

Would This Work?

And How About This...

int float float charfloat = 3 char = 3.14

integer areal bcharacter c

Where Do We Stand?

Alphabets, Digits, Sp. Symbols

Constants, Variables, Keywords

Statements or Instructions

Program

C

The First C Programp = 1000.50

n = 3

r = 15.5

si = p * n * r / 100

Declaring Variables...

Tip1: All variables must be declared.

p = 1000.50n = 3 r = 15. 5si = p * n * r / 100

float p, r, siint n

Printing Values...float p, r, siint np = 1000.50n = 3r = 15. 5si = p * n * r / 100 printf ( si ) ”%f”,

Terminology Matters( ) Parentheses{ } Braces[ ] Brackets

General Form of printf( )printf ( ”format string”, list of variables )

%i - integer%f - float

%c - character

Ex. printf ( ”%f %f %f %i”, p, r, si, n )

can contain

Statement Terminators

float p, r, si ;int n ;

: colon ; semicolon

I am a boy I go to school

Statement Terminator

float p, r, siint n

Free Form Languagefloat p, r, si ;int n ;

is same as

float p, r, si ; int n ;

What To Executemain( )

Collective Name

float p, r, si ;int n ;p = 1000.50 ;n = 3 ;r = 15. 5 ;si = p * n * r / 100 ;printf ( ”%f”, si ) ;

What Belongs to main( )main( ){

float p, r, si ;int n ;p = 1000.50 ; n = 3 ; r = 15. 5 ;si = p * n * r / 100 ;printf ( ”%f”, si ) ;

}

main( ){

float p, r, si ;int n ;p = 1000.50 ; n = 3 ; r = 15. 5 ;si = p * n * r / 100 ;printf ( ”%f”, si ) ;

}

Comments Are Useful

RemarkNote

/* Calculation of simple interest */

Tips About Comments

Any number of comments anywhere

Nested comments -/* .............. /* ....... */ ........ */

Multiline comments -/* .............................

............................... */

A More General Program/* Calculation of simple interest */main( ){

float p, r, si ; int n ;printf ( ”Enter values of p, n and r : ” ) ;scanf ( ”%f %i %f”, p, n, r ) ;si = p * n * r / 100 ;printf ( ”%f”, si ) ;

}

&& &

‘Address of ’operator

1000.50 3 15

Try Your Hand At...Page No. 34 - 35

[G] (a) to (f)

C Compilers

Turbo C Quick C Microsoft C Aztech C Zortech C Lattice C Watcom C GreenLeaf C Vitamin C

All Provide an IDE

Integrated Development Environment

I D E

Editor

Compiler

PreprocessorLinker

Debugger

Editor and Compiler

Editor - Helps in typing / editing of a program

Compiler - Converts C language program to machinelanguage program

Editing Commands

Del Up Arrow Down Arrow Right Arrow Left Arrow

Cursor Movement Deletion

Ctrl+PgUp Ctrl+PgDn

Home EndPgUp PgDnCtrl+Home Ctrl+End

BackspaceCtrl+TCtrl+Y

Computers are fun

Screen

File

Some More Commands

F2 SaveCtrl+F9 CompileAlt+F5 Output-

Screen

Tip: Use meaningful filenames. Ex. CH1PR1.C

NewSaveSave AsOpenExitDos Shell

File Menu Miscellaneous

Permanent

Temporary

Interchanging Contents of Two Variablesmain( ){

printf ( ”Enter values of c and d” ) ;

c d5 10

c d10 10

c d10 10

c = d ;d = c ;

scanf ( ”%i%i”, &c, &d ) ;

5 10

printf ( ”%i %i”, c, d ) ; }

int c, d ;

10 10

Interchanging Contents of Two Variables

main( ){

printf ( ”Enter values of c and d” ) ;

c d5 10

tx

c d5 10

t5

c d10 10

t5

c d10 5

t5

t = c ;c = d ;

d = t ;

printf ( ”%i %i”, c, d ) ; }

int c, d , t ;

scanf ( ”%i%i”, &c, &d ) ;

5 10

10 5

One More Way

scanf ( ”%i%i”,&c, &d ) ;

c d25 10c d

25 15c d

10 15

c = c + d ;d = c - d ;c = c - d ;

15 10

c d15 10

main( ){

printf ( ”Enter a five digit no.” ) ; scanf ( ”%d”, &n ) ;

Sum of Digits2 6 9 1 3

d1

26913

d3d2 d4 d5int n ;

.. ..

.. ..}

Calculations

10 26913 2691

26913 / 10 2691 - Division

26913 % 10 3 - Modular division

3

26910

Mod

The Whole Picturemain( ){

…3 2691d5

n

d4

d3

d2

d1

1

9

6

2

269

26

2

2

26913

d5 = n % 10 ;

d4 = n % 10 ;

d3 = n % 10 ;

d2 = n % 10 ;

d1 = n % 10 ; s = d1 + d2 + d3 + d4 + d5 ;printf ( ”%i”, s ) ;

}

n = n / 10 ;

n = n / 10 ;

n = n / 10 ;

n = n / 10 ;

21

Is % ( modulus ) Really Useful

Leap year or not Odd / Even Prime or not

Where Are We....

Alphabets, Digits, Sp. Symbols

Constants, Variables, Keywords

Statements or Instructions

Program

C Statements / Instructions

Type Declaration InstructionEx. int i, j, k ;

float a, b, c ;char ch ;

Type Declaration, A few Subtleties

int a = 5, b = 10, c = a + b * 5 % 2 ;Here order is important

int a ;a = 5 ;

is same as

int a = 5 ;

Is This Ok?

int a, b, c, d ;a = b = c = d = 5 ;

int a = b = c = d = 5 ;

C Statements/Instructions

Type Declaration Instructions

Arithmetic InstructionsEx. s = d1 + d2 + d3 ;

si = j * n * r / 100 ;c = 5.0 / 9 * f - 32 ;

+, -, *, /, % - Arithmetic Operators

a = b ( c + d ) ;a = b * ( c + d ) ;

Arithmetic Instructions, a few Small Issues

i = j * k + 3 ;j * k + 3 = i ;

i = 3 ;3 = i ;

Tip:

Tip:

Type of Arithmetic Instructions

Integer mode AI Real mode AI Mixed mode AI

c a b 5 6 14

Ex. int a = 3, b = 4, c ;c = a * b + 5 % 6 - b + 14 ;

????

* + % - +=;

Integer mode AI

Legal Arithmetic Operations

Operand1 Operand2 Result

int int float float int float float int

intfloatfloatfloat

Try This

int a ;a = 5 / 2 ;a = 5.0 / 2 ;a = 5 / 2.0 ;a = 5.0 / 2.0 ;a = 2 / 5 ;a = 2.0 / 5 ;a = 2 / 5.0 ;a = 2.0 / 5.0 ;

22220000

Try Thisfloat a ;a = 5 / 2 ;a = 5.0 / 2 ;a = 5 / 2.0 ;a = 5.0 / 2.0 ;a = 2 / 5 ;a = 2.0 / 5 ;a = 2 / 5.0 ;a = 2.0 / 5.0 ;

2.02.5

0.00.4

2.52.5

0.40.4

Which Is Correct?

float c, f = 212.0 ;

c = 5 / 9 * ( f - 32 ) ;

c = 5 / 9.0 * ( f - 32 ) ;

c = ( f - 32 ) * 5 / 9 ;

0.0

100.0

100.0

Note: Parenthesis matter

Heirarchy/Priority/Precedence

c = a + b * c % 5 - d * 61

2

4

Operators

* / %+ -=

6

3

5

C Instructions

Type declarations Instructions Arithmetic Instructions Input / Output Instructions

printf( ) - Outputscanf( ) - Input

General Form of printf( )

printf ( ”format string”, list of variables ) ;

printf ( ”Enter values of c and d” ) ; List of variables is optional.

printf ( ”%i %i %i”, a, 35, 2 + 6 % 3 ) ; List can contain variables,

constantsor expressions.

printf( )

- int - %i , %d- float - %f- char - %c

Escape sequences

Any othercharacters

can contain

printf ( ”format string”, list of variables ) ;

Format specifiers

Numbering Systems

Binary( 0 - 1 )011011100...1111000….….

Decimal( 0- 9 )01 .91011..99

100......

Octal( 0- 7 )01.71011..77100......

Hexadecimal( 0-9, A- F )01.9A.F10..FF100

Conversions

Deci 473 decimal 4 * 102+ 7 * 101 + 3 * 100 = 473

Octal 11 decimal 1 * 81 + 1 * 80 = 9decimalHexa 11 1 * 161 + 1 * 160 = 17

Binary 11 1 * 21 + 1 * 20 = 3 decimal

More Conversions

Dec. 9 Octal 11

8 9 8 1 1

0 1

Dec. 17 Hex 11

16 1716 1 1

0 1

Dec. 3 Binary 11

2 32 1 1

0 1

printf( ) Makes It Handy

printf ( ”%d %o %x %X”, 10, 10, 10, 10 ) ;

10 12 a A

10 10 10 10

Error printf ( ”%d %d %d %d”, 10, 12, a, A ) ;

printf ( ”%d %d %d %d”, 10, 012, 0xa, 0XA ) ;

zero or O?

Escape Sequences

\n - Newline \t - Tab printf ( ”%d\n%d\t%d”, 10, 20, 30 ) ;

1020 30

Any Other Characters

printf ( ”Enter values of c and d” ) ; printf ( ”Hello” ) ; printf ( ”\nSimple Interest = Rs. %f”, si ) ;

Escape sequence Format

specifierAny other character

C Instructions

Type Declaration

Arithmetic Instruction

Input/Output Instruction

Control Instructions

Let Us C Chapter 1 - Page 29-36

Try At Home

C InstructionsType Declaration InstructionsArithmetic Instructions Input / Output InstructionsControl Instructions

Control Instructions

What are they?- Control the sequence of executionof instructions

What different types?- Sequence- Decision- Repitition- Case

Normal C Programmain( ){

int ..... ; float ...... ;printf ( ...... ) ;scanf ( ...... ) ;a = .... ;b = .... ;printf ( .......) ;

}

Tip: Sequence CI is the default CITip: Sequence CI is the default CI

Decision Control Instruction/* Calculation of total expenses */main( ){

int qty ;float price ;printf ( ”Enter quantity and price” ) ;scanf ( ”%d%f”, & qty, &price ) ;......

}

/* Calculation of total expenses */main( ){

int qty ; float price ;printf ( ”Enter quantity and price” ) ;scanf ( ”%d%f”, &qty, &price ) ;

}

if ( qty >= 1000 )dis = 10 ;

- qty * price * dis / 100 ;totexp = qty * priceprintf ( ”Total expenses = Rs %f”, totexp ) ;

1200 15.50

200 15.50

int dis ; float totexp ;

elsedis = 0 ;

Tips if, else - Keywords General form:

if ( condition )statement1 ;

elsestatement2 ;

Cond. is usually built using <, >, <=, >=, = =, !=

Relational Operators

a = b

a = = bAssignment

Comparison

int a = 3, b = 4, c, d ;printf ( ”%d”, a + b ) ;

Would This Work?

7

0

12

1

Tip: Condition - True - Replaced by 1Condition - False - Replaced by 0

Tip: Condition - True - Replaced by 1Condition - False - Replaced by 0

printf ( ”%d”, a <= b ) ;c = a * b ;printf ( ”%d”, c ) ;d = a = = b ;printf ( ”%d”, d ) ;

Is it Monday or Tuesday

int a ;printf ( ”%d”, a ) ; Garbage

Tip: Unless specifically initialised avariable contains a garbage value.

Tip: Unless specifically initialised avariable contains a garbage value.

/* Calculation of Total Expenses */main( ){

Tip: else block is optionalTip: else block is optional

if ( qty >= 1000 )dis = 10 ;

printf ( ”Enter quantity and price” ) ;scanf ( ”%d%f” , &qty, &price ) ;

int qty ; int dis ;float price ;

totexp = qty * price - qty * price * dis / 100 ;

= 0 float totexp ;

printf ( ”Total expenses = Rs %f”, totexp ) ;}

main( ){

printf ( ”Enter basic salary” ) ;scanf ( ”%f”, &bs ) ;

/* Calculation of gross salary */

float bs, hra, ca, da, gs ;

if ( bs >= 1500 )da = bs * 95 / 100 ;hra = bs * 20 / 100 ;ca = bs * 12 / 100 ;

elseda = bs * 92 / 100 ;hra = bs * 15 / 100 ;ca = 200 ;

gs = bs + hra + da + ca ;printf ( ”Gross salary = Rs. %f”, gs ) ;

}

only thisbelongs toif block

only thisbelongs toelse block

/* Calculation of gross salary */main( ){

float bs, hra, ca, da, gs ;printf ( ”Enter basic salary” ) ;scanf ( ”%f”, &bs ) ;if ( bs >= 1500 ){

da = … ; hra = ... ; ca = … ;}else{

da = … ; hra = ... ; ca = … ;}gs = bs + da + hra + ca ;printf ( ”Gross salary = Rs %f”, gs ) ;

}

One More Formif ( condition ){

statement1 ;statement2 ;

}else{

statement3 ;statement4 ;

}Tip: - Default scope of if and else is only the

next statement after them. Tip: - Default scope of if and else is only the

next statement after them. - To override the default scope use { }

Leap Year or Notmain( ){

printf ( ”Enter year” ) ;scanf ( ”%d”, &y ) ;

4 1996 499 1996

0Leap

4 2000 5002000

0 Leap

4 1900 475 1900

0 Not Leap

int y ;

…}

main( ){

. . . if ( y % 100 == 0 ){

if ( y % 400 == 0 )printf ( ”Leap” ) ;

elseprintf ( ”Not Leap” ) ;

}else{

if ( y % 4 == 0 )printf ( ”Leap” ) ;

elseprintf ( ”Not Leap” ) ;

}}

Nested if-elsestatements are legal.

Decide First Day of Any Year

main( ){

int y ;printf ( ”Enter year” ) ;scanf ( ”%d”, &y ) ; . . .

}

1998

The Logic Behind It

………1/ 1/ 1998

1 /1 / 1 Monday29/ 1 / 1 ?

1/ 1/ 1 to 28/1 / 1

28 % 7

1/ 1/ 1 to 31/ 12/ 1997

? % 7

0

?

1/ 1/ 1 Monday

15/ 1/ 1 Monday

22/ 1/ 1 Monday

29/ 1/ 1 Monday

?

8/ 1/ 1 Monday

main( ){

printf ( ”Enter year” ) ;scanf ( ”%d”, &y ) ;

totaldays = normaldays + leapdays ;firstday = totaldays % 7 ;if ( firstday == 0 )

printf ( ”Monday” ) ;.. .... ..

}

leapdays =( y - 1 ) / 4- ( y - 1 ) / 100 + ( y - 1 ) / 400 ;

1/ 1/ 1 to 28/ 1/ 1

28 % 7

1/ 1/ 1 to 31/ 12/ 1997

? % 7

0

?

int y ;, firstday, normaldays, leapdays, totaldays ;

normaldays = ( y - 1 ) * 365 ;

main( ){

int y, firstday, leapdays ;

.. ..

.. ..

normaldays = ( y - 1 ) * 365 ;.. .... ..

}

long int normaldays, totaldays ;

int -32678 to +32767long int -2147483648 to +2147783647

normaldays = ( y - 1 ) * 365 ;

What’s Wrong Here?

float a ;a = 5 / 2.0 ;

float a ;a = 5 / 2 ;

Soln: normaldays = ( y - 1 ) * 365L ;

int i ;long int j ;printf ( ”%d %d”, sizeof ( i ), sizeof ( j ) ) ; printf ( ”%d %d”, sizeof ( int ), sizeof ( long int ));

The sizeof( ) Operator

OperatorKeyword

2 42 4

Are You Sure?

4 % 33 % 4-3 % 43 % -4-3 % -4

13-33

-3

Tip: Sign of remainder is same as sign of numeratorTip: Sign of remainder is same as sign of numerator

Try Your Hand At

Exploring C Chapter 1Let Us C Chapter 2 Pg 60 - 64 ( e )

What Will Be The Outputmain( ){

int a = 5, b = 10 ;if ( a >= 20 ) ;

b = 30 ;printf ( ”%d”, b ) ;

}

; - Null statement. Doesn’t do anything on execution

; - Null statement. Doesn’t do anything on execution

30

What Will Be The Outputmain( ){

int a = 10 ;if ( a = 5 )

printf ( ”Hi” ) ;}

if ( a = 5 ) if ( a ) if ( 5 )

Tip : Truth in C is nonzero, whereas, falsity is zero.

Tip : Truth in C is nonzero, whereas, falsity is zero.

if ( per >= 60 )printf ( ”First division” ) ;

else{

if ( per >= 50 )printf ( ”Second division” ) ;

Three Problems

int m1, m2, m3, m4, m5 ;

main( ){

printf ( ”Enter marks in five subjects” ) ;scanf ( ”\n%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5 );per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;

int per ;

else{

if ( per >= 40 )printf ( ”Third division” ) ;

elseprintf ( ”Fail” ) ;

}}

}

main( ){

int m1, m2, m3, m4, m5, per ;printf ( ”Enter marks in five subjects” ) ;scanf ( ”%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5 ) ;per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;

if ( per >= 60 )printf ( ”First division” ) ;

if ( per >= 50 )printf ( ”Second division” ) ;

if ( per >= 40 )printf ( ”Third division” ) ;

elseprintf ( ”Fail” ) ;

}

Anything Wrong?

?

main( ){

int m1, m2, m3, m4, m5, per ;printf ( ”Enter marks in five subjects” ) ;scanf ( ”%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5 ) ;per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;

if ( per >= 60 )printf ( ”First division” ) ;

if ( per >= 50 && per < 60 )printf ( ”Second division” ) ;

if ( per >= 40 && per < 50 )printf ( ”Third division” ) ;

elseprintf ( ”Fail” ) ;

}

Still Anything Wrong?

main( ){

int m1, m2, m3, m4, m5, per ;printf ( ”Enter marks in five subjects” ) ;scanf ( ”%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5 ) ;per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;

if ( per >= 60 )printf ( ”First division” ) ;

if ( per >= 50 && per < 60 )printf ( ”Second division” ) ;

if ( per >= 40 && per < 50 )printf ( ”Third division” ) ;

if ( per < 40 )printf ( ”Fail” ) ;

}

Is This Better?

Logical Operators

&& - And|| - Or! - Not

Useful in

Checking Ranges

Yes / No Problem

int age ;main( ){

printf ( ”Enter age, sex, marital status” ) ;scanf ( ”%d%c%c”, &age, &s, &ms ) ;if ( ms == m )

printf ( ”Insured” ) ;else{

if ( s == m ){

if ( age > 30 )printf ( ”Insured” ) ;

elseprintf ( ”Not Insured” ) ;

}else{

if ( age > 25 )printf ( ”Insured” ) ;

char s, ms ;

elseprintf ( ”Not In.” ) ;

}}

}

26 m u’ ’

’ ’

Not InsuredNot Insured

Program Using Logical Operatorsmain( )

{int age ;char s, ms ;printf ( ”Enter age, sex, marital status” ) ;scanf ( ”%d%c%c”, &age, &s, &ms ) ;

}

if ( ms = = ’m’ ms = = ’u’ s = = ’m’ age > 30ms = = ’u’ s = = ’f’ age > 25 )

else

printf ( ”Insured” ) ;

printf ( ”Not Insured” ) ;

)(||

||( )

)(&&&&

&&&&

26 m u

Not InsuredNot Insured

Working of && And ||

True True

TrueTrue

False FalseFalseFalse

cond2 cond1 && cond2 cond1 || cond2cond1

True TrueFalse FalseTrue FalseFalse True

Hierarchy of Operators

Operators Type! Logical Not* / % Arithmetic+ - Arithmetic< > <= >= Relational= = != Relational&& Logical And|| Logical Or= Assignment

Increasing Priority

Other UnaryOperators - + & sizeof

Exchanging Blocks

main( ){

int a = 3, b = 4 ; if ( a <= b )

printf ( ”A” ) ; else

printf ( ”B” ) ;}

main( ){

int a = 3, b = 4;

}

if ( )printf ( ”B” ) ;

elseprintf ( ”A” ) ;

a > b

Output: AOutput: A

One More Way

main( ) {

int a = 3, b = 4 ;if ( a <= b )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

main( ) {

int a = 3, b = 4 ;if ( )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

! a > b

Output: BOutput: A

The Correct Waymain( ){

int a = 3, b = 4 ;if ( ! ( a > b ) )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

Output: A

main( ){

int a = 3, b = 4 ;if ( a > b )

printf ( ”B” ) ;else

printf ( ”A” ) ;}Output: A

Yet Another Waymain( ){

int a = 3, b = 4 ;if ( )

printf ( ”B” ) ;else

printf ( ”A” ) ;}

! ( a <= b )

Output: A

What Would be The Output

main( ){

int a = 3, b = - 4, c ,d ;c = !a ;d = !b ;printf ( ”%d %d %d %d”, c, d, a, b ) ;

}

0

0

3

- 4

Point Out The Error

main( ){

int a = 3, b = 4, c ;

c = !a || b = 7 ;printf ( ”%d %d”, b, c ) ;

}

LvalueRequired

main( ){

int a = 3, b = 4, c ;c = !a || ( b = 7 ) ;printf ( ”%d %d”, b, c ) ;

}

What Would be The Output

7 1

Yet Another Way

main( ){

:?

Conditionaloperators

How are theydifferent?

main( ){

int a = 3, b = 4 ;if ( a <= b )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

Output: A

printf ( ”A” ) printf ( ”B” ) ;a <= b}

int a = 3, b = 4 ;

How Would You Convert

main( ){

int a = 3, b = 4 ;if ( a <= b )

printf ( ”A” ) ;}

main( ){

int a = 3, b = 4 ;a <= b ? printf ( ”A” ) ;

}

Error

Remove The Error

main( ){

int a = 3, b = 4 ;a <= b ? printf ( ”A” ) : ;

}Necessary

No Errors At Last

main( ){

int a = 3, b = 4 ;a <= b ? printf ( ”A” ) : ; ;

}

TerminatorTerminator

Null Statement

Soln: a <= b ? printf ( ”A” ) : printf ( ” ” ) ;a <= b ? printf ( ”A” ) : ( z = 3 ) ;

Dummies

Moral of The Story

Use one, use anotherDummy statementNot a replacement for if-else

Only 1 statement in ? partand one in : part

Some More Different Waysmain( )

{int a = 3, b ;a <= 5 ? ( b = 10 ) : ( b = 20 ) ;printf ( ”%d”, b ) ;

}

b = a <= 5 ? 10 : 20 ;printf ( ”%d”, b ) ;

printf ( ”%d”, a <= 5 ? 10 : 20 ) ;

( ) Necessary

Practice Hasn’t Harmed Anybody

Exploring C Chapter 2Let Us C Chapter 2

Conversionsmain( ){

int a = 10, b = 20 ;float c = 3.14 , d = 6.28 ;printf ( ”%d %d %f %f ”, a, b, c, d ) ;printf ( ”%d %d %f %d ”, a, b, c, d ) ;printf ( ”%f %d %f %f ”, a, b, c, d ) ;

} 10 20 3.140000 010 20 3.140000 0

10 20 3.140000 6.28000010 20 3.140000 6.280000

2.68 e 154 7864 0.000000 -1.827 e 2592.68 e 154 7864 0.000000 -1.827 e 259

main( ){

int i = 65, j = 90 ;char ch = ’A’, dh = ’Z’ ;printf ( ”%d %d %c %c”, i, j, ch, dh ) ;

Conversions Continued...

65 90 A Z65 90 A Z

A ZA Z

65 9065 90

printf ( ”%c %c”, i, j ) ;printf ( ”%d %d”, ch, dh ) ;

}

2 652 32 12 16 02 8 0 2 4 02 2 02 1 0

0 1

Divisions,multiplications

illegal

i a ch

i a

?

int i = 65 ; float a = 3.14 char ch = ’A’

3.14

01000001 0’s and 1’s ?

chDec 65 Bin 01000001

Some method involving division by 2 and

multiplication by powers of 2

’A’

Our Own Scheme 2 Binary Digits 00 01 10 11

A B C D

3 Binary Digits 000 001 010 011 100 101 110 111A B C D E F G H

4 Binary Digits 24 = 16 combinations

5 Binary Digits 25 = 32 combinations

00000 00001 00010 .. .. .. .. 26 CombinationsA B C .. .. .. .. 26 Alphabets

Characters to be Represented

26 Capital letters ( A- Z )26 Smallcase letters ( a - z )10 Digits ( 0 - 9 )32 Special Symbols ( + - * / . : ; etc. )34 Non-printable chars - control chars128 Graphic characters

256 Characters

Our Own Scheme

2 Bits 22 = 4 Combinations3 Bits 23 = 8 Combinations4 Bits 24 = 16 Combinations5 Bits 25 = 32 Combinations6 Bits 26 = 64 Combinations7 Bits 27 = 128 Combinations8 Bits 28 = 256 Combinations

Graphics Characters

Character ASCII value218191192 217 196 179

00001111 01001111 10101010 256 combinationsA B C 256 characters

Workable Scheme?

01000001 A01000010 B01000011 C01000100 D01000101 E…. ..…. ..

ASCII Codes

Binary Is Difficult

Binary

A 01000001B 01000010C 01000011D 01000100E 01000101.. ….

Decimal

6566676869..

Character

Characters to be Represented

26 Capital letters ( 65 - 90 )26 Smallcase letters ( 97 - 122 )10 Digits ( 48 - 57 )32 Special Symbols ( )34 Non-printable chars ( 0 - 33 ) 128 Graphic characters ( 128 - 255 )

256 Characters ( 0 - 255 )

printf ( ”%d”, ch ) ;

Methods Are Different

printf ( ”%c”, i ) ;

int i = 65 ; char ch = ’A’ ;i ch

01000001 01000001

65

A

What About More Than 255

int i = 300, j = 65 ;

printf ( ”%c”, i ) ;

printf ( ”%c”, j ) ;

00000001 00101100

00000000 01000001j

i

Higher Lower

Only lower bytegets used

Why Unreliable Conversionsfloat i = 3.14 ; printf ( ”%c”, i ) ;printf ( ”%d”, i ) ;

0s and 1s 0s and 1s 0s and 1s 0s and 1s

i

int i = 35 ; printf ( ”%f”, i ) ;

0s and 1s 0s and 1s

i

Control Instructions

Sequence Decision - if-else

- ? :- < > <= >= = = !=- && || !

Repitition / Loop control instruction

To Begin With...

printf ( ”Simple interest = Rs %f”, si ) ;}

main( ){

printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;

int p, n ;float r, si ;

Repeat with whilemain( ){

int p, n ;float r, si ;

printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;printf ( ”Simple interest = Rs %f”, si ) ;

}

Tip : while - Keyword

while

Any Conditionmain( ){

int p, n, i ;float r, si ;

while ( )printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;printf ( ”Simple interest = Rs %f”, si ) ;

}

i <= 10

Initialization Necessarymain( ){

int p, n, i ; float r, si ;

while ( i <= 10 )printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;printf ( ”Simple interest = Rs %f”, si ) ;

}

i = 1 ;

So Also Incrementationmain( ){

int p, n, i ; float r, si ;i = 1 ;

while ( i <= 10 )printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;printf ( ”Simple interest = Rs %f”, si ) ;

}i = i + 1 ;

Scope And Default Scopemain( ){

int p, n, i = 1 ; float r, si ;while ( i <= 10 ){

printf ( ”Enter values of p, n, r” ) ;scanf ( ”%d%d%f”, &p, &n, &r ) ;si = p * n * r / 100 ;printf ( ”Simple interest = Rs %f”, si ) ;i = i + 1 ;

}}

Logic Doesn’t Matter

main( ){

int i ;i = 1 ; while ( i <= 10 ){

/* any logic */i = i + 1 ;

}}

Loop Counter /Index variable

/* Initialisation of loop counter */

/* Testing of loop counter */

/* Incrementation of loop counter*/

More On Loop Counters

Loop counters can be integers, long integers, floats or characters

Loop counters can be incremented or decremented by any suitable step value

Another Program

/* Print numbers from 1 to 10 */

main( ){

int i = 1 ;printf ( ”%d”, i ) ;

}

Put it in a Loop

/* Print numbers from 1 to 10 */

main( ){

int i = 1 ;while ( i <= 10 ){

printf ( ”%d”, i ) ;

}}

i = i + 1 ;

Another Way/* Print numbers from 1 to 10 */

main( ){

int i = 1 ;while ( i <= 10 ){

printf ( ”%d”, i ) ;

}}

i ++ ;

++ Increases value of a variable by 1 -- Decreases value of a variable by 1 **

//%%

Incrementation / Decrementation Operators

Don’t make sense

Are They OK

i = i + 1 i++ i = i + 2 i+++ i = i + 10 ?Tip : +++ doesn’t exist

Would This Work

i = j---2 ;

int i, j = 3 ;i = --j ;i = --3 ;

i = j----2 ; i = j----2 ;

Space Matters

i = j-- - -2 ;i = j----2 ;

ComplusoryOptional

Is i++ Same As ++i

main( ){

int i = 1 ;while ( i <= 10 )

printf ( ”%d”, i++ ) ;}

1Output : 2 3 4 ……9 10

1 st oper. - Printing2 nd oper. - Incrementation1 st oper. - Printing2 nd oper. - Incrementation

main( ){

int i = 1 ;while ( i <= 10 )

printf ( ”%d”, ++i ) ;}

Output :

Using ++i

2 3 4 5 ……9 10 11

1 st oper. - Incrementation2 nd oper. - Printing1 st oper. - Incrementation2 nd oper. - Printing

The Correct Way

main( ){

int i = 0 ;while ( i < 10 )

printf ( ”%d”, ++i ) ;}

1Output : 2 3 4 ……9 10

Moral?

main( ){

int i = 1 ;while ( i <= 10 )

printf ( ”%d”, i++ ) ;}

main( ){

int i = 0 ;while ( i < 10 )printf ( ”%d”,++ i ) ;

}

Two More Ways

main( ){

int i = 0 ;while ( i++ < 10 )

printf ( ”%d”, i ) ;}

main( ){

int i = 0 ;while ( ++i <= 10 )

printf ( ”%d”, i ) ;}

1 st oper. - Incr2 nd oper. - Testing1 st oper. - Incr2 nd oper. - Testing

1 st oper. - Testing2 nd oper. - Incr1 st oper. - Testing2 nd oper. - Incr

Comparemain( ){

int i = 1 ;while ( i <= 10 )

printf ( ”%d”, i++ ) ;}

main( ){

int i = 0 ;while ( i < 10 )

printf ( ”%d”,++ i ) ;}

main( ){

int i = 0 ;while ( ++i <= 10 )

printf ( ”%d”, i ) ;}

main( ){

int i = 0 ;while ( i++ < 10 )

printf ( ”%d”, i ) ;}

While ( We Don’t Meet Again )

Let Us C Page 96-99 ( f )

Print Nos. From 1 to 10

main( ) {

int i = 1 ;while ( i <= 10 ){

printf ( ”%d”, i ) ;

}}

a = a * 10 ;

a *= 10 ;

b = b % 5 ;

b %= 5 ;

+= -= *= /= %= Compound Assignment Oper.+= -= *= /= %= Compound Assignment Oper.

i += 1 ;

Same as i++, ++i, i = i + 1

One More Way

main( ){

int i = 1 ;while ( ){

printf ( ”%d”, i ) ;i++ ;

}}

/* Repeat infinite times */1

Any Non-Zero number

Applying Brakesmain( ){

int i = 1 ;while ( 1 ) /* Repeat infinite times */{

printf ( ”%d”, i ) ;i++ ;

}}

if ( i > 10 )break ;

Keyword

if ( i > 10 )exit( ) ;

if ( i > 10 )exit( ) ;

break - Terminates Loopexit( ) - Terminates Programbreak - Terminates Loopexit( ) - Terminates Program

Calculate

n!n ii = 1

xn

1 * 2 * 3 * 4 *….n

1 + 2 + 3 + 4 +.…n

2 * 2 * 2 * 2 *….n

Running sum

Running product

Running product

s = s + ;

Running Sum And Products

}

ip = p * i ;pr = pr * 2 ;

s = 0 ; p = 1 ; pr = 1 ;

1 + 2 + 3 + 4 +.…n RS1 * 2 * 3 * 4 *….n RP2 * 2 * 2 * 2 *….n RP

main( ){

scanf ( ”%d”, &n ) ;int s, p, pr, i, n ;

i = 1 ;while ( i <= n ){

i++ ;

printf ( ”%d %d %d”, s, p, pr ) ;}

i s1 0

123364105156

5

x x3 x5 x7 x9— - — + — - — + — - …………10 terms1! 3! 5! 7! 9!x x3 x5 x7 x9— - — + — - — + — - …………10 terms1! 3! 5! 7! 9!

main( ){

scanf ( ”%f”, &x ) ; while ( i <= 10 ){

calculate numeratorcalculate denominatorterm = numerator / denominatorAdd / subtract alternate terms to/from s

i = 1 ; s = 0 ;

i++ ;}print ( s ) ;

}

main( ){

scanf ( ”%f ”, &x ) ;i = 1 ;while ( i <= 10 ){

i++ ;}printf ( ”%f ”, s ) ;

}

i j1 12 33 54 75 9.. ..

j = 2 * i - 1 ;

while ( k <= j ){

d = d * k ; n = n * x ;k++ ;

}

k = n = d = 1 ;

t = n / d ;( i % 2 == 0 ) ? s = s - t : s = s + t ;

float x, s, n, d, t ; int i, j, k, n ;x1 x3 x5— - — + — -1! 3! 5! x1 x3 x5— - — + — -1! 3! 5!

OK ?

Anything wrong ?

s = 0 ;Associatesfrom R to L

main( ){

printf ( ”Enter any number” ) ;scanf ( ”%d”, &n ) ; ......

}

Prime Number or Not

13

2 3 4 .. .. .. 12

int n ;

13

Prime No.main( ){

int n ; printf ( ”Enter any number” ) ;scanf ( ”%d”, &n ) ;

}

13

2 3 4 .. .. .. 12

while ( )

int i = 2 ;

i <= n - 1{

if ( n % i = = 0 )printf ( ”Not a prime number” ) ;

elsei++ ;

}

main( ){

int n, i = 2 ;printf ( ”Enter any number” ) ;scanf ( ”%d”, &n ) ;while ( i <= n - 1 ){

if ( n % i == 0 )

printf ( ”Not a prime number” ) ;

elsei++ ;

}

}

if ( i == n )

break ;

{

}

printf ( ”Prime number” ) ;

13

Generate Prime Numbers

2 173 195 237 .11 .13 199

main( ){

int i = 5, j = 4, k = -1, a, b ;a = i && !j ;b = ++i && ++j || ++k ;printf ( ”%d %d %d %d %d”, a, b, i, j, k ) ;

}

What Would Be The O/Pb = ( ++i && ++j ) || ++k ;

b = ++i && ( ++j || ++k );

0 1 6 5 -1

i = ++a && ++b && ++c ;j = ++a || ++b || ++c ;

Loop Control Instructions

whilefordo-while

The while Loopmain( ){

int m1, m2, m3, avg, i ;i = 1 ;while ( i <= 10 ){

scanf ( ”%d%d%d”, &m1, &m2, &m3 ) ;avg = ( m1 +m2 + m3 ) / 3 ;printf ( ”%d”, avg ) ;i++ ;

}}

Init Test IncrTestTest

IncrIncr

Test Incr.. .... ..

main( ){

int m1, m2, m3, avg, i ;

scanf ( ”%d%d%d”, &m1, &m2, &m3 ) ;avg = ( m1 + m2 + m3 ) / 3 ;printf ( ”%d”, avg ) ;

}

( )

The for LoopInit Test Incr

TestTest

IncrIncr

Test Incr.. .... ..for i++i = 1 ; i <= 10 ;

{

}

Comparision - I

main( ){

int i = 1 ;while ( i <= 10 )

statement1 ;statement2 ;statement3 ;i++ ;

}

main( ){

int i ;for ( i = 1 ; i <= 10 ; i++ )

statement1 ;statement2 ;statement3 ;

}

Finite LoopInfinite Loop

Comparison II

main( ){

int i = 1 ;while ( i <= 10 ) ;{

statement1 ;statement2 ;statement3 ;i++ ;

}}

main( ){

int i ;for ( i = 1 ; i <= 10 ; i++ ) ;{

statement1 ;statement2 ;statement3 ;

}}

Finite LoopInfinite Loop

Print Nos. From 1 to 10

main( ){

int i ;for ( i = 1 ; i <= 10 ; i++ )

printf ( ”\n%d”, i ) ;}

Dropping Initialisationmain( ){

int i = 1 ;for ( ; i <= 10 ; i++ )

printf ( ”\n%d”, i ) ;}

Dropping Incrementationmain( ){

int i = 1 ;for ( ; i <= 10 ; ){

printf ( ”\n%d”, i ) ;i++ ;

}}

Dropping Conditionmain( ) {

int i = 1 ;for ( ; ; ){

printf ( ”%d”, i ) ;i++ ;

}}

if ( i > 10 )break ;

; ; Necessary

printf ( ”%d”, i++ ) ;

if ( ++i > 10 )

Comparison III

main( ){

int i = 1 ;while ( ){

statement1 ;statement2 ;statement3 ;

}}

main( ){

int i = 1 ;for ( ; ; ){

statement1 ;statement2 ;statement3 ;

}}

Infinite LoopError

Drawing Boxes

012.....24

0 1 2 … … … … 79

Tip : ( 10, 20 )Tip : ( 10, 20 )

(10,20)

(23,70)

( row number, col number )

Box Drawing CharactersCharacter ASCII value

218191192 217 196 179

To Begin With...

main( ){

clrscr( ) ;printf ( ”%c”, 218 ) ;……

}

main( ){

clrscr( ) ;

}

gotorc ( 10, 20 ) ; printf ( ”%c”, 218 ) ;gotorc ( 10, 70 ) ; printf ( ”%c”, 191 ) ;gotorc ( 23, 20 ) ; printf ( ”%c”, 192 ) ;gotorc ( 23, 70 ) ; printf ( ”%c”, 217 ) ;for ( r = 11 ; r < 23 ; r++ ) {

gotorc ( r, 20 ) ; printf ( ”%c”, 179 ) ;gotorc ( r, 70 ) ; printf ( ”%c”, 179 ) ;

}for ( … … … .. ){}

int r, c ;

(10,20)

(23,70)

main( ){

int r, c ;clrscr( ) ;gotorc ( 10, 20 ) ; printf ( ”%c”, 218 ) ;.. .. .. .. for ( r = 11 ; r < 23 ; r++ ){

.. ..}for ( … … … ){}

}

#include ”goto.c”

96 - 9996 - 99

Chapter 3 Chapter 3

1 1 1

1 1 2

1 1 3

1 3 1

1 3 2

1 3 3

1 2 1

1 2 2

1 2 3

3 1 1

3 1 2

3 1 3

3 2 1

3 2 2

3 2 3

3 3 1

3 3 2

3 3 3

2 1 1

2 1 2

2 1 3

2 2 1

2 2 2

2 2 3

2 3 1

2 3 2

2 3 3

Combinations

i = 1 ;j = 1 ;for ( k = 1 ; k <= 3 ; k++ ){

printf ( ”\n%d%d%d”, i, j, k ) ;}

}

1 1 11 1 21 1 3

1 3 1

1 3 2

1 3 3

1 2 1

1 2 2

1 2 3

main( ){

int i, j, k ;

Starting Off...i j k

main( ){

int i, j, k ;i = 1 ;

for ( k = 1 ; k <= 3 ; k++ )printf ( ”\n%d%d%d”,

i, j, k ) ;

}

for ( j = 1 ; j <= 3 ; j++ ){

Adding One More Loop

1 1 11 1 21 1 3

1 3 1

1 3 2

1 3 3

1 2 1

1 2 2

1 2 3

i j k

}

main( ){

int i, j, k;

for ( j = 1 ; j <= 3 ; j ++ ){

for ( k = 1 ; k <= 3 ; k++ )printf ( ”\n%d%d%d”, i, j, k ) ;

}

}

for ( i = 1 ; i <= 3 ; i ++ ) {

1 1 1.. .. .... .. ..1 3 3

2 1 1.. .. .... .. ..2 3 3

3 1 1.. .. .... .. ..3 3 3

}

Finishing Off...

Unique Combinationsmain( ){

int i, j, k ;for ( i = 1 ; i <= 3 ; i++ ){

for ( j = 1 ; j <= 3 ; j++ ){

for ( k = 1 ; k <= 3 ; k++ ){

printf ( ”%d %d %d”, i, j, k ) ;}

}}

}

.. .. ..1 2 3.. .. ..1 3 2

.. .. ..2 1 3.. .. ..2 3 1

.. .. ..3 1 2.. .. ..3 2 1

if ( i != j && j != k && k != i )

if ( i != j != k )printf ( ”%d %d %d”, i, j, k ) ;

if ( i != j != k )printf ( ”%d %d %d”, i, j, k ) ;

One More Waymain( ){

int i, j, k ;for ( i = 1 ; i <= 3 ; i++ ){

for ( j = 1 ; j <= 3 ; j++ ){

for ( k = 1 ; k <= 3 ; k++ ){

printf ( ”%d %d %d”, i, j, k ) ;}

}}

}

i j k

1 1 1

2 1

13

if ( i = = j || j = = k || k = = i )

elsebreak ;

The Correct Waymain( ){

int i, j, k ;for ( i = 1 ; i <= 3 ; i++ ){

for ( j = 1 ; j <= 3 ; j++ ){

for ( k = 1 ; k <= 3 ; k++ ){

if ( i == j || j == k || k == i )continue ;

elseprintf ( ”%d %d %d”, i, j, k ) ;

}}

}}

i j k

1 1 123

123

24

Would ; be OK?

Multiple Initializationsmain( ){

int i, j, k ;i = 1 ; j = 3 ;for ( k = 1 ; k <= 5 ; k++ ) {

……i += 2 ;j *= 4 ;

}}

Better Way

for ( i = 1, j = 3, k = 1 ; k <= 5 ; i += 2, j *= 4 ){

……

}Multiple

Conditions?Can I Drop

k++

Connect using && and ||

Type of Loops

while for

Which is

better do - while

The do-while Loopmain( ) {

int i = 1 ;do{

printf ( ”\n%d”, i ) ;i++ ;

} while ( i <= 10 ) ;}

Tip1: { } - NecessaryTip2: ; after while - Necessary

Compare

do{

printf ( ”Hi” ) ;} while ( 4 < 1 ) ;

for ( ; 4 < 1 ; )printf ( ”Hi” ) ;

while ( 4 < 1 )printf ( ”Hi” ) ;

Hi No Output

No Output

Which To Use When

for - Finite no. of times while - Unknown no. of times do - while - At least once

Recommended, Not compulsory

while ( ){

Unknown No. of Times

}}

char ch = ’y’ ;ch == ’y’

main( ){

/* some logic */printf ( ”Continue Y/N” ) ;scanf ( ”%c”, &ch ) ;

Foolproof?

while ( ch == ’y’ || ch == ’Y’ )while ( toupper ( ch ) == ’Y’ )while ( tolower ( ch ) == ’y’ )

while ( ch == ’y’ || ch == ’Y’ )while ( toupper ( ch ) == ’Y’ )while ( tolower ( ch ) == ’y’ )

Solution

Control Instructiopns

Sequence Decision Repetition

- while, for, do-while break, continue

- ++, --- +=, -=, *=, /=, %=

- while, for, do-while break, continue

- ++, --- +=, -=, *=, /=, %=

Case

main ( ){

int n ;printf ( ”Enter no. between 1 and 3” ) ;scanf ( ”%d”, &n ) ;if ( n = = 1 )

printf ( ”You entered 1” ) ;else{

if ( n = = 2 )printf ( ”You entered 2” ) ;

else{

if ( n = = 3 )printf ( ”You entered 3” ) ;

elseprintf ( ”Wrong choice” ) ;

}}

}

Three Problems

Alternative

Use Logical Operators

Use case Control Instruction

main( ){

int n ; printf ( ”Enter no. below 1 and 3” ) ;scanf ( ”%d”, &n ) ;

{case 1 :

printf ( ”You Entered 1” ) ;case 2 :

printf ( ”You Entered 2” ) ;case 3 :

printf ( ”You Entered 3” ) ;else

printf ( ”Wrong Choice” ) ;}

}

switch ( n )

main( ){

int n ; printf ( ”Enter no. between 1 and 3” ) ;scanf ( ”%d”, &n ) ;

{case 1 :

printf ( ”You entered 1” ) ;case 2 :

printf ( ”You entered 2” ) ;case 3 :

printf ( ”You entered 3” ) ;

}}

switch ( n )

default :printf ( ”Wrong Choice” ) ;

2 Output:You entered 2

Tip: If a case fails control jumpsto the next case

Tip: If a case fails control jumpsto the next case

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

case 1 : printf ( ”You entered 1” ) ;

case 2 :printf ( ”You entered 2” ) ;

case 3 :printf ( ”You entered 3” ) ;

default : printf ( ”Wrong choice” ) ;

}}Tip: If a case is satisfied all statements

below it are executedTip: If a case is satisfied all statements

below it are executed

Output:You entered 2You entered 3Wrong choice2

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

case 1 :printf ( ”You Entered 1” ) ;

case 2 :printf ( ”You Entered 2” ) ;

case 3 :printf ( ”You Entered 3” ) ;

default : printf ( ”Wrong choice” ) ;

}}

The Solution

break ;

break ;

break ;

2

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

case 1 :printf ( ”You Entered 1” ) ; break ;

case 2 :printf ( ”You Entered 2” ) ; continue ;

case 3 :printf ( ”You Entered 3” ) ; break ;

default : printf ( ”Wrong choice” ) ;

}}

Illegal

What If continue

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

case 2 :printf ( ”You Entered 2” ) ; break ;

case 1 : printf ( ”You Entered 1” ) ; break ;

case 3 : printf ( ”You Entered 3” ) ; break;

default : printf ( ”Wrong choice” ) ;

}}

Tip: Order of cases is unimportantTip: Order of cases is unimportant

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

default : printf ( ”Wrong choice” ) ;

case 2 :printf ( ”You Entered 2” ) ; break ;

case 1 : printf ( ”You Entered 1” ) ; break ;

case 3 : printf ( ”You Entered 3” ) ; break ;

}}

Tip: Even default can be the very first caseTip: Even default can be the very first case

break ;

main ( ) {

int n ;scanf ( ”%d”, &n ) ;switch ( n ) {

case 2 :printf ( ”You Entered 2” ) ; break ;

case 1 : printf ( ”You Entered 1” ) ; break ;

case 3 : printf ( ”You Entered 1” ) ;

}}

Tip: default case is optionalTip: default case is optional

main( ){

char ch ;printf ( ”Enter alphabet between A and C” ) ;scanf ( ”%c”, &ch ) ;switch ( ch ){

case ’A’:printf ( ”You entered A” ) ;break ;

case ’B’:printf ( ”You entered B” ) ;break ;

case ’C’:printf ( ”You entered C” ) ;break ;

}}

main( ){

char ch ;printf ( ”Enter alphabet between A and C” ) ;scanf ( ”%c”, &ch ) ;switch ( ch ){

case ’A’ || ’a’ :printf ( ”You entered A” ) ;break ;

case ’B’ || ’b’ :printf ( ”You entered B” ) ;break ;

case ’C’ || ’c’ :printf ( ”You entered C” ) ;break ;

}}

Becomecase 1 :

main( ){

char ch ;printf ( ”Enter alphabet between A and C” ) ;scanf ( ”%c”, &ch ) ;switch ( ch ){

case ’A’:printf ( ”You entered A” ) ;break ;

case ’B’:printf ( ”You entered B” ) ;break ;

case ’C’:printf ( ”You entered C” ) ; break ;

}}

Acase ’a’ :

case ’b’ :

case ’c’ :

a

main( ){

int n = 2 ;int a = 1, b = 2 ;switch ( n ){

case a :…

case b :…

case 3 :…

}}

Would This Work

General Form

main( ){

switch ( expression ){

case constant expression :…

case constant expression :…

case constant expression :…

default: …

}}

3 + 2 % 5

n + 3 / a + 2 4 + 3 / 5 + 2

Checking switch

int char long int float

?

Tip: float cannot be checked using switchTip: float cannot be checked using switch

Is switch a replacementfor if ?

99 [D] - 10299 [D] - 102

Chapter 3 Chapter 3

Menu Management

1. Odd / Even2. Leap Year3. Prime No.0. ExitYour Choice?

20

10

main( ){

clrscr( ) ;gotorc ( 10, 20 ) ; printf ( ”1. Odd / Even” ) ;gotorc ( 11, 20 ) ; printf ( ”2. Leap year” ) ;gotorc ( 12, 20 ) ; printf ( ”3. Prime number” ) ;gotorc ( 13, 20 ) ; printf ( ”0. Exit” ) ;gotorc ( 15, 20 ) ; printf ( ”Your choice?” ) ;scanf ( ”%d”, &choice ) ;.. ..

}

int choice ;

# include ”goto.c”

main( ){

int choice ;/* display menu */scanf ( ”%d”, &choice ) ;switch ( choice ){

case 1 : /* odd / even logic */break ;

case 2 :/* leap year logic*/break ;

case 3 :/*prime number logic*/break ;

default :printf ( ”\a” ) ;

}}

case 0 :break ;

\n \t \a

EscapeSequences

printf ( ”\a\a\a” ) ;

LongBeep

switch ( choice ){

case 1 :break ;

case 2 :break ;

case 3 :break ;

case 0 :break ;

default :printf ( ”\a” ) ;

}

Block CommandsOdd / evenlogic

Leap yearlogic

Prime no.logic

CH2PR3.C

CH2PR4.C

CH2PR5.C

Ctrl KBCtrl KK

Other Block Commands

Ctrl KV Move blockCtrl KC Copy blockCtrl KW Write block to fileCtrl KY Delete blockCtrl KH Hide or unmark block

Mark block

Readjustments Necessary case 1:

main( ){

……

}break ;

Shift declarations

DeleteDelete

Only Shifting Won’t Do

No while, No Menu

while ( 1 ){

/*display menu*/scanf ( ”%d”, &choice ) ;switch( choice ){

case 1 :…break ;

case 0 :break ;

}

}

#include ”goto.c”main( ){

int choice ;

} exit( ) ;

Requirements of A Menu

Infinite loop switch

Surprised?main( ){

float a = 0.7 ;if ( a < 0.7 )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

A

Appearances Are Misleading

main( ){

float a = 0.7 ;printf ( ”%d%d”, sizeof ( a ), sizeof ( 0.7 ) );

}

365 0.7

Integer Double

4 8

Binary of A Floatfloat a = 5.375 ;

Binary of 5 Binary of .375

101 .011Binary of 5.375

101.011

Normalised form

1.01011 * 22

.375 * 2 = 0.750 0

.750 * 2 = 1.500 1

.500 * 2 = 1.000 1

1000 00010 01011000000000000000000

The Actual Storage

Mantissa

Positive2 + 127

. 01011

8 23132

SignBit Biased

Exponent

Difference In double

Mantissa

Bias valueis 1023

11 52164

SignBit

BiasedExponent

.4 * 2 = 0.8 0

.8 * 2 = 1.6 1

.6 * 2 = 1.2 1

.2 * 2 = 0.4 0

Binary of 0.7.7 * 2 = 1.4 1.4 * 2 = 0.8 0.8 * 2 = 1.6 1.6 * 2 = 1.2 1.2 * 2 = 0.4 0

.4 * 2 = 0.8 0

. . . . . .

. . . . . .

32 - bitRecurring binary

equivalent of0.7

64 - bitRecurring binary

equivalent of0.7

<

float a = 0.7 ;if ( a < 0.7 )

printf ( ”A” ) ;else

printf ( ”B” ) ;

A

Overriding Defaults365 365L

0.7 0.7f

if ( a < 0.7f )printf ( ”A” ) ;

elseprintf ( ”B” ) ;

B

Exact Binarymain( ){

float a = 5.375 ;if ( a < 5.375 )

printf ( ”A” ) ;else

printf ( ”B” ) ;}

B

Functionsmain( ){

printf ( ”\n I am in main” ) ;}

bombay( ){

printf ( ”\n I am in Bombay” ) ;}

kanpur( ){

printf ( ”\n I am in Kanpur” ) ;}

Output:I am in main

Functionsmain( )printf( )scanf( )getch( )exit( )gotorc( )clrscr( )for( )while( )if( )switch( )

Categories

printf( )scanf( )exit( )clrscr( )

kanpur( )bombay( )gotorc( )main( )

Std. Library User-Defined

Functions

Calling Functionsmain( ){

printf ( ”\n I am in main” ) ;

bombay( ){

printf ( ”\n I am in Bombay” ) ;}kanpur( ){

printf ( ”\n I am in Kanpur” ) ;}

Output :I am in mainI am in BombayI am in Kanpurbombay( ) ; kanpur( ) ;

}

Function Call

Function Def.

Tips A C program is nothing but a collection

of 1 or more functions

If C program contains 1 function its name must be main( )

If C program contains more than 1 functionthen one of them has to be main( )

Execution of any C program always beginswith main( )

Function names in a program must be unique

Order, Order !bombay( ){

printf ( ”\n I am in Bombay” ) ;}main( ){

printf ( ”I am in main” ) ;bombay( ) ;

}

Tip: Functions can be defined in any orderTip: Functions can be defined in any order

More Calls, More Billsmain( ){

printf ( ”\n I am in main” ) ;bombay( ) ;bombay( ) ;

}bombay( ){

printf ( ”\n I am in Bombay” ) ;}

Tip: More the calls, slower the executionTip: More the calls, slower the execution

Nobody is Nobody’s Boss

kanpur( ){

printf ( ”\n I am in Kanpur” ) ; bombay( ) ;

}

main( ){

printf ( ”\n I am in main” ) ;bombay( ) ; kanpur( ) ;

}bombay( ){

printf ( ”\n I am in Bombay” ) ;kanpur( ) ;

} Tip: Any function can callany other function

Tip: Any function can callany other function

Local v/s STD v/s ISD Callsmain( ){

printf ( ”\n I am in main” ) ;main( ) ;

}

Local Call - Recursive FunctionProcess - Recursion

115 - 120115 - 120

Chapter 4 Chapter 4

main( ){

for ( i = 1 ; i <= 22 ; i+= 2 ) {

for ( j = 5 ; j <= 50 ; j++ ){

for ( k = 1 ; k <= 9 ; k += 3 ){

… … if ( i + j % k >= 2 )

break ; }

}

}}

Break From The Outermost Loop

break ;

break ; if ( i + j % k >= 2 )

break ;

Go to workonly once

main( ){

for ( i = 1 ; i <= 22 ; i+= 2 ) {

for ( j = 5 ; j <= 50 ; j++ ){

for ( k = 1 ; k <= 9 ; k += 3 ){

… … if ( i + j % k >= 2 )

goto out ; }

}}

}

Better Way...

out :;

Never usea goto

main( ){

for ( i = 1 ; i <= 22 ; i+= 2 ) {

for ( j = 5 ; j <= 50 ; j++ ){

for ( k = 1 ; k <= 9 ; k += 3 ){

… … if ( i + j % k >= 2 )

goto out ; }}

}

}

Where Am I...

out :goto in ;

goto there ;in :

there :

Control Instructions

Sequence Decision Repitition Case goto

Communicationmain( ){

int a = 10, b = 20, c = 30 ;calsum ( ) ;printf ( ”%d”, s ) ;

}calsum( ){

int a, b, c, s ;

}

int s ;

printf ( ”%d”, s ) ;s = a + b + c ;

Garbage

Garbage

main( ){

int a = 10, b = 20, c = 30 ; int s ; calsum ( ) ;printf ( ”%d”, s ) ;

}calsum ( ){

int s ;

}printf ( ”%d”, s ) ;s = x + y + z ;

a, b, c

int x, int y, int z

Passing Values

60

Garbage

Formal Arguments

ActualArguments

main( ){

int a = 10, b = 20, c = 30, s ; calsum ( a, b, c ) ;

}calsum ( int x, int y, int z ){

int ss ;ss = x + y + z ;return ( ss ) ;

}

s = calsum ( a, b, c ) ;printf ( ”%d”, s ) ;

Returning Values

60

return ( ss ) ;

return ( 60 ) ;

return ( x + y + z ) ;

Return control and value

return ; Returns onlycontrol

calsum ( a, 25, d ) ;calsum ( 10 + 2, 25 % 3, d ) ;calsum ( a, calsum ( 25, 10, 4 ), d ) ;d = calsum ( a, 25, d ) * calsum ( a, 25, d ) + 23 ;

Are These Calls OK?

calsum ( int x, int y, int z ){

int ss ;ss = x + y + z ;return ( ss ) ;

}

Nested calls are legal.Call within an expression are legal.

main( ){

int a = 10, b = 20, c = 30 ;

printf ( ”%d%d”, s, p ) ;}sumprod ( )int x, int y, int z

ss = x + y + z ;pp = x * y * z ;

sumprod ( a, b, c ) ; s, p = sumprod ( a, b, c ) ;

{int ss, pp ;

return ( ss, pp ) ;}

Returning More Than 1 Value

int s, p ;

A function can return only 1 value at a time

main( ){

int a = 10, b = 20, c = 30 ;int s, p ; s = sumprod ( a, b, c ) ;p = sumprod ( a, b, c ) ;printf ( ”%d%d”, s, p ) ;

}sumprod ( int x, int y, int z ){

ss = x + y + z ;pp = x * y * z ;return ( ss ) ;return ( pp ) ;

}

int ss, pp ;

One More Try

60 60

Redundant

main( ){

int a = 10, b = 20, c = 30 ; int s, p ; s = sumprod ( a, b, c ) ;p = sumprod ( a, b, c ) ;printf ( ”%d%d”, s, p ) ;

}

, 1, 2

sumprod ( int x, int y, int z, ){

ss = x + y + z ; pp = x * y * z ;int ss, pp ;

}

int code

if ( code == 1 ) return ( ss ) ;

elsereturn ( pp ) ;

The Only Way Out

Sum, Product,Average, VarianceStandard Deviation

A Better Waysumprod ( int x, int y, int z, int code ){

ss = x + y + z ;pp = x * y * z ;

int ss, pp ;

}

if ( code == 1 ) return ( ss ) ;

elsereturn ( pp ) ;

code == 1 ? return ( x + y + z ) : return ( x * y * z ) ;

return ( code == 1 ? x + y + z : x * y * z ) ;

ANSI V/s K & Rcalsum ( int x, int y, int z ){

..}

calsum ( x, y, z )int x, y, z ;{

..}

Kernighan &Ritchie

ANSI

main( ){

printf ( ”Enter year” ) ;scanf ( ”%d”, &y ) ;

int y ;

romanize ( y ) ;}romanize ( int yy ){

int n, i ;n = yy / 1000 ;for ( i = 1 ; i <= n ; i ++ )

printf ( ”m” ) ;

Decimal Roman1000 m500 d100 c50 l10 x5 v1 i

}

Roman Equivalent

1998 m d c c c c l x x x x i i i

1998

v

romanize ( y ) ;

main( ){

printf ( ”Enter year” ) ;scanf ( ”%d”, &y ) ;

int y ;

}romanize ( int yy ) {

int n, i ;n = yy / j ;for ( i = 1 ; i <= n ; i ++ )

printf ( ) ;

}

”%c”, ch

, int j , char ch

return ( yy % j ) ;

, 1000 , ’m’

A More General Call

y = romanise ( y, 1000, ’m’ ) ;

main( ){

..., ’m’

}romanize ( int yy ) {

}

, int j , char ch

y = romanise ( y, 500, ’d’ ) ;y = romanise ( y, 100, ’c’ ) ;y = romanise ( y, 50, ’l’ ) ;y = romanise ( y, 10, ’x’ ) ;y = romanise ( y, 5, ’v’ ) ;romanise ( y, 1, ’i’ ) ;

int n, i ;n = yy / j ;for ( i = 1 ; i <= n ; i ++ )

printf ( ”%c”, ch ) ;return ( yy % j ) ;

y = romanise ( y, 1000 ) ;

1998 m d c c c c l x x x x i i i v

Works

Advanced Features of Functions

Returning a non-integer value Call by value / Call by reference Recursion

square ( 2.0 ) ;

Returning a Non-Integer Valuemain( ){

a = square ( 2.0 ) ;b = square ( 2.5 ) ;c = square ( 1.5 ) ;printf ( ” %f %f %f ”, a, b, c, ) ;

}square ( )float x{

float y ;y = x * x ;printf ( ” %f ”, y ) ;return ( y ) ;

}

FunctionPrototype

4.0 6.0 2.0

float a, b, c ; float square ( float ) ;

4.0

6.25

2.25

float square ( float x )

156 - 161 (e)156 - 161 (e)

main( ){

What’s Wrong?

float square ( float ) ;float a = 0.5 ; f ( a ) ;

}f ( float x ){

float y ;y = square ( x ) ;printf ( ”%f”, y ) ;

}float square ( float x ){

return ( x * x ) ;}

main( ){

What Would Be The Output

int a = 10 ;printf ( ”\n a = %d” , a ) ; a = f( ) ; printf ( ”\n a = %d” , a ) ;

}

a = 10

f( ){

printf ( ”Hello !” ) ; }

a = 45

main( ){

Solution 1

int a = 10 ;printf ( ”\n a = %d” , a ) ; f( ) ; printf ( ”\n a = %d” , a ) ;

}

a = 10

f( ){

printf ( ”Hello !” ) ; }

a = 10

Returned value is ignored.

main( ){

Solution 2

int a = 10 ;printf ( ”\n a = %d” , a ) ; f( ) ; printf ( ”\n a = %d” , a ) ;

}

a = 10

void f( ){

printf ( ”Hello !” ) ; }

a = 10

void prevents returning of value.

void f( ) ;

Advanced Features of functions

Returning a non-integer value Call by Value / Call by Reference Recursion

Pointers

*

*

The Biggest Hurdle !!

Why Learn Pointers?

Simple Powerful Earn respect and money

*( )

AddressReferenceMemory locationCell number

main( ){

Things Are Simple

int i = 10 ;printf ( ”\n value of i = ” , ) ; printf ( ” \n address of i = ” , ) ;

%d

printf ( ” \n value of i = ” , ) ;

i

%d &i&i

}

POINTER OPERATORS

& - ‘Address Of’ Operator* - ‘Value at Address’ Operator- ‘Indirection’ Operator

10 4080

i4080%d 10

1 2 30

Memory

10

Would This Work...int i = 10 ;j = &i ;j = &23 ;j = & ( i + 34 ) ;

printf ( “ %d ” *j ) ; printf ( “ %d ”, *4568 ) ;printf ( “ %d ”, * ( 4568 + 1 ) ) ;

& can be usedonly with a variable

* can be used with variable, constant

or expression

Some ChangeNecessary

printf ( ” \n value of j = ” , ) ;

The Next Step

printf ( ” \n value of i = %d ” , i ) ;printf ( ” \n address of i = %d ” , &i ) ;printf ( ” \n value of i = %d ” , *( &i ) ) ;

int j ; int k ;

j = &i ;printf ( ” \n address of j = ” , ) ;%d &jprintf ( ” \n value of j = ” , ) ;%d

%dj*&j

k = &j ;printf ( ” \n %d %d %d %d ” , k , &k , *k , *&k ) ;

printf ( ” \n %d %d %d %d %d %d ”, ) ;

}

i j k

4080 6010 51126010408010

*&i,i, *j, **&j,**k, ***&k

main( ){

int i = 10 ;

6010

4080

4080

6010 5112 4080 6010

* **

10 10 10 10 10 10

Kneel Down , Bow Your Head , Close Your Eyes ...

In Essence ...

&

*- Address of operator- value of address operator

PointerOperators

variable *& variable

Pointers are variables which holdaddresses of other variables

int i = 10 ; **k , m = &l ;

???***l , ****m ;int *j ,

j = &i ; k = &j ; l = &k ;

Integer Pointer

int &k ;k = && j ;

*s = *s - 32 ;

if ( >= ’A’ && *s <= ’Z’ )

*(s+i) = *s - 32 ;

Accessing Screenmain( ){

while ( 1 ){

}

s = 1000 ;for ( i = 0 ; i <= 1999 ; i++ ){

}

*s*s = *s + 32 ;

else{

if ( *s >= ’a’ && *s <= ’z’ )

}

}

0xB8000000

int i ; char *s ;char far *s ;

*(s+i) = *s + 32 ;if ( >= ’A’ && *s <= ’Z’ ) *(s+i)

if ( *(s+i) >= ’a’ && *s <= ’z’ )*(s+i) = *(s+i) - 32 ;

*(s+i) = *(s+i) + 32 ;

if ( *(s+i) >= ’a’ && *(s+i) <= ’z’ )

if ( >= ’A’ && *(s+i) <= ’Z’ ) *(s+i)

Screen

M1000 1000

+11000+2

1000+3

1000 + 1999

char ch ;ch = ’A’ ;ch = ch + 32 ;

Accessing Screenmain( ){

M

0xB8000000

+ 2 + 4 + 6

+ 3998

while ( 1 ){

}

s = 0xB8000000 ;for ( i = 0 ; i <= 1999 ; i++ ){

}

if ( >= ’A’ && *(s+i) <= ’Z’ ) *(s+i)*(s+i) = *(s+i) + 32 ;

else{

if ( *(s+i) >= ’a’ && *(s+i) <= ’z’ )*(s+i) = *(s+i) - 32 ;

}

}

i += 2 int i ; char far *s ;3999

main( ){

char far *s ; int r ;char far * v ;s = 0xB8000000 ;

for ( r = 1 ; r <= 24 ; r ++ ) {

v = s + r * 160 ;* v = ch ;

}}

Screen

ch = * s ;

0xB80000000xB8000000

+160+320+480+640

M+2 +4 +6

+3998

To Make Characters Fall

char ch ;

for ( c = 0 ; c <= 79 ; c++ )

}

main( ){

char far *s ; int r ;char far *v ;s = 0xB8000000 ;

}

ch = * s

int c ;

Screen0xB80000000xB8000000

+160+320+480+640

M+2 +4 +6

+3998

{+ c * 2 ) ;

for ( r = 1 ; r <= 24 ; r++ ) {

v = s + r * 160* v = ch ;

}

(

+ c * 2 ;

Make All Characters Fall

char ch ;

Any Screen Address

A

Column 20

Row 10

0xB8000000

v = 0xB8000000 + 10 * 160 + 20 * 2 ;In general,

v =0xB8000000 + r * 160 + c * 2 ;*v = ch ;

{

main ( ){

char far *s ; char ch ;int r, c ;char far *v ;

s = 0xB8000000 ;

for ( r = 1 ; r <= 24 ; r ++ ) {

v = s + r * 160

ch = *s ;

+ c * 2 ;*v = ch ;

for ( c = 0 ; c <= 79 ; c++ )

}}

}

delay ( ) ;* ( v - 160 ) = ’ ’ ;sound ( 350 ) ; delay ( 100 ) ;nosound ( ) ;

60

Screen0xB80000000xB8000000

+160+320+480+640

M+2 +4 +6

+3998

Bells And Whistles

ch = * ( s + c * 2 ) ;

r = random ( ) ;24c = random ( 79 ) ;

Use randomize( )# include ”time.h”

What if 10 - 20?

Millisec

char far *v ;

char far *s, far *v ;

char far *s, *v ;

char far *s ;

Are They Same

char far *s ;s = 0xB8000000 ;

char far *s = 0xB8000000 ;

Why Two Bytes Apartmain( ){

char far *s ; int i ;int color = 0 ;s = 0xB8000000 ; while ( 1 ) {

}}

for ( i = 1 ; i <= 3999 ; i += 2 ) * ( s + i ) = color ;

color++ ;if ( color > 255 )

color = 0 ;

Screen

ASCII Color

VDU Memory

Color Byte

8 Bits

Min value 00000000

Max value11111111

Range 0 to 255

M+2 +4 +6

0xB8000000

Is The Caps Lock On

char far *kb ;

main( ) {

kb = 0x417 ;*kb = 64 ;

}

How would you put off the caps lock?

Toggle Keys

Caps lockNum lockScroll lockInsert

01000000

0x417

0

Caps Lock1 - On0 - Off

Caps Lock1 - On0 - Off

1234567

00001100

Don’t Do Deletemain( ){

char far *kb ;kb = 0x417 ;

printf ( ”Please press delete key” ) ;

*kb = 12 ;getch( ) ;

}

Alt Ctrl

01234567

scanf( )getch( )

Input Fun.

Happy Birthday Joshi01234567

0 0

Our Program

Happy Birthday Joshi

Del Ctrl + Alt + Del

Del Ctrl + Alt + Del

What would be the outputmain( ){

int i = 10 ; float a = 3.14 ; char ch = ’z’ ;

j = &i ; b = &a ; dh = &ch ; k = &j ; c = &b ; eh = &dh ; printf ( ” ” , j , b , dh ) ;

printf ( ” ” , *k ,*c , *eh ) ;

printf ( ” ” , sizeof ( i ), sizeof ( a ), sizeof ( ch ) ) ;

%d %d %d

%d %d %d

%d %d %d

10i

3.14 z1000 2000 3000

a ch

1000 2000 3000j b dh

4000 5000 6000

4000 5000 6000500 1500 2500

k c eh

1000 2000 3000

2 4 1

Continued...Continued...

1000 2000 3000

int *j, **k ; float *b, **c ; char *dh, **eh ;

printf ( ” %d %d %d ”, sizeof ( j ), sizeof ( b ), sizeof ( dh ) ) ;

printf ( ”%d %d %d”, sizeof ( k ), sizeof ( c ), sizeof ( eh ) ) ;

printf ( ” %d %f %c ” , **k, **c, **eh ) ;

}

10i

3.14 z1000 2000 3000

a ch

1000 2000 3000j b dh

4000 5000 6000

4000 5000 6000500 1500 2500

k c eh

10 3.14 z

2 2 2

2 2 2

...Continued...Continued

What would be the outputmain( ){

int i = 10 ; float a = 3.14 ; char ch = ’z’ ;

j = &i ; b = &a ; dh = &ch ; k = &j ; c = &b ; eh = &dh ; printf ( ” ” , j , b , dh ) ;

printf ( ” ” , *k ,*c , *eh ) ;

printf ( ” ” , sizeof ( i ), sizeof ( a ), sizeof ( ch ) ) ;

%d %d %d

%d %d %d

%d %d %d

10i

3.14 z1000 2000 3000

a ch

1000 2000 3000j b dh

4000 5000 6000

4000 5000 6000500 1500 2500

k c eh

1000 2000 3000

2 4 1

Continued...Continued...

1000 2000 3000

int *j, **k ; float *b, **c ; char *dh, **eh ;

printf ( ”%d %d %d ”, sizeof ( j ), sizeof ( b ), sizeof ( dh ) ) ;

printf ( ”%d %d %d”, sizeof ( k ), sizeof ( c ), sizeof ( eh ) ) ;

printf ( ”%d %f %c” , **k, **c, **eh ) ;

}

10i

3.14 z1000 2000 3000

a ch

1000 2000 3000j b dh

4000 5000 6000

4000 5000 6000500 1500 2500

k c eh

10 3.14 z

2 2 2

2 2 2

...Continued...Continued

Truly Speaking

int *j ;float *b ;

b = &a ;

main( ){

int i = 25 ; float a = 3.14 ;j = &i ;

}printf ( ”%d%f”, *j, *b ) ;

401 402

i

501 502 503 504

a

j

Binary of 3.14 501b

Binary of 25 401

Accessing Individual Bytesmain( ){

float a = 3.14 ;

b = &a ; c = &a ; d = &a ; printf ( ” ”, *b, *c, *d ) ;printf ( ”%d %d %d %d”, *d, *(d+1), *(d+2), *(d+3) ) ;

float *b ; int *c ; char *d ;

printf ( ”%d %d”, *( c+1 ), *( c+2 ) ) ;}

%f %d %d

501

501

503 504

a0’s & 1’s

0’s & 1’s

0’s & 1’s

0’s & 1’s

501

502

501b c d

main( ){

float a = 3.14 ;int i = 25 ; int *j ;

float *b ;char far *kb ;kb = 0x417 ;j = &i ;b = &a ;

}

Why far and near

25 3.14 200 300200 300

0x417i a j b kb

Code Segment

Turbo C

DOS/Windows

BDA 0x417IVT

M A

0xB8000000

Screen

MABCDEF

384 KBHigh Memory

640 KBBase orConventionalMemory

Data

Segment

0xB8000000

Free Memory

(640 + 64 ) * 1024

HEX64 * 6

main( ){

float a = 3.14 ;int i = 25 ; int *j ;

float *b ;char far *kb ;kb = 0x417 ;j = &i ;b = &a ;

}

printf ( ”%d %d %d”, sizeof ( j ), sizeof ( b ),sizeof ( kb ) ) ;

Pointer Sizes

4

2 2

How Much Memorymain( ){

int far *m ;m = 0x413 ;printf ( ”%d” ,*m ) ;

} 0x413 0x414

640

640 KB

BDAIdeally

632634636

?

main( ){

int a = 10, b = 20 ;printf ( ”%d%d”, a, b ) ;swapv ( ) ;a, bprintf ( ”%d%d”, a, b ) ;

}swapv ( int x, int y ){

}

int t ;t = x ; x = y ; y = t ;printf ( ”%d%d”, x, y ) ;

10 20

10 20

x y t

x y t

x y t

x y t

10 20 g

10 1020

20 1020

20 10 10

20 10

10 20a b

swapr ( ) ;&a, &bprintf ( ”%d%d”, a, b ) ;

swapr ( ){

}

int t ;t = *x ;*x = *y ;*y = t ;

10 20

20 10

x y t

20a b

300

main( ){

int a = 10, b = 20 ;printf ( ”%d%d”, a, b ) ;

int *x , int *y 200} 10

200 300 10

1020

main( ){

int a = 10, b = 20, c = 30sumprod ( a, b, c, ) ;printf ( ”%d%d”, s, p ) ;

}

, s, p ;

sumprod ( int x, int y, int z, ){

}

x + y + z ; x * y * z ;

&s, &p

int *ss, int*pp

ss =pp =

**

a b c s p

100 200x y z ss pp

10 20 30

10 20 30 100 200

G G600060

60 6000

Advanced Features of Functions

• Returning Non-integer Value• Call By Value / Reference• Recursion

To Be A Successful Software Developer

Creative Intelligence

Analytical Ability

Patience

Ability To Think

Simpler Form

main( ){

printf ( ”Hi” ) ;main( ) ;

}

One More Form

main( ){

f( ) ;}f( ){

printf ( ”Hi” ) ;f( ) ;

}

More Generalmain( ){

int num, sum ;printf ( ”Enter a number” ) ;scanf ( ”%d”, &num ) ;

}sumdig ( int n ){

int d ; int s = 0 ; while ( ){

n != 0

d = n % 10 ;n = n / 10 ; s = s + d ;

}return ( s ) ;

}

31698d5

372d3

2846d4

n s d327 0 732 7 23 9 30 12

327

sum = sumdig ( num ) ;printf ( ”%d”, sum ) ;

main( ){

printf ( ”Enter a number” ) ;scanf ( ”%d”, &num ) ;

}

int num, sum ;

rsum ( int n ){

int d ; int s ; if ( ){

n != 0

d = n % 10 ;s = d + rsum ( n ) ;

n = n / 10 ;

}else

return ( 0 ) ; return ( s ) ;}

327sum = rsum ( num ) ;printf ( ”%d”, sum ) ;

{if ( ){

n != 0d =

s =n =

}else

return ( 0 ) ; return ( s ) ;

}

rsum ( int n )

rsum ( int n ){

if ( ){

n != 0d =

s =n =

}else

return ( 0 ) ; return ( s ) ;

}

rsum ( int n ){

if ( ){

n != 0d =

s =n =

}else

return ( 0 ) ; return ( s ) ;

}

327 % 10 ;327 / 10 ;7 + rsum ( 32 ) ;

rsum ( int n ){

if ( ){

n != 0d =

s =n =

}else

return ( 0 ) ; return ( s ) ;

}

32 % 10 ;32 / 10 ;2 + rsum ( 3 ) ;

3 % 10 ;3 / 10 ;3 + rsum ( 0 ) ;

327

Factorial Valuemain( ){

printf ( ”Enter a number” ) ;scanf ( ”%d”, &num ) ;

}

int num, fact ;

fact = factorial ( num ) ;printf ( ”%d”, fact ) ;

factorial ( int n ){

int p = 1 ; while ( ){

}

n != 0

p = p * n ;n-- ;

return ( p ) ;}

Recursive Factorial main( ){

printf ( ”Enter a number” ) ;scanf ( ”%d”, &num ) ;

}

int num, fact ;

fact = refact ( num ) ;printf ( ”%d”, fact ) ;

refact ( int n ){

int p ; if ( )n != 0

p = n * refact ( n - 1 ) ;

return ( p ) ;}

elsereturn ( 1 ) ;

Advantages of Recursion

Ease ?

Speed ?

Peg A Peg B Peg C A B CA to C

A B C

A B C

A to B

B to AC to B A to C

B to C A to C

3 ! + 1

A B C A B C

A B C A B C

Chapter 5 Chapter 5

Chapter 5 Chapter 5

Data Types in C

i

Type of Integersint

short int long int

Specifier: %u

signed short unsigned short

Specifier: %i %d %o %x %X

15 bits = value

max value

111 1111 1111 1111

32767

int i ;short int i ;

signed short int i ;

Sign bit0 - Positive1 - Negative

default

Range:-32768 to +32767

Size: 2 Bytes

Range: 0 to 65535

Size: 2 Bytes

Type of Integers

short int long int

signed unsigned

Specifier: %ld

long signed long unsigned

Specifier: %lu

long int a

31 bits = value

max value

111 1111 1111 1111 1111 1111 1111 11112147483647

Range: -2147483648 to+2147483647

Size: 4 Bytes

Range: 0 to 4294967295

Size: 4 Bytes

Sign bit0 - Positive1 - Negativeint

Type of Chars

char

signed char unsigned char

Specifier: %c Specifier: %c

7 bits = valueSign bit0 - Positive1 - Negative

max value

111 1111

127

char ch ;

Range : -128 to + 127Size : 1 Byte

Range: 0 to 255 Size: 1 Byte

Types of RealReal

float double long double

Range: -3.4*1038 to +3.4*1038

Size: 4 bytesSpecifier: %f

Range: -1.7*10308

to +1.7*10308

Size: 8 bytesSpecifier: %lf

Range: -1.7*104932

to +1.7*104932

Size: 10 bytes

Specifier: %Lf

1 - 8 - 23 1 - 11 - 52 1 - 15 - 64

127 1023 16383

int

short int long int

signed unsigned signed unsigned

char Real

long doubleunsignedsigned doublefloat

Chars With a Sign?

char ch = ’A’ ;ch

65

char dh = -15 ; dh

-15

What If We Exceed The Range?

signed char ch = 128 ;

printf ( ”%d”, ch ) ;Why?

-128

Why This Bias?

-128 +127

int

-32768 +32767

-2147483648 +2147483647

long int

char

signed char ch = -128 ;

Binary of 128

10000000

1’s complement

01111111

2’s complement

10000000printf ( ”%d”, ch ) ;

-128

unsigned char dh = 128 ;

signed char eh= 128 ;

Binary of 128

10000000printf ( ”%u”, dh ) ;

Binary of 128

10000000

Add 0 for PositiveSign bit

010000000

Store rightmost8 bits

10000000

printf ( ”%d”, eh ) ;

011111111+

10000000

-128

128

Various Formssigned short int i ;short signed int i ;short int i ;signed int i ;int i ;short i ;signed i ;unsigned short int j ;short unsigned int j ;unsigned int j ;unsigned j ;

long signed int k ;signed long int k ;long int k ;long k ;

long unsigned int i ;unsigned long int i ;unsigned long i ;

signed char ch ;char signed ch ;char ch ;

unsigned char dh ;

float a ;

long double e ;

char unsigned dh ;

double d ;

What Is 365?int 365

double 3.14

What Is 3.14?

long int unsigned int unsigned long int

365L 365l

365u365lu 365ul

floatlong double

3.14f3.14L

Would This Workmain( ){

for ( i = 0 ; i <= 255 ; i++ )printf ( ”%d %c”, i, i ) ;

}

char i ; unsigned char i ;

int i ;

Stick To Your Gunsmain( ){

for ( i = 0 ; ; i++ )printf ( ”%d %c”, i, i ) ;

}

unsigned char i ;

printf ( ”%d %c”, i, i ) ;

i < 255

Storage Classes In C

A Complete definition of variable :TypeStorage Class

A Storage Class signifies

StorageDefault Initial ValueScopeLife

Types of Storage Classes

AutomaticRegisterStaticExternal

Automatic Storage ClassStorage

Default Initial Value

Scope

Life

Memory

Garbage

Local to the block in whichthe variable is defined

Till the control is in theblock in which the variable is defined

Automatic Storage Class

main( ){

int a ;static int b ;automatic int c ;printf ( ”%d %d %d”, a, b, c ) ;

automaticauto

}

Error

?

Default Initial Value

main( ){

int a ;static int b ;auto int c ;printf ( ”%d%d%d”, a, b, c ) ;

}G 0 G

Which Is Correct?main( ){

int a = 10 ;float a = 3.14 ;. . . . . . .. . . . . . .

}

main( ){

int a = 10 ;int a = 20 ;. . . . . . .. . . . . . .

}

Tip: Redefinition not allowedTip: Redefinition not allowed

Redefinition?main( ){

int a = 10 ;{

int a = 20 ;{

int a = 30 ;printf ( ”%d”, a ) ;

}printf ( ”%d”, a ) ;

}printf ( ”%d”, a ) ;

}

Error ! Why?

main ( ){

int a = 20 ;f ( ) ;

}f ( ){

printf ( ”%d”, a ) ;}

30

20

10

Death, But When?main( ){

int i =10, j = 20, k, l ;k = f ( ) ;l = i + j + k ;printf ( ”%d”, l ) ;

}f ( ){

int m = 5, n ;n = m * 2 ;return ( n ) ;

}

Would die when control goes back

Won’t die when the control goes to f( )

Register Storage Class

Storage :

Default Initial value :

Scope : Life :

CPU Registers 14 Each of 2 bytes

Central Processing Unit

Microprocessor µp

Different Speeds?main( ){

for ( i = 1 ; i <= 250 ; i++ )printf ( ”%d %c”, i, i ) ;

}

main( ){

for ( i = 1 ; i <= 250 ; i++ )printf ( ”%d %c”, i, i ) ;

}

auto int i ; register int i ;

Storage : CPU Registers

Register Storage Class

Default Initial Value : GarbageScope : Local to the block in which the variable is defined

Life : Till the control remains in the block in whichthe variable is defined

Be Judiciousmain( ){

for ( i = 1 ; i <= 250 ; i++ )printf ( ”%d %c”, i, i ) ;

register int i ; register int j = 20 ;

printf ( ”%d”, j ) ;}

Static Storage Class

Storage

Default Initial Value

Scope

Life

Memory

0

Local to the block in whichthe variable is defined

Variable persists between different function calls

main( ){

increment( ) ;increment( ) ;increment( ) ;

}increment( ){

auto int i = 1 ;register int j = 1 ;static int k = 1 ;i++ ; printf ( ”%d %d %d”, i, j, k ) ;

j++ ; k++ ;

2 2 2

2 2 3

2 2 4}

f( )

main( ){

When to Use Static

f( ) ;

int a = 20 ;return ( &a ) ;

}

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

}

int *p ; int * f( ) ;

{

20 250a p

250

int * f( ) char ** f ( int *, float * ) ;char ** f ( int *, float * ) ;static int a = 20 ;

External Storage Classmain( ){

printf ( ”%d”, a ) ;increment( ) ;increment( ) ;decrement( ) ;printf ( ”%d”, a ) ;

}increment( ){

a++ ; printf ( ”%d”, a ) ;}decrement( ){

a-- ; printf ( ”%d”, a ) ;}

1011121111

int a = 10 ;

Output

Declaration V/s Definitionmain( ){

int a = 10 ;

extern int a ;

extern int a ;

extern int a ;

printf ( ”%d”, a ) ;increment( ) ;increment( ) ;decrement( ) ;printf ( ”%d”, a ) ;

}increment( ){

a++ ; printf ( ”%d”, a ) ;}decrement( ){

a-- ; printf ( ”%d”, a ) ;}

DeclarationDeclaration

DefinitionDefinition

DeclarationDeclaration

DeclarationDeclaration

float square ( float ) ;

float square ( float ) {

..

..}

float square ( float ) ;

float square ( float ) {

..

..}

DefinitionDefinition

Declaration V/s Definitionmain( ){

int a = 10 ;

extern int a ;

extern int a ;

extern int a ;

printf ( ”%d”, a ) ;increment( ) ;increment( ) ;decrement( ) ;printf ( ”%d”, a ) ;

}increment( ){

a++ ; printf ( ”%d”, a ) ;}

a-- ; printf ( ”%d”, a ) ;}

decrement( ){

Declaration V/s Definitionmain( ){

int a = 10 ;

extern int a ;

extern int a ;

extern int a ;

printf ( ”%d”, a ) ;increment( ) ;increment( ) ;decrement( ) ;printf ( ”%d”, a ) ;

}

a++ ; printf ( ”%d”, a ) ;}

a-- ; printf ( ”%d”, a ) ;}

decrement( ){

increment( ){

Two Types Of Conflicts

main( ){

int a = 10 ;

int a = 20 ;{

int a = 30 ;printf ( ”%d”, a ) ;

}printf ( ”%d”, a ) ;

printf ( ”%d”, a ) ;}

30

20

External Storage Class

Storage

Default Initial Value

Scope

Life

Memory

0

Global

Till execution of the program doesn’t end

Which is The Most Powerful

Automatic Register Static External

If variable required byall functions

If variable is to live across function calls

For frequently used variables

All other cases

Ctrl F9

F9

F7

F8

Compile and Execute

Compile

Step into

Step over

C Preprocessor

main( ){

int a = 10 ;float b = 3.5 ;display( ) ;printf ( ”Hello” ) ;

}display( ){

printf ( ”Nagpur” ) ;}

A Closer LookHand written program

Text Editor

C Source CodePreprocessor

CompilerExpanded source code

Object code

Executable code

Linker

C :

TC

WORKS

WS4 . .Helps in typing a program

Helps in typing a program

Expands the source codeExpands the source code

Converts expanded sourcecode into machine languageConverts expanded sourcecode into machine language

Why IDE Editor

Preprocessor

Compiler

Linker

Ctrl F9

Turbo C/C++Turbo C/C++

Preprocesses,Compiles, Links

and Executes

Types of Preprocessor Directives

File Inclusion

Macro Expansion

Conditional Compilation

Miscellaneous Directives

Preprocessor In Action

main( ){

clrscr( ) ;gotorc ( 10, 20 ) ;printf ( ”Hello !” ) ;

}

Source Code

# include ”goto.c”

Ctrl F9

Preprocessormain( ){

clrscr( ) ;gotorc ( 10, 20 ) ;printf ( ”Hello !” ) ;

}

gotorc( - , - ) {

---

}

Expanded source code

Compiler

Unresolved Externals

main( ){

---

}

gotorc( - , - ) {

---

} Compilermachine languagecode of gotorc( )

machine language code of main( )

Error Why?

Solution

m/c language codeof gotorc( )

m/c language codeof main( )

m/c language codeof clrscr( )

m/c language codeof printf( )

LinkerLinker

Executable code

# include ”goto.c”# include <goto.c>

Your wish

C :

TC

WORKS

WS4 . .

INCLUDE

C:\ TC\ INCLUDE

C:\ TC\ LIB

C:\ TC\ WORKS

C:\ TC

INCLUDE DIRECTORIES

LIBRARY DIRECTORIES

OUTPUT DIRECTORY

SOURCE DIRECTORIES

Chapter 6 Chapter 6

Chapter 6 Chapter 6

Macro Expansion# define LOWER 1

main( ){

int i ;for ( i = LOWER ; i <= UPPER ; i++ )

printf ( ”\n%d”, i ) ;}

# define UPPER 10

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

Macro Template

Macro Expansion

Macro Expansion# define PI 3.14main( ){

float r, a ; printf ( ”Enter radius” ) ;scanf ( ”%f”, &r ) ;a = PI * r * r ;printf ( ”\n%f”, a ) ;

}

a = 3.14 * r * r ;a = 3.14 * r * r ;

3.141528

# define PI 3.14PI = 6.28 ;

float PI = 3.14 ;PI = 6.28 ;

Don’t Remember ConstantsAvogadro’s Number

# define PLANK 6.634E-24main( ){

a = PLANK * … ;b = PLANK / …. ;c = PLANK + … ;d = PLAN - …. ;

}

Plank’s Constant

6.023 * …..6.634 * …..

DetectedError

Detected

Types Of Macros

Macros WithMacros WithArguments

Simple Macros

Macros With Arguments# define PI 3.14# define AREA ( x ) PI * x * x main( ){

float r, a ; scanf ( ”%f”, &r ) ;a = AREA ( r ) ;printf ( ”\n%f”, a ) ;a = area ( r ) ;

}float area ( float rr ) {

return ( PI * rr * rr ) ;}

a = 3.14 * r * r ;a = 3.14 * r * r ;

float area ( float rr ) ;

Macros - FasterFunctions - Less SpaceMacros - FasterFunctions - Less Space

Order is unimportant

Macros With Arguments# define S ( x ) x * x main( ){

int i, j, k, l, x, n = 2 ; i = S ( 4 ) ;j = S ( 2 + 2 ) ;k = S ( 3 + 1 ) ;l = S ( 1 + 3 ) ;m = S ( ++n ) ;

printf ( ”%d %d %d %d %d %d”, i, j, k, l, n, x ) ;}

j = 2 + 2 * 2 + 2 ;j = 2 + 2 * 2 + 2 ;

k = 3 + 1 * 3 + 1 ;k = 3 + 1 * 3 + 1 ;

i = 1 + 3 * 1 + 3 ;i = 1 + 3 * 1 + 3 ;

i = 4 * 4 ;i = 4 * 4 ;

16 8 7 7 4 1616 8 7 7 4 16

Alt F Dos ShellC> CPP PR1.CC> exit

Alt F Dos ShellC> CPP PR1.CC> exit

m = ++n * ++n ;m = ++n * ++n ;

Conditional Compilation

scanf ( .. ) ; /* input */.... /* formula */..

}

main( ){

..

..

../*

*/

Conditional Compilation

scanf ( .. ) ; /* input */.... /* formula */..

}

main( ){

..

..

..# ifdef YES

# endif

2 Solutions :- # define YES- Delete # ifdef, # endif

2 Solutions :- # define YES- Delete # ifdef, # endif

Miscellaneous Directives

a = YES - .. ;printf ( ”YES” ) ;

}f( ){

int YES ;}

main( ){

a = YES + .. ;# define YES 20

# undef YES

# define YES 10 RedefinitionOK

Never Replaced

# pragma

asm stc asm pushfasm pop flags..

}

main( ){

..

..

..

..

# pragma inline

F7, F8, F9, Ctrl F9Won’t Work

How much C

10 %?20 % ?

30 %?Control Instruc.ifelseforwhile do break continueswitchcasedefault

Control Instruc.ifelseforwhile do break continueswitchcasedefault

Storage Classesautoregisterstaticextern

Storage Classesautoregisterstaticextern

gotoreturnvoid

Data Typesint charfloatlongdoubleshortsignedunsignednearfar

Data Typesint charfloatlongdoubleshortsignedunsignednearfar

27 / 32

Arraysmain( ){

printf ( ”Enter Marks” ) ;scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;per = ( m1 + m2 + m3 ) / 3 ;printf ( ”%d”, per ) ;

}

int m1, m2, m3, per ;

for ( i = 1 ; i <= 10 ; i++ ){

}

int i ;

printf ( ”%d”, per ) ;

Choices Available

Use 10 variables each holding 1 value

Use 1 variable holding all 10 values

Array

What is an Array?Array is a variable capable of holding more than 1 value at a time

Nothing Different32, 62, 65, 42, 48, 70, 80, 86, 92, 68{ }per =

In General peri

subscript

H2O

superscript

per perii

per ( i )per ( i ) per [ i ]per [ i ]

Screen

per3per1 per6per10

H2O

main( ){

printf ( ”Enter Marks” ) ;scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;per[ i ] = ( m1 + m2 + m3 ) / 3 ;

}

int m1, m2, m3, per[ 10 ] ;

for ( i = 1 ; i <= 10 ; i++ ){

}

int i ;

printf ( ”%d”, per[ i ] ) ;for ( i = 1 ; i <= 10 ; i++ )

0 9

0 9

Array?A

Screen

00

Initializing Arraysint i = 2 ;main( )

{int a[ ] = { 7, 6, 11, -2, 26 } ;

optional

int b[ 10 ] ; compulsory

int c[ ] = { 16, 13, -8, -7, 25 } ;10printf ( ”%d%d”, sizeof ( a ), sizeof ( b ) ) ;printf ( ”%d%d”, a[ 0 ], b[ 0 ] ) ;scanf ( ”%d%d%d”, ) ;&c[ 7 ], &c[ 8 ], &c[ 9 ]c[ 5 ] = 3 + 7 % 2 ;c[ 6 ] = c[ 1 ] + c[ 3 ] / 16 ;

}

10 20

int i ;i = 2 ;

7 G

MoralArrays can be initializedArray elements can be scannedArray elements can be calculatedArithmetic on array elements is allowed

Then how are they different?

Storagemain( ){

int i = 3, j = 20, k = -5, l = 7, m = 11 ;int a[ ] = { 3, 20, -5, 7, 11 } ; int ii ;printf ( ”%u %u %u %u %u”, &i, &j, &k, &l, &m ) ;for ( ii = 0 ; ii <= 4 ; ii++ )

printf ( ”%u”, &a[ ii ] ) ;

502 504 506 508 510

3 20 -5 7 11502 504 506 508 510

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

100 }

400 500 700 600

3i

10020j

400

k-5500

7l

70011m

600

a[ ] = { 2, 1.4, ’A’, 6 } ; - Adjacency- Similarity

int

Bounds Checking

main( ){

int a[ ] = { 3, 60, -5, 7, 11 } ;int i ;for ( i = 0 ; i <= 4 ; i++ )

printf ( ”%d”, a [ i ] ) ;}

a[ i ] = a[ i ] * 2 ;for ( i = 0 ; i <= 4 ; i++ )

0

0

Subscript outof range

3 60 -5 7 11500 502 504 506 508

a[0] a[1] a[2] a[3] a[4] a[5] a[6]

510 512

So ...Arrays are variables capable of storingmultiple valuesArray elements are stored in adjacentmemory locations

Checking the bounds of an array is programmer’s responsibility

Selection Sortmain( ){

int a[ ] = { 17, 6, 13,12, 2 } ;int i, j, t ;for ( i = 0 ; i <= 3 ; i++ ){

for ( j = 1 ; j <= 4 ; j++ ){

if ( a[ i ] > a[ j ] ){

t = a [ i ] ; a[ i ] = a[ j ] ;a[ j ] = t ;

}}

}for ( i = 0 ; i <= 4 ; i++ )

printf ( ”%d”, a[ i ] ) ;}

i +

17 6 13 12 2 i6 17 13 12 2 0 - 1

0 - 20 - 30 - 4

6 17 13 12 26 17 13 12 22 17 13 12 62 1 - 22 2 2 6 2 6

2 6 12

13 17 12 612 17 13 6 1 - 36 17 13 12 1 - 4

13 17 1212 17 13

2 - 32 - 4

13 17 3 - 4

j

Bubble Sortmain( ){

int a[ ] = { 17, 6, 13, 12, 2 } ;int i, j, t ;for ( j = 0 ; j <= 3 ; j++ ){

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

if ( a[ i ] > a[ i + 1 ] ){

t =a[ i ] ;a[ i ] = a[ i + 1 ] ;a[ i + 1 ] = t ;

}}

}for ( i = 0 ; i <= 4 ; i++ )

printf ( ”%d”, a[ i ] ) ;}

- j

17 6 13 12 2 i 6 17 13 12 2 0 - 1

1 - 22 - 33 - 4

6 13 17 12 26 13 12 17 26 13 12 2 17

6 13 12 2 0 - 16 12 13 2 6 12 2 136 12 2 6 2 12

2 6

1 - 22 - 3

13 17 0 - 11 - 2

12 13 17 0 - 1

i+1

17

13 17

17

17

Sorting Procedures

Selection Sort Bubble Sort Shell Sort Shuttle Sort Heap Sort Merge Sort Radix Sort Quick Sort

qsort( )

Recursion

Fastest?

log2n

n2

main( ){

int a[ ] = {17, 6, 13, 12, 2 } ;

Quick Sort At Work

qsort ( a, 5, sizeof ( int ), fun ) ;for ( i = 0 ; i <= 4 ; i++ )

printf ( ”\n%d”, a[i] ) ;}fun ( int *i, int *j ){

return ( *i - *j ) ;}

int i ;int fun ( int *, int * ) ;

ComparisonFunction

Chapter 7 Pg 209-212244-249 (C)

Chapter 7 Pg 209-212244-249 (C)

Chapter 7 Chapter 7

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;102 104 106 108 110

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

int i ;printf ( ”%u %u %u”, &a[ 0 ], &a[ 1 ], &a[ 2 ] ) ;

printf ( ”%u %u %u”, a, a + 1, a + 2 ) ;

printf ( ”%d %d %d”, *a, *( a +1 ), *( a + 2 ) ) ;

for ( i = 0 ; i <= 4 ; i ++ )printf ( ”%d”, *( a + i ) ) ;

for ( i = 0 ; i <= 4 ; i ++ )printf ( ”%d”, a[ i ] ) ;

}

102 104 106

102 104 106

7 9 16

8-21697Another Form...

SubscriptNotation

PointerNotation

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;int i ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, a[ i ] ) ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, *( a + i ) ) ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, *( i + a ) ) ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, i[ a ] ) ;}

a[ i ]i[ a ]

*( a + i ) *( i + a )

More Forms...

Flexible Arrays

Size of an array must always be mentionedas a positive, non-zero, integer constant

int a[ n ] ;scanf ( ”%d”, &n ) ;

1012

main( ){

float a = 3.14char ch = ’z’int i = 25b = &a ; dh = &ch ; j = &i ;printf ( ”%u %u %u”, b, dh, j ) ;b++ ; dh++ ; j++ ;printf ( ”%u %u %u”, b, dh, j ) ;b += 3 ; dh += 8 ; j -= 3 ;printf ( ”%u %u %u”, b, dh, j ) ;

}

, *b ;, *dh ;

, *j ;

3.14a

z 251008 2009 6002

ch i

1008b

2009 6002dh j

1024

Pointer Arithmetic

1008 2009 6002

60042010

59982018

Legal Pointer Arithmetic

Pointer + number

Pointer - PointerPointer - number

Pointer Pointer Number

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;int *p ; int i ;p = a ; /* same as &a[ 0 ] */printf ( ”%d”, *p ) ; 7p++ ;printf ( ”%d”, p ) ; 104printf ( ”%d”, *p ) ;

9for ( i = 0 ; i <= 4 ; i++ )

printf ( ”%d”, *p ) ;p++ ;

{

}}

102p p

104p++

*p

Ist

* ++p ;

IstIInd

++ *p ;

p = a ;

102 104 106 108 110

a[0] a[1] a[2] a[3] a[4]8-21697

++ ;*

IInd

p++ ;

Access Using Pointers

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;int *p ; int i ;p = a ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d %d %d %d”,

}

*( p + i ), *( i + p ),p[ i ], i[ p ] ) ;

[ ] For Notation...

102 104 106 108 110

a[0] a[1] a[2] a[3] a[4]8-21697

int a[5] ; int 5[a] ;printf ( ”%d”, a[2] ) ; printf ( ”%d”, 2[a] ) ;

main( ){

char far *s = 0xB8000000 ; int i ;for ( i = 0 ; i <= 3999 ; i += 2 ){

if ( *( s + i ) >= ’A’ && *( s + i ) <= ’Z’ )

}}

Dancing Dolls Revisited

s[ i ]s[ i ]

* ( i + s )

i[ s ]

a[i]

- One is pointeror array

- Other is int

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;int *p ; int i ;p = a ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, *p ) ;p++ ;

{

}

}

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

printf ( ”%d”, *a ) ;a++ ;

{

} Error

Changing Array Address

102 104 106 108 110

a[0] a[1] a[2] a[3] a[4]8-21697

a-- ;a = a + 2 ;a = a - 2 ;a += 2 ;a -= 2 ;

a-- ;a = a + 2 ;a = a - 2 ;a += 2 ;a -= 2 ;

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;int i ;display ( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ] ) ;for ( i = 0 ; i <= 4 ; i++ )

display1 ( a[ i ] ) ;}display ( ){

printf ( ”%d %d %d %d %d”, i, j, k, l, m ) ;}display1 ( ){

printf ( ”%d”, n ) ;}

int i, int j, int k, int l, int m

int n

Passing Array Elements

Whichis good?Which

is good?

main( ){

int a[ ] = { 7, 9, 16, -2, 8 } ;display2 ( a ) ;display3 ( a ) ;

}display2 ( )int *p

int i ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, ) ;}

*( p + i )

, sizeof ( a ) / 2 - 1

{

display3 ( )int *p{

, int n

int i ;for ( i = 0 ; i <= 4 ; i ++ )

printf ( ”%d”, ) ;} *( p + i )

i <= n

Passing Entire Array

102 104 106 108 110

a[0] a[1] a[2] a[3] a[4]8-21697

qsort ( a, 5, , , ) ;qsort ( a, 5, , , ) ;

Any time an entire array is to be passedto function, it is necessary to pass(1) Base address of array(2) No. of elements present in the array

Remember...

printf ( ”%d”, a[ ][ ] ) ;

Two Dimensional Arraymain( ){ int a[ ][ ] = {

{ 2, 6, 1, 8, 4 }{ 1, 2, 5, 6, 8 }{ 7, 9, 8, 7, 21 }{ 4, 5, 6, 8, 10 }

} ;int i, j ;

2 4printf ( ”%d %d”, sizeof ( a ), a ) ; for ( i = 0 ; i <= 3 ; i++ ) {

for ( j = 0 ; j <= 4 ; j++ ) printf ( ”%d”, a [ i ][ j ] ) ;

printf ( ”\n” ) ;}}

5

int b[ ][1][2][3]optional

compulsory21

40 4080

optional,,

,

compulsory

compulsoryoptional

ExceptionException

main( ){

int a[ ][ ] = {7, 2, 6, 13, 5, 4, 86, 2, 9, 50 1, 2, 3, 8

} ;

,,,

big = a[ 0 ][ 0 ] ; for ( i = 0 ; i <= 3 ; i++ )

for ( j = 0 ; j <= 3 ; j++ ){{

if ( a[ i ][ j ] > big )

big = a[ i ][ j ] ;{

r = i ; c = j ;}

}}printf ( ”%d ”, big ) ; printf ( ”%d %d ”, r, c ) ;

}

4

r = 0 ; c = 0 ;int i, j, big ; int r, c ;

Find Biggest...

Find Second Biggestand its Position

int a[ ][ ] = {7, 2, 6, 1, 9, 3, 4, 5, 10, 12, 16, 18

} ;

4Row Major

502 504 506 508 510 512 514 516 518 520 522 524printf ( ”%d ”, a ) ;printf ( ”%d ”, *a ) ;printf ( ”%d %d %d ”, a+0 , a+1 , a+2 ) ;printf ( ”%d %d %d ”, *(a+0) , *(a+1) , *(a+2) ) ;printf ( ”%d %d %d ”, a[0] , a[1] , a[2] ) ;printf ( ”%d %d %d ”, a[0]+1 , a[1]+2 , a[2]+3 ) ;printf ( ”%d %d %d ”, *(a[0]+1) , *(a[1]+2) ,

*(a[2]+3) ) ;printf ( ”%d %d %d ”, a[0][1] , a[1][2] , a[2][3] ) ;

5027

502 504 5067 2 67 2 68 4 9

Garbage/ Error2 4 18}

main( ){

9 3 4 5 10 12 16 181627

int a[ ][ 4 ] = {7, 2, 6, 1 , 9, 3, 4, 5, 10, 12, 16, 18

} ;

502 510 5187 2 6 1 9 3 4 5 10 12 16 18

printf ( ”%d”, a ) ;printf ( ”%d”, *a ) ;

502

1627

int b[ ] = { 7, 2, 6, 1 } ;

402

printf ( ”%d”, b ) ;printf ( ”%d”, *b ) ;

402

7

502

5

int i = 5 ;printf ( ”%d”, i ) ;

5

i

200

int a[ ][ ] = {7, 2, 6, 1, 9, 3, 4, 5, 10, 12, 16, 18

} ;

4Row Major

502 510 514 518 524printf ( ”%d ”, a ) ;printf ( ”%d ”, *a ) ;printf ( ”%d %d %d ”, a+0 , a+1 , a+2 ) ;printf ( ”%d %d %d ”, *(a+0) , *(a+1) , *(a+2) ) ;printf ( ”%d %d %d ”, a[0] , a[1] , a[2] ) ;printf ( ”%d %d %d ”, a[0]+1 , a[1]+2 , a[2]+3 ) ;printf ( ”%d %d %d ”, *(a[0]+1) , *(a[1]+2) ,

*(a[2]+3) ) ;printf ( ”%d %d %d ”, a[0][1] , a[1][2] , a[2][3] );

502502

502 510 518

2 4 18}

main( ){

9 3 4 5 10 12 16 181627

502 510 518502 510 518504 514 524

2 4 18

a[2][3] * ( a[2] + 3 ) * ( * ( a + 2 ) + 3 )

Moral...

1-D

2-D

3-D

4-D

Arraya[ i ] *( a+i )

a[ i ][ j ] *( *( a+i ) + j )

a[ i ][ j ][ k ] *( *( *(a + i ) + j ) + k )

a[ i ][ j ][ k ][ l ] *( *( *( *(a + i ) + j ) + k )+ l )

Subscript Pointer

3 Ways

int i, j ;for ( i = 0 ; i <= 2 ; i++ )

main( ){

int a[ ][ 4 ] = {7, 2, 6, 1, 9, 3, 4, 5, 10, 12, 16, 18

} ;

{for ( j = 0 ; j <= 3 ; j++ )

printf

}}

( ”%d %d %d”, a[ i ][ j ] ,*( a[ i ] + j ) , *( *( a + i ) + j ) ) ;

a[i][j][k]

*( a[i][j] + k )

*( *( a[i] ) + j ) + k )

*( *( *(a + i ) + j ) + k )

printf ( ”%d %d”, r, q ) ;

int a[ ][ 4 ] = {7, 2, 6, 1, 9, 3, 4, 5, 10, 12, 16, 18

} ;

main( ){

int *p[ 4 ] ; int *r ;int ( *q )[ 4 ] ;p[ 0 ] = &a[ 0 ][ 0 ] ;p[ 1 ] = &a[ 2 ][ 2 ] ;p[ 2 ] = p[ 3 ] = &a[ 1 ][ 1 ] ;printf ( ”%d”, p ) ;r = a ; q = a ;r++ ; q++ ;

}

130

504 510

512512522502130 132 134 136

r q

p[ ]502 510 5187 2 6 1 9 3 4 5 10 12 16 18

Different?

502 502

Applications of 2-D ArraysMatrices - Addition, Multiplication,

Chess

QQ

Q

QQ

Q

Q8 8Board

Determinant,Transpose, Inverse etc .

The Solution

QQ

QQ

QQ

QQ

100 More...

int v, j, k, l, s, a[ 99 ] ;main( ){

for ( scanf ( ”%d”, &s ) ;*a - s ; v = a[ j*=v ] - a[i], k = i < s,j += ( v = j < s && ( !k && !! printf (

2 + ”\n\n%c” - ( !l << !j ),”Q” [ l^v ? ( l ^ j ) & 1 : 2] ) &&++l||a[i] < s && v && v - i + j && v + i - j )

)&& ! ( l % = s ), v || ( i == j ? a[i += k] =0 : ++a[i] >= s *k && ++a[--i] )

;}

The Program...

Knight’s Tour

K

Conditions :- Visit every house- Don’t revisit any house

Conditions :- Visit every house- Don’t revisit any house

1

234

567

8

9

One Up, One Right

Earn A TV...

Puzzle

1 2

3 49 7

10 14 13 11

6 5

12

158

int a[ ][4 ]= {10, 14, 13, 11, 9, 7, 6, 5, 3, 4, 8, 15,1, 2, 12, 0

} ;

# include ”goto.c”

main( ){

clrscr( ) ;boxes( ) ;display( ) ;. .

}

(10, 20 )

(18, 32)1 2

3 49 7

10 14 13 11

6 5

12

158

display( ){

int i, j, r = 11, c = 21 ; for ( i = 0 ; i <= 3 ; i++ ){

for ( j = 0 ; j <= 3 ; j++ ){

gotorc ( ) ;r, cif ( a[ i ][ j ] ! = 0 )

printf ( ”%d”, a[ i ][ j ] ) ;else

printf ( ”- -” ) ;c = c + 3 ;

}

}}

r = r + 2 ;c = 21 ;

(10, 20 )

(18, 32 )1 2

3 49 7

10 14 13 11

6 5

12

158

2 Spaces

# include ”goto.c”int a[ ][ ]= {

. . } ;

main( ){

clrscr( ) ;boxes( ) ;display( ) ;gotorc ( 20, 25 ) ;printf ( ”Use arrow keys to move nos.” ) ;ch = getkey( ) ;. .. .

}

Scan Codes72

80

7775

Optionsscanf ( ”%c”, &ch ) ;

getch( ) ;ch =

int ch ;

# include ”goto.c”int a[ ][ 4 ]= {

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

} ; main( ){ . .

switch ( ch ){

case 80 :t = a[ 3 ][ 3 ] ; a[ 3 ][ 3 ] = a[ 2 ][ 3 ] ;a[ 2 ][ 3 ] = t ;display( ) ;break ;

}}

1 2

3 49 7

10 14 13 11

6 5

12

158

. . .

ch = getkey( ) ;

int a[ ][ 4 ]= {10, 14, 13, 11, 9, 7, 6, 5, 3, 4, 8, 15,1, 2, 12 , 0

} ; main( ){

switch ( ch ){

case 80 :t = a[ r ][ c ] ; a [ r ][ c ] = a[ r - 1 ][ c ] ;

display( ) ;

break ;}}

a [ r - 1 ][ c ] = t ;

r-- ;

int r = 3, c = 3 ;1 2

3 49 7

10 14 13 11

6 5

12

158

ch = getkey( ) ;

int a[ ][4]= {10, 14, 13, 11, 9, 7, 6, 5, 3, 4, 8, 15,1, 2, 12, 0

} ;

int a[ ][4]= {10, 14, 13, 11, 9, 7, 6, 5, 3, 4, 8, 15,1, 2, 12, 0

} ;

switch ( ch ){ case 80 :

if ( r ! = 0 ){

t = a[ r ][ c ] ;

display( ) ;

break ;

a[ r - 1 ][ c ] = t ;

r-- ;

a[ r ][ c ] = a[ r - 1 ][ c ] ;

}else

printf ( ”\a” ) ;

}

1 2

3 49 7

10 14 13 11

6 5

12

158

ch = getkey( ) ;

switch ( ch ){ case 80 :. .. .

case 72 :if ( r != 3 ){

t = a[ r ][ c ] ;

display( ) ;

break ;

a[ r + 1 ][ c ] = t ;

r++ ;

a[ r ][ c ] = a[ r + 1 ][ c ] ;

}else

printf ( ”\a” ) ;

}. .. .

1 2

3 49 7

10 14 13 11

6 5

12

158

ch = getkey( ) ;

main( ){ . .

gotorc ( 20, 25 ) ;printf ( ”Use arrow keys… ” ) ;

switch ( ch ){ case 80 :

case 72 :case 75 :case 77 :case 1 :

exit( ) ;default :

printf ( ”\a” ) ;}

}

Esc to Exit

main( ){

char ch ;ch = getkey( ) ;printf ( ”%d”, ch ) ;

}

ch = getkey( ) ;#include ”goto.c”

OK

main( ){

. .

. .while ( 1 ){

ch = getkey( ) ;switch ( ch ){

case 80 :case 72 :case 75 :case 77 :

}

}}

check( ) ;

Tic-Tac-Toe

3-D Arraysmain( ){ int a[ ][ ][ ] = {

{3, 7, 2, 5,6, 1, 4, 8

} ,{

4, 5, 3, 2,0, 0, 1, 7

} , {

4, 8, 5, 12,6, 0, 0, 100

}

2 4

}} ;

main( ){

int a[ ][ ][ ] = {. .

} ;

2 4

printf ( ”%d%d”, sizeof ( a ), a[ 2 ][ 1 ][ 3 ] ) ;printf ( ”%d”, ) ;* ( * ( * ( a + 2 ) + 1 ) + 3printf ( ”%d%d%d%d”, a, *a, **a, ***a ) ;

} a[0][0][0]

* ( * ( * ( a + 0 ) + 0 ) + 0 )

36 1 4 8

7 2 5 72354

4 8 5 12100

48 100

100

400 400400 3

Stringsmain( ){

char name[ ] = { ’S’, ’a’, ’n’, ’j’, ’a’, ’y’, } ;’\0’int i ;for ( i = 0 ; i <= 5 ; i++ )

printf ( ”%c”, name[ i ] ) ;i = 0 ;while ( name[ i ] ! = ’\0’ ){

printf ( ”%c”, name[ i ] ) ;i++ ;

}}

name[ i++ ]

main( ){

char name[ ] = { ’S’, ’a’, ’n’, ’j’, ’a’, ’y’, } ;’\0’int i ;printf ( ”%d%d”, ’\0’, ’0’ ) ;

0 48

i = 0 ;while ( name[ i ] ! = 0 )

printf ( ”%c”, name[ i++ ] ) ;

}

i = 0 ;while ( name[ i ] )

printf ( ”%c”, name[ i++ ] ) ;

Two More Ways

for ( i = 0 ; i <= 5 ; i++ ) while ( name[ i ] ! = ’\0’ )while ( name[ i ] ! = 0 )while ( name[ i ] )printf ( ”%s”, name ) ;

Which Is Best?

display3 ( a, sizeof ( a ) / 2 - 1 ) ;display4 ( name ) ;display3 ( a, sizeof ( a ) / 2 - 1 ) ;display4 ( name ) ;

Why?

Chapter 8 Chapter 8

Chapter 8 Chapter 8

char str1[ ] = { ’S’, ’a’, ’n’, ’j’, ’a’, ’y’, } ;char str2[ ] = ”Sanjay” ;

printf ( ”%d%d”, sizeof ( str1 ), sizeof ( str2 ) ) ;printf ( ”Enter name & surname” ) ;scanf ( ”%s”, str3 ) ;printf ( ”%s”, str3 ) ;printf ( ”Enter name & surname” ) ;

printf ( ”%s”, str3 ) ;gets ( str3 ) ;

}

char str3[ 15 ] ;

’\0’ 7 7

Rahul

Rahul Sood

Multiword Stringsmain( ){

Rahul Sood

Rahul Sood

puts ( str3 ) ;

33.0’3’”3”

Different

\0 Assumed

StringTerminator

char str1[ ] = ”Amol” ;char str2[ ] = ”Sanjay” ;

printf ( ”%s%s%s”, str1, str2, str3 ) ;

gets ( str1 ) ;gets ( str2 ) ;gets ( str3 ) ;

char str3[ ] = ”Rahul” ;

Which Is Better?main( ){

puts ( str1 ) ;puts ( str2 ) ;puts ( str3 ) ;scanf ( ”%s%s%s”, str1, str2, str3 ) ;

}

while ( )

char str [ ] = ”Sanjay” ;char *p ;p = str ;

{printf ( ”%c”, *p ) ;p++ ;

}}

*p != ’\0’

401p p++ 402

p

401 2 3 4 5

ppstr[ ]

7a y \0jnaS

6

Think Differentlymain( ){

p

}

printf ( ”Hello” ) ;printf ( 2 + 3 % 2 + ”Mechanical” ) ;

Hellohanical

Output ?

main( ){

while ( ){

..

p++ ;}

*p != ’\0’

printf ( char *p, … ){

}

printf ( ”\nsi = Rs. %f”, si ) ;printf ( ”\nsi = Rs. %f”, si ) ;

while ( *p != ’\0’ )

char str1[ ] = ”Nagpur” ;char str2[ ] = ”Ahmedabad” ;

strlen ( str1 ) ;l1 = strlen( str1 ) ;xstrlen ( str1 ) ;int l1 ;

l2 = xstrlen ( str2 ) ;

}

6 9

xstrlen ( )char *p6

{int count = 0 ;

{

}

count ++ ; }

p++ ;

return ( count ) ;

p

401 2 3 4 5 7u r \0pgaN

6

401p

int l2 ;

printf ( ”%d%d”, l1, l2 ) ;l3 = xstrlen ( ”Baroda” ) ;printf ( ”%d”, l3 ) ;

int l3 ;

main( ){

strcpy ( str2, str1 ) ;N

while ( *s != ’\0’ )

}xstrcpy ( )char *t, char *s

Bombay

{

{}

}

printf ( ”%s”, str3 ) ;

printf ( ”%s”, str2 ) ;xstrcpy ( str3, ”Bombay” ) ;

*t = *s ;

u r \0pgaN

s

t

Nagpurxstrcpy ( str2, str1 ) ;

Copying Strings

char str1[ ] = ”Nagpur” ;char str2[ 10 ] ;char str3[ 20 ] ;str2 = str1 ;

main( ){

t++ ;s++ ;

*t = ’\0’ ;

a g p u r

xstrcpy ( char *t, char *s ){

while ( *s != ’\0’ )

t++ ;s++ ;

*t = ’\0’ ;}

{*t = *s ;

}

xstrcpy ( char *t, char *s ){

while ( *s )*t++ = *s++ ;

*t = ’\0’ ;}xstrcpy ( char *t, char *s ){

while ( *t++ = *s++ )}

More Ways...

u r \0pgaN

;s s

u r \0pgaNt t

*t = *swhile ( *t )t++s++

while ( i = 2 )while ( i = 2 )

char str1[ ] = ”Nagpur” ;char str2[ ] = ”Bombay” ;xstrcat ( str1, str2 ) ;printf ( ”%s”, str1 ) ;

}xstrcat ( char *t, char *s ){

while ( *t )t++ ;

while ( *s )*t++ = *s++ ;

*t = ’\0’ ;}

NagpurBombay

tu r \0pgaN

t

sa y \0bmoB

Concatenationmain( ){

20

A Shorter Version...xstrcat ( char *t, char *s ){

while ( *t )t++ ;

while ( *s )*t++ = *s++ ;

*t = ’\0’ ;}

ttu r \0pgaN

sa y \0bmoB

t = t + strlen ( t ) ;

strcpy ( t, s ) ;

char str1[ ] = ”Kanpur” ;char str2[ ] = ”Raipur” ;char str3[30] ;

printf ( ”%s”, str3 ) ;

strcpy ( str3, str1 ) ;strcat ( str3, str2 ) ;

}

Concatenationmain( ){

KanpurRaipur

strcpy ( str3, str1 ) ;strcpy ( str3 + strlen ( str3 ), str2 ) ;strcpy ( str3, str1 ) ;strcpy ( str3 + strlen ( str3 ), str2 ) ;

str3[0] = ’\0’ ;xstrcat ( str3, str1 ) ;xstrcat ( str3, str2 ) ;

str3[0] = ’\0’ ;xstrcat ( str3, str1 ) ;xstrcat ( str3, str2 ) ;

Using onlystrcpy( )

Using onlystrcat( )

Convert To Uppercasemain( ){

char str[ ] = ”Nagpur” ;xstrupr ( str ) ;printf ( ”%s”, str ) ;

}

while ( *p )

xstrupr ( )char *p{

{

}}

if ( *p >= ’a’ && *p <= ’z’ )*p = *p - 32 ;

p++ ;

NAGPUR

What’s The Difference?

strupr( )strlwr( )

toupper( )tolower( )

Works onStrings

Works onChars

Can use tolower( )

& toupper( )

282 - 286(d)282 - 286(d)

xstrcmp ( str1, str4 ) ;

main( ){

char str1[ ] = ”Bombay” ;char str2[ ] = ”Nagpur” ;char str3[ ] = ”Bombaywala” ;char str4[ ] = ”Bombay” ;

strcmp ( str1, str2 ) ;xstrcmp ( str1, str3 ) ;

printf ( ”%d%d%d”, i, j, k ) ;

Non Zero Non

Zero

}0

k = xstrcmp ( str1, str4 ) ;

xstrcmp ( str1, str2 ) ;i = xstrcmp ( str1, str2 ) ;int i, j, k ;

Comparing Strings

j = xstrcmp ( str1, str3 ) ;

xstrcmp ()

char *t,char *s

while ( *t == *s ){

if ( *t == ’\0’ )break ;

t++ ;s++ ;

}return ( *t - *s ) ;

}

{

t

sa y wbmoB \0alaa y \0bmoB

tu r \0pgaN

sa y \0bmoB

i = xstrcmp ( str1, str2 ) ;

main( ){

}

Comparing Strings

main( ){

Outputting Strings

char str1[ ] = ”Nagpur” ;printf ( ”%s”, str1 ) ;xputs ( str1 ) ;

pu r \0pgaN

}

{while ( *p != ’\0’ )

printf ( ”%c”, *p ) ;p++ ;

}}

xputs ( char *p )

{

putch ( *p ) ;

strlenstrcpystrcatstruprstrlwrtouppertolowerstrcmpputsgets

strncpy ( str1, str2, 5 ) ;strncat ( str1, str2, 6 ) ;strncmp ( str1, str2, 6 ) ;strncmpi ( str1, str2, 4 ) ;strnicmp ( str1, str2, 4 ) ;strchr ( ”Hello”, ’e’ ) ;strstr ( ”I am a boy”, ”am” ) ;strsetstrnset. .. .. .

Standard Library Functions

main( ){

char str1[ ] = ;char str2[ ] = ;char str3[ ] = ;char str4[ ] = ;char str5[ ] = ;. .. .

”Sanjay””Amol””Sivaramakrishnan””Sameer””Rahul”

}

Handling Several Strings

char n[ ][ ] = {”Sanjay””Amol””Sivaramakrishnan””Sameer””Rahul”

} ;

,,

,,

printf ( ”%d”, sizeof ( n ) ) ;printf ( ”%c%c”, n[ 0 ][ 1 ], n[ 1 ][ 0 ] ) ;

100

a A}

20

main( ){

Array of Strings / 2-D Array

int i, j ; for ( )i = 0 ; i <= 4 ; i++{

for ( ) j = 0 ; j <= 19 ; j++{

if ( n[ i ][ j ] == ’\0’ )break ;

}}

}

401 421 441 461 481

printf ( ”%c”, n[ i ][ j ] ) ;

char n[ ][ 20 ] = { . .. .} ;

main( ){

Sanjay\0 Amol\0 Sivar...\0 Sameer\0 Rahul\0

int i, j ; for ( j = 0 ; j <= 19 ; j++ ){

}

char n[ ][ 20 ] = { ”Sanjay”, “Amol”, … } ;main( ){

401 421 441 461 481Sanjay\0 Amol\0 Sivar...\0 Sameer\0 Rahul\0

n[ 1 ][ j ] ;t =n[ 1 ][ j ] = n[ 2 ][ j ] ;n[ 2 ][ j ] = t ;

for ( i = 0 ; i <= 4 ; i++ )printf ( ”%s”, ) ;

}

&n[ i ][ 0 ]n + i

char t ;

Disadvantages

- Wastage- Inefficient Processing

Wastage13153

131458 Bytes

401 421 441 461 481Sanjay\0 Amol\0 Sivar...\0 Sameer\0 Rahul\0

400Sanjay\0

300Amol\0

600Sivar...\0

500Sameer\0

100Rahul\0

char *n[ ] = {

} ;

”Sanjay””Amol””Sivaramakrishnan””Sameer””Rahul”

,

,

,,

400 300 600 500 100n[ ]

202 4 6 8 10

int i ; char *t ;for ( i = 0 ; i <= 4 ; i++ )

printf ( ”%s”, ) ;n[ i ]t = n[ 1 ] ;n[ 1 ] = n[ 2 ] ;n[ 2 ] = t ;

for ( i = 0 ; i <= 4 ; i++ )printf ( ”%s”, n[ i ] ) ;

}

main( ){

main( ){

char *n[ ] = {

} ;

”Sanjay””Amol”

,,

SelectionSorti j0 - 10 - 20 - 30 - 41 - 21 - 31 - 42 - 32 - 43 - 4

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

for ( j = i + 1 ; j <= 4 ; j++ ){

if ( strcmp ( n[ i ], n[ j ] ) )> 0{

t = n[ i ] ; n[ i ] = n[ j ] ; n[ j ] = t ; }

}}

int i, j ; char *t ;

for ( i = 0 ; i <= 4 ; i++ )printf ( ”%s”, n[ i ] ) ;

}

Chapter 9Chapter 9

Chapter 9 Chapter 9

main( ){

int m, y ;long int normaldays ; long int totaldays ;

scanf ( ”%d%d”, &m, &y ) ; printf ( ”Enter month and year” ) ;

normaldays = ( y - 1 ) * 365 L ;leapdays = ( y - 1 ) / 4 - ( y - 1 ) / 100

+ ( y - 1 ) / 400 ;totaldays = normaldays +

leapdays ; . .}

8 1999

1/8/1999 - ?1/1/1 - Mon1/1/1999 - ?

1/1/1 to 31/12/1998

x % 71/8/1999 - ?1/1/1 to 31/7/1999

1/1/1 to 31/12/1998

+1/1/1999 to 31/7/1999x % 7

Calendar

int leapdays ;

main( ){

{ 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 } ;

int days[ ] =

int i, s ; int firstday ;. .. .totaldays = normaldays +

leapdays ; s = 0 ;for ( i = 0 ; i <= ; i++ )

s = s +totaldays += s ;firstday = totaldays % 7 ;. .

}

m - 2days[ i ] ;

1/1/1 to 31/12/1998

1/1/1999 to 31/7/1999

totaldays

31 + 28 + 31 + 30 + 31 + 30 + 31

...Calendar

( )

main( ){

{ 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 } ;

int days[ ] =

. .. .totaldays = normaldays + leapdays ; if ( ( y % 400 == 0 ) || )

days[ 1 ] = 29 ;s = 0 ;for ( i = 0 ; i <= ; i++ )

s = s +

. .}

days[ i ] ;m - 2

y % 100 != 0 && y % 4 == 0

...Calendar

totaldays += s ;firstday = totaldays % 7 ;

ScreenScreen

August 1999

10

20 26 32 38 44 50 56

Mon Tue Wed Thu Fri Sat Sun--- --- --- --- --- ---

10

20 26 32

Mon Tue Wed--- --- ---main( ){

. .. .totaldays += s ;firstday = totaldays % 7 ;

char *months[ ] = { ”January”, ”February”, … } ;

col = 20 + firstday * 6 ;clrscr( ) ;gotorc ( , ) ;8 35printf ( ”%s %d”, months [ m - 1 ] , y ) ;

}

...Calendar

gotorc ( , ) ;35printf ( ”Mon Tue Wed Thu Fri Sat Sun”

10) ;

for ( )i = 1 ; days[ m - 1 ] ; i++ i <= {

gotorc ( ) ;row, colprintf ( ”%d”, i ) ;col = col + 6 ;if ( col > 56 ){

row++ ; col = 20 ;}}}

...Calendarmain( ){

{ 31, 28, 31, 30, 31, 30, 31, 31, 30, … } ;int days[ ] =/* print month year *//* print days */

10

20 26 32

Mon Tue Wed--- --- ---

row = 12 ;

main( ){ . .

scanf ( ”%d%d”, &m, &y ) ; while ( 1 ){

normaldays = ( y - 1 ) * 365L ;____calender____gotorc ( ) ;printf ( ”Rt-Next mth…” ) ;ch = getkey( ) ;switch ( ch ){

case 77 :m++ ;if ( m > 12 ){

y++ ; m = 1 ;}____}

20, 35

}}

Next year

Prev. year

Prev.mth Next

mth

...Calendar

main( ){

{ 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 } ;

int days[ ] =

scanf ( ”%d%d”, &m, &y ) ; while ( 1 ){

normaldays =

totaldays = leapdays =

if ( y % 400 = = 0 ) || ( y % 100 ! = 0 && y % 4 = = 0 ) ) days[ 1 ] = 29 ;

elsedays[ 1 ] = 28 ;. .

}}

9, 19989, 20009, 17009, 1752

- 30- 30- 30- 16

...Calendar

TerminologyFields

Record

Database

Name Age Salary

’X’ 27 5000.00’Y’ 28 6000.75

’A’ 23 4000.50’A’ 23 4000.50

main( ){

char n[ ] = { ’A’, ’X’, ’Y’, ’\0’ } ;int a[ ] = { 23, 27, 28 } ;float s[ ] = { 4000.50, 5000.00, 6000.75 } ;int i ;for ( )i = 0 ; i <= 2 ; i++

printf ( ”%c %d %f”, n[ i ], a[ i ], s[ i ] ) ;}

Handling Data

printf ( ”%c %d %f”, n, a, s ) ;

main( ){

struct employee{

char n ;int a ;float s ;

} ;struct employee e { ’A’, 23, 4000.50 } ;struct employee e2 = { ’X’, 27, 5000.00 } ;struct employee e3 = { ’Y’, 28, 6000.75 } ;

1 =

e1. e1. e1.printf ( ”%c %d %f”, e2.n, e2.a, e2.s ) ;printf ( ”%c %d %f”, e3.n, e3.a, e3.s ) ;

}

.

structure operators

Structures

main( ){

struct employee{

char n ;int a ;float s ;

} ;struct employee e[ ]

{ ’A’, 23, 4000.50 } ,{ ’X’, 27, 5000.00 } ,{ ’Y’, 28, 6000.75 }

} ;

= {

int i ;for ( i = 0 ; i <= 2 ; i++ )

printf ( ”%c %d %f”, e[ i ]}

.n, e[ i ].a, e[ i ].s ) ;

Array of Structures

struct{

char n ;int a ;float s ;

} ;struct employee e1, e2, e[ 10 ] ;

Keyword employeeemployeestructStructure

name/tag

Structure elements/members

Structurevariables Array of

structures

ConclusionA structure is usually a collection of dissimilar elements.

Structure elements are always stored in adjacent memory locations.

struct employee e[ 3 ] ;400.50A 23 500.00X 27 600.75Y

401 408 41528

struct employee e[ ] = { ... } ;char *p ;

p = e ;p++ ;

printf ( ”%u”, q ) ;

Array of Structures

struct employee e[ 3 ] ;400.50A 23 500.00X 27 600.75Y

401 408 41528

struct employee *q ;struct employee (*r )[3] ;

q++ ; r++ ;q = e ; r = e ;

printf ( ”%u”, r ) ;

printf ( ”%u”, p ) ;

402402

408408

422422

Ptr. to structure

Array ofptrs.

282- 288282- 288

Chapter 9 Chapter 9

struct employee{

char n ;int a ;float s ;

} ;struct employee e

Declarations & Definitions

= { ”Rahul”, 25, 4000.50 } ;

OR

struct employee{

char n[20] ; int a ; float s ;

[20]

= { ”Rahul”, 25, 4000.50 } ;} e

Optional

Compulsory

, x, y

Copyingmain( ){ struct emp

{char n[20] ;int a ;float s ;

} ;struct emp e1 = { ”Rahul”, 23, 4000.50 } ;struct emp e2, e3 ;e2.n = e1.n ;

e2.s = e1.s ;

strcpy ( ) ;strcpy ( ) ;

e3 = e1 ;printf ( ”%s %d %f”, e3.n, e3.a, e3.s ) ;

e2.a = e1.a ;

}

piecemealcopying

copying atone shot

e2.n, e1.n

Copying Arraysint a[10] = { 3, 6, 5, … } ;int b[10] ;for ( i = 0 ; i <= 9 ; i++ )

b[i] = a[i] ;

struct z a

b = a ;

struct z {

int arr[10] ;} ;

struct z b ;

OR

= { 3, 6, 5, ... } ;

Nested Structuresmain( ){ struct address

{char city[20] ;long int pin;

} ;

struct emp e = { ”Rahul”, 23, ”Nagpur”, 440010,4000.50 } ;

printf ( ”%s %d%s%ld%f”, e.n,}

struct emp{

char n[20] ;

e.age, e.pin,e.s ) ;

e.city,

int age ; float s ;struct address a ;

} ;

e.a.pina.citye.a.city

printf ( ”%d”, a.b.c.d.e.f ) ;

f - int

main( ){

struct book{

char n[20] ; int nop ; float pr ;} ;struct book b = { ”Basic”, 425, 135.00 } ;display ( b.n, b.nop,b.pr ) ;show ( b.n, &b.nop, &b.pr ) ;}

display ( char *n, int pg, float p ){

printf ( ”%s %d %f”, n, pg, p ) ;}show ( char *n, int *pg, float *p ){

printf ( ”%s %d %f”, n, *pg, *p ) ; }

Passing Structure Elements

bb .n,( * )

main( ){

struct book{

char n[20] ; int nop ; float pr ;} ;struct book b = { ”Basic”, 425, 135.00 } ;display1 ( b ) ; show1 ( &b ) ;

}display1 ( ){

printf ( ”%s %d %f”, }show1 ( ){ printf ( ”%s %d %f”,

}

Passing Structures

struct book bb

bb.n, bb.nop, bb.pr ) ;struct book *bb

bb .nop,bb .pr ) ;

printf ( ”%s %d %f”, bb -> n , bb -> nop,bb -> pr ) ;

( * )( * )

main( ){

struct com {

float r, i ;} ;struct com a

c = add ( a, b ) ;

add ( struct com x, struct com y )

}

Complex Nos.

struct com c ;

x.r + y.r ;x.i + y.i ;

struct com b = { 1.2, 1.7 } ;

printf ( ”%f %f”, c.r, c.i ) ;

struct com add ( struct com, struct com ) ;

= { 2.5, 1.3 } ;

struct com add ( struct com x, struct com y ) {

}

z.i = x.i + y.i ;z.r = x.r + y.r ; struct com z ;

return z ;

Applications of Structures

Database Management Positioning Cursors Receiving ascii and scan codes Displaying characters Printing on printer Mouse Programming Graphics Programming All Disk Operations etc.

Floppy DisksJacketJacket

Write Protect notchWrite Protect notchPlatter ( mylar )Platter ( mylar )

Hub ringHub ring

Read / Write slotRead / Write slot

Retractable metal sheathRetractable metal sheath

Write Protect notchWrite Protect notch

Access to magnetic surface( only when retracted )

Access to magnetic surface( only when retracted )Platter

( mylar )Platter( mylar )

SpindleSpindle

Read / Write HeadRead / Write Head

Head AssemblyHead Assembly

Hard DiskPlatter ( aluminium )Platter ( aluminium )

Sectors

Parts of Platter

of same capacity

Tracks

Specs Of Floppy DisksType

360 KB1.2 MB1.44 MB

Sides222

Trk/side

408080

Sec/Trk

91518

Dia.

5 1/4 ”5 1/4 ”3 1/2 ”

TPI

4896

135

Name

DSDD-D9HD-QD152HD-QD18

Bytes / Sector for any disk = 512

Capacity of D9 disk =

2 * 40 * 9 * 512 / 10242 * 40 * 9 * 512 / 1024360 KB

Logical Organization

Boot SectorBoot

Sector

Side 0, Track 0Side 0, Track 0 Side 1, Track 0Side 1, Track 0

1

18

17

3

2

4567

8

9

10

11

1213 14 15

16

1

18

17

3

2

4567

8

9

10

11

1213 14 15

16

DD

DDDD

D

D

DD

DD D D

F1F1

F1F1F1F1

F1

F1

F1

F2F2

F2 F2 F2F2

F2

F2F2

printf ( ”Enter floppy in drive A, press any key …” ) ;

getch( ) ;absread ( ) ;

main( ){

Reading Boot Sector

0, 1, 0, arr

char arr [ 512 ] ; int i ;

for ( i = 0 ; i < 512 ; i++ ) ”%c”, printf ( arr [ i ] ) ;

1Boot Sector

Side 0, Track 0Side 0, Track 0

#include ”dos.h”

}

Chapter 10

Chapter 10

23

4

1

567

8

9

10

1112

13 14 1516

1718

Boot Parameters

Disk BootstrapProgram

Side 0, Track 0Side 0, Track 0

Contents Of Boot Sector

Description

Boot Parameters

Jump Instruction 3

360 Kb

1.2Mb

1.44Mb

No.of

bytes

MSDOS5.0EB3490

No. of bytes/sector 2 512 512 512No. of sectors/cluster 1 2 1 1No. of sectors in reserved area 2 1 1 1No. of copies of FAT 1 2 2 2Max. no. of root dir. entries 2 112 224 224Total no. of sectors 2 720 2400 2880Media descriptor 1 FD F9 F0 No. of sectors/FAT 2 2 7 9No. of sectors/track 2 9 15 18No. of sides 2 2 2 2No. of hidden sectors 2 0 0 0

System ID 8

Reading Boot SectorNo. of bytesDescription

Jump InstructionSystem IDBytes/sector Sectors/cluster Sectors in reserved areaCopies of FAT Max. root dir. entries Total no. of sectors Media descriptorSectors/FAT Sectors/track Sides Hidden sectors

3821212212222

main( ){

struct boot{

char jump[ 3 ] ;char sysid[ 8 ] ;int bps ;char spc ;. .

} ; struct boot b ;printf ( ”Insert disk,

Press any key ) ;getch( ) ;absread ( 0, 1, 0, &b ) ;. .

} BPBP

DBPDBP

Side 0,Trk 0, Sec1

Side 0,Trk 0, Sec1

char rest[ 482 ] ;

main( ){

struct boot{

char jump[ 3 ] ;char sysid[ 8 ] ;int bps ;char spc ;. .

} ; struct boot b ; absread ( 0, 1, 0, &b ) ;

printf ( ”%c”, ) ;

# include ”dos.h”

for ( i = 0 ; i <= 2 ; i++ )printf ( ”%X”, ) ;

b.sysid[ i ]for ( i = 0 ; i <= 7 ; i++ )

b.jump[ i ]

printf ( ”Bytes/sector = %d”, b.bps ) ;printf ( ”Sectors/cluster = %d”, b.spc ) ;

}

int i ;

...Cont...Cont

In Generalabsread ( drive no., no. of sectors to read,

sector from where reading should begin, buffer ) ;absread ( 0, 1, 0, &b ) ;

ROM - BIOS DOS

S0, T0, S1

Every sector referred usingside, track, sectorDrive A - 0Drive B - 1Drive C - 128Drive D - 129. . .. . .

LSN 0

LSN 36Every sector referred using LSNDrive A - 0Drive B - 1Drive C - 2Drive D - 3. . .. . .

S0, T1, S1

What Is It? Description

Jump InstructionSystem IDBytes/sector Sectors/cluster Sectors in reserved areaCopies of FAT Max. root dir. entries Total no. of sectors Media descriptorSectors/FAT Sectors/track Sides Hidden sectors

ObtainedValues

TypicalValues

1.44 Mb Disk

EB3490IBM 3.3

512112

2242880

F09

1820

102….

2048001

-240

20487-2008

BP

DBS

Virus

BPBP

DBSDBS

LSN 50LSN 50

# include ”dos.h”

char a[ 512 ] ;printf ( ”Insert infected disk, Press any key” ) ;

absread ( 0, 1, 50, a ) ;0, 1, 0, a ) ;

}

V((

Anti-Viral

main( ){

getch( ) ;

abswrite (

#include ”dos.h”main( ){

char a[ 512 ] ; char ch = ’y’ ;char *names[ ] = { ”O Jerusalem”, ”Yankee Doodle”,

”Robinson Cruso”, ”Eddie Murphy”, ... } ;printf ( ”Insert uninfected disk, Press any key” ) ;getch( ) ;absread ( 0, 1, 0, a ) ;while ( ch = = ’y’ ){

printf ( ”Insert infected disk, Press any key” ) ;getch( ) ;abswrite ( 0, 1, 0, a ) ;printf ( ”Another disk y/n” ) ; ch = getche( ) ; }

}

Better...

DirectoryDirectory

Several entries, each of 32-bytesSeveral entries, each of 32-bytes

FilenameExtensionAttributeReserved for Future use Time Date Starting Cluster number Size

Description Size8 bytes3 bytes1 byte

10 bytes 2 bytes 2 bytes 2 bytes 4 bytes

Directory Sector

# include ”dos.h”main( ){

struct entry{

char n[ 8 ] ; char ext[ 3 ] ;char unused[ 17 ] ;long int size ;} ;

struct entry e ;[ 16 ]printf ( ”Insert disk, Press any key” ) ; getch( ) ;absread ( 0, 1, 19, e ) ; for ( i = 0 ; i <= 15 ; i++ ) {

for ( j = 0 ; j <= 7 ; j++ ) printf ( ”%c”, e[ i ].n[ j ] ) ;

for ( j = 0 ; j <= 2 ; j++ ) printf ( ”%c”, e[ i ].ext[ j ] ) ;

}}

printf ( ”%ld”, e[ i ].size ) ;

Printing Directory

Directory EntryElementFilenameExtensionAttributeReservedTimeDateStarting clus. no.Size

83

Total

110

2224

32

9 Bytes

?

25/01/99

Directory Entry

Bytes

9785

25/01/99

( 1999 - 1980 ) * 51201* 32+

+ 25

= 9728= 32= 25

yr m d

7 Bits 4 Bits 5 Bits

16 + 2 + 1

1

16 + 8 + 1

19 + 1980 1999

25

Why 2 Bytes?

10011 0001 1100100

0010011

0001

11001

Distributionm d

7 Bits 4 Bits 5 Bits

yr

Date

Time

m s

5 Bits 6 Bits 5 Bits

hr

Attribute Byte012347 56

Read only

Hidden

main( ){

struct entrychar n[11] ;char attr ;char rest[20] ;

} ;struct entry e ;

{

[16]printf ( ”Insert disk, PAK” ) ;getch( ) ;absread (

# include ”dos.h”

for ( i = 0 ; i <= 15 ; i++ )0, 1,19, e ) ;

e[ i ].attr = 2 ;abswrite ( 0, 1, 19, e ) ;

}

2

00000010int i ;

Attribute Byte012347 56

Read only

HiddenSystem

Volume LabelSubdirArchive

Unused

A>DirVolume Label is ICITPR1.C 300 02-27-90PR2.C 520 05-23-98AAA.BBB 400 01-01-99. . . . . .. . . . . .

FormatCreate

Tracks &Sectors

Write BP& DBS

AskVolumeLabel

Loading / Saving a FilePR1.C

3 5 8

512 512 476

32 - Byte Ditectory Entry

PR1 C Attr Res T D 3 Size

0 1 2 3 4 75 6 8 9 10 11FFF85

FAT

1500 Bytes

3

5

8

Input / Output In C

printfscanfgetchputchgetsputs

getkeyabsreadabswrite Keywords?

( )( )( )( )

( )( )

( )( )( )

All I/O is done using FunctionsAll I/O is done using Functions

I/O Functions

Console I/O Port I/ODisk I/O

Formatted Unformattedcharintfloatstring

printf( )scanf( )

char - getch( ), getche( ), getchar( ),fgetchar( ), putch( ),putchar( ), fputchar( )

int -float - No Std. Library Function

string - gets( ), puts( )

printf( )printf ( ”format string”, list of variables / constants

/ Expressions ) ;Can containCan contain

Format Specifiers - %c- %d %u %ld %lu %X %x %o %i- %f %lf %Lf- %s

Escape Sequences

\n\t\a

- newline- tab- alert

\r - carriage return\’\”\\\b - backspace

Any other character

3 4 5 6 7 8 9 0 1 2 . .

Formatting Outputmain( ){

int a = 35 ;clrscr( ) ;printf ( ”a = %d”, a ) ;printf ( ”\na = %2d”, a ) ;printf ( ”\na = %6d”, a ) ;printf ( ”\na = %-7d”, a ) ;printf ( ”\na = %1d”, a ) ;

}

ScreenScreen0 1 2a =a =a =a =a =

3 53 5

3 5- - - -3 53 5

- - - - -

%-35s%20s%7lu%5c%15ld%10u

-

1 1 1

main( ){

float a = 35.6927 ;clrscr( ) ;printf ( ”a = %f”, a ) ;printf ( ”\na = %7.4f”, a ) ;printf ( ”\na = %8.2f”, a ) ;printf ( ”\na = %-7.1f”, a ) ;printf ( ”\na = %1.1f”, a ) ;

}

ScreenScreen

a =a =a =a =a =

3 5 . 6 9 2 73 5 . 6 9 2 7

3 5 . 6 9- - -3 5 . 73 5 . 7

- - -

0 0

Formatting Output

%-15.3Lf%10.2lf

0 1 21

3 4 5 6 78 9 0 1

main( ){

clrscr( ) ;printf ( ”Hello\b\bHi” ) ;

ScreenScreen

printf ( ”\nHello\nHi” ) ;

Hello

printf ( ”\nHello\rHi” ) ;

Hi

printf ( ”He said ”Let us go ”. ” ) ;\ \printf ( ”\n// ” ) ;\\\\

He said ”Let us go”.// \\

}

Escape Sequences

printf ( ”\nHello\tHi” ) ;

Hello HiHelloHelloHelHi

HelloHelloHillo

Hello Hiprintf ( ”\nHello\tHi” ) ;

printf ( ”\nHello\t\tHi” ) ;Hello Hi

8 8

What’s The Difference

\n - New Line\r - Carriage Return

ch = getch( ) ;printf ( ”%d”, ch ) ; 13 10

main( ){

}

char ch ; 13

printf ( ”%d %d”, ’\r’, ’\n’ ) ;

Enter

printf ( ”Format String”, variables ) ;

Format SpecifiersEscape SequenceAny Other Chars

optional

VariablesConstantsExpressions

scanf ( ”Format String”, List of variables ) ;

compulsoryFormat Specifiersonly

float a ;scanf ( ”%10.2f”, &a ) ;

Acceptable, but rarely used

printf ( ”Delete all files Y/N” ) ;ch = getchar( ) ; /* or ch = fgetchar( ) ; */putch ( ch ) ;putchar ( ch ) ;fputchar ( ch ) ;

}

Unformatted Console I/O Functionsmain( ){

printf ( ”Press any key” ) ;getch( ) ;printf ( ”Another disk Y/N” ) ;ch = getche( ) ;

same

char ch ;

Peculiarities

getch( ) - Doesn’t wait for enter.

getche( ) - Echoes character.

getchar( ) - Waits for enter. Macro.

fgetchar( ) - Waits for enter. Function.

High Level / Std Disk I/O Low Level

Disk I/O

Formatted Unformatted

charintfloatstring

fprintf( )fscanf( )

char - getc ( ), fgetc( )putc ( ), fputc( )

int -float - No Std. Library Function

string - fgets( ), fputs( )

Text Binary

Reads / Writes char by char

Reads / Writes line by line

file

Memory

Buffer

CH1PR1.C

Disk

Bufferred I/O

# include ”stdio.h”Displaying File Contents

fopen ( ) ;

printf ( ”Enter file name” ) ;gets ( fname ) ;

char fname[13] ;

main( ){

char ch ;FILE *fp ;

printf ( ”%c”, ch ) ;

fname, ”r”fp =

ch = getc ( ) ;

while ( 1 ){

if ( ch == EOF )break ;

}fclose ( ) ;

}

fp

fp

typedef

struct employee{ ___} ;struct employee e1, e2 ;

struct a{ __

char *p ;} ;typedef struct a FILE ;

unsigned long int i, j ; typedef unsigned long int uli ;uli i, j ;

struct employee{ ___} ;typedef struct employee emp ;emp e1, e2 ;

FILE *fp ;

# include ”stdio.h”

fopen ( ) ;

printf ( ”Enter file name” ) ;gets ( fname ) ;

char fname[13] ;

main( ){

char ch ;FILE *fp ;

printf ( ”%c”, ch ) ;

fname, ”r”fp =

ch = getc ( ) ;

while ( 1 ){

if ( ch == EOF )break ;

}fclose ( ) ;

}

fp

fp

A Fresh Look

Buffer

40

fp p40

fp -> p = fp -> p + 1 ;

Tips

fopen( ) - Standard Library Function to open the file.

fopen ( fname, ”r” ) ; - Returns NULL if file not found.

Every file ends with a char with ascii value 26.

EOF is a macro.

# define EOF -1

FILE is a structure defined in stdio.h

getc( ) reads char & also shifts pointer to next char.

Copying Files

ft = fopen ( target, ”w” ) ;

# include ”stdio.h”

fopen ( ) ;

printf ( ”Enter source & target file names” ) ;gets ( fname ) ;

char fname[13] , target[13] ;

main( ){

char ch ;FILE *fs, *ft ;

putc ( ) ;

fname, ”r”fs =

ch = getc ( ) ;

while ( 1 ){

if ( ch == EOF )break ;

}fclose ( ) ;

fs

fs fclose ( ft ) ;

gets ( target ) ;

ch, ft

}

Filecopymain( ){

char source[67], target[67] ;FILE *fs, *ft ;printf ( ”Enter source file name” ) ;gets ( source ) ;printf ( ”Enter target file name” ) ;gets ( target ) ;fs = fopen ( source, ”r” ) ;if ( fs == NULL ){

printf ( ”Can’t open source file” ) ;exit( ) ;

}ft = fopen ( target, ”w” ) ;if ( ft == NULL ){

printf ( ”Can’t open target file” ) ;exit( ) ;} fclose ( fs ) ;

while ( 1 ){

ch = getc ( fs ) ;if ( ch == EOF )

break ;putc ( ch, ft ) ;

}fclose ( fs ) ;fclose ( ft ) ;

}

# include ”stdio.h”

while ( ch = getc ( fs ) != EOF ) putc ( ch, ft ) ;( )

Tips

Maximum path length = 66

fs = fopen ( s, ”r” ) - Returns NULL if file is absent- Returns address of structure, if present

ft = fopen ( t, ”w” ) - Creates new file if file is absent- Overwrites file, if present

fclose( ) - closes the file and adds EOF at the end, if opened for writing

Coding/Decodingmain( ){

char s[67], t[67 ] ;

FILE *fs, *ft ;

printf ( ”Enter source” ) ;gets ( s ) ;printf ( ”Enter target” ) ;gets ( t ) ;fs = fopen ( s, ”r” ) ;if ( fs == NULL ){

printf ( ”Unable to open” ) ;exit( ) ;

}ft = fopen ( t, ”w” ) ;if ( ft == NULL ){

printf ( ”Unable to open” ) ;exit( ) ;} fclose ( s ) ;

# include ”stdio.h”

char ch ;puts ( ”Encrypt / Decrypt

E/D” ) ;ch = getche( ) ;switch ( ch ){

case ’E’ :case ’e’ :

encrypt( ) ;break ;

case ’D’ :case ’d’ :

decrypt( ) ;break ;

}fclose ( fs ) ;fclose ( ft ) ;remove ( s ) ;

}

Offset Cipherencrypt( ){

char ch ;while ( ( ch = getc ( fs ) ) != EOF )

putc ( ch + 128, ft ) ;}

decrypt( ){

int ch ;while ( ( ch = getc ( fs ) ) != EOF )

putc ( ch - 128, ft ) ;}

I am at Nagpur

J bn bu Obhqvs

Graphic CharactersGraphic Characters

Substitution Cipherencrypt( ){

char str1[ ] = ”Z a A 3 4 n M ….” ;char str2[ ] = ”N j J x 8 9 0 M ….” ;char ch ; int i ;while ( ( ch = getc ( fs ) ) != EOF ){

for ( i = 0 ; i < strlen ( str1 ) ; i++ ){

if ( ch == str1[ i ] ){

putc ( str2[ i ], ft ) ;break ;

}} }

}

I am at Nagpur

main( ){

char s[67], t[67 ] ;

# define NOTBLANK 1# define BLANK 0

Remove Blank Lines

FILE *fs, *ft ;int a ;

char str[80] ;

puts ( ”Enter source & target” ) ;gets ( s ) ; gets ( t ) ;fs = fopen ( s, ”r” ) ; ft = fopen ( t, ”w” ) ;while ( fgets ( ) )

a = isblank ( str ) ;{

if ( a == NOTBLANK )fputs ( ) ;}

fclose ( fs ) ; fclose ( ft ) ;remove ( s ) ; rename ( t, s ) ;

} Contd...Contd...

str, 79, fs

str, ft

...Contd...Contd

isblank ( char *p ){

while ( *p != ’\0’ ){

if (return ( NOTBLANK ) ;

elsep++ ;}

}return ( BLANK ) ;

*p != ’ ’ && *p != ’\t’ && *p != ’\n’ )

Handling Recordsmain( ){

# include ”stdio.h”

struct employee{

char n[20] ; int a ; float s ;} ;struct employee e ;FILE *fp ;fp = fopen ( ”emp.dat”, ”w” ) ;while ( ch == ’y’ ){

puts ( ”Enter record” ) ;scanf ( ”%s %d %f”, e.n, &e.a, &e.s ) ;fprintf (puts ( ”Add another y/n” ) ;

Cont...

}fclose ( fp ) ;

ch = getche( ) ;

char ch = ’y’ ;

fp, ”%s %d %f \n”, e.n, e.a, e.s ) ;

while ( )fscanf (

...Cont

printf ( ”\n %s%d%f”, e.n, e.a, e.s ) ;

fclose ( fp ) ;}

fp = fopen ( ”emp.dat”, ”r” ) ;!= EOFfp,”%s%d%f ”, e.n, & e.a, & e.s )

Why The Difference

26 bytes

Amol\0401 421 423

23 4500.50

20 bytes 2 bytes 4 bytes

fwrite ( ) ;

while ( fread ( ) )

while ( fscanf ( fp, ”%s%d%f”, e.n, & e.a, & e.s ) != EOF )

fprintf ( fp, ”%s %d %f \n”, e.n, e.a, e.s ) ;

&e, sizeof ( e ), 1, fp

&e, sizeof ( e ), 1, fp != 0

”wb”

”rb”

File Opening Modes”w” ”wt” ”wb”- If file is absent, new file is created- If file is present, existing file is overwritten- Operation - Writing

”rb” ”rt”- If file is absent, returns NULL- If file is present, loads the file into memory and sets pointer pointing to first character in file

- Operation - Reading

Cont...

”ab” ”at”- If file is absent, new file is created- If file is present, loads the file into memory and sets up a pointer beyond last character in file

- Operation - Writing at end

...Cont

”wb+” ”wt+”- If file is absent, new file is created- If file is present, existing file is overwritten- Operation - Reading / Writing

”rb+” ”rt+”- If file is absent, returns NULL- If file is present, loads the file into memory and sets pointer pointing to first character in file

- Operation - Reading / Writing

”ab+” ”at+”- If file is absent, new file is created- If file is present, loads the file into memory and sets up a pointer beyond last character in file

- Operation - Writing at the end / Reading

380 - 396380 - 396

Chapter 11Chapter 11

Delete

Open a file called “WS.EXE”

Skip past first 1701 bytes

Copy rest into TEMP.EXE

Delete WS.EXE

Rename TEMP.EXE to WS.EXE

The Programmain( ){

# include ”stdio.h”

char e[10] ;char s[ ] = { 0xE5, 0x92, 0x0, 0x20, 0x20, 0x20,

0x20, 0x20, 0x20, 0x20 } ;fs = fopen ( ”WS.EXE”, ”rb” ) ;fread ( e, 10, 1, fs ) ;for ( i = 0 ; i <= 9 ; i++ ){ if ( e[ i ] != s[ i ] )

{ printf ( ”File is clean” ) ;fclose ( fs ) ;exit( ) ;}

printf ( ”\a \a Jerusalem virus found” ) ;printf ( ”\n attempting recovery …..” ) ;

Cont..

int i ;FILE *fs ;

}

170

WS.EXE

virus signature ?

while ( ( ch = getc ( fs ) ) != EOF )

..Cont

putc ( ch, ft ) ;

fclose ( fs ) ;fclose ( ft ) ;

}

remove ( ”WS.EXE” ) ;rename ( ”TEMP.EXE”, ”WS.EXE” ) ;

ft = fopen ( ”TEMP.EXE”, ”wb” ) ;fseek ( fs, 1701L, SEEK_SET ) ;

char ch ;FILE *ft ;

Changing Commandsmain( ){

# include ”stdio.h”

FILE *fp ; char ch ;fp = fopen ( ”command.com”, ”rb+” ) ;while ( ( ch = getc ( fp ) ) != EOF ){

if ( ch == ’D’ ){

ch = getc ( fp ) ;if ( ch == ’I’ ){

ch = getc ( fp ) ;if ( ch == ’R’ ){

fseek ( fp, -3L, SEEK_CUR ) ;putc ( ’Y’, fp ) ; putc ( ’P’, fp ) ; putc ( ’K’, fp ) ;fseek ( fp, 0L, SEEK_CUR ) ;}

}}}

}fclose ( fp ) ;

D

fseek ( fp, 02, SEEK_CUR )

IR

Necessary on alteration

Low Level Disk I/O

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

int inif ( argc != 3 ){ puts ( ”Improper Usage !” ) ;

puts ( ”Correct Usage : c> filecopy source target” ) ;exit( ) ;}

open ( ) ;if ( in == -1 ){

puts ( ”Unable to open” ) ;exit( ) ;}

out = open ( argv[2], O_WRONLY | O_BINARY | O_CREAT ) ; Cont..

, out ;

C>filecopy PR1.C NEWPR1.C

argv[1], in = O_RDONLY | O_BINARY

..Cont

if ( out == -1 ){

puts ( ”Unable to open” ) ;close ( in ) ;

}while ( read ( ) )

write ( out, buffer, n ) ;

close ( in ) ;close ( out ) ;

}

exit( ) ;

# include ”fcntl.h”# include ”types.h”# include ”stat.h”

int n ;char buffer[512] ;

( n = ) != 0in, buffer, 512

Interaction with HardwareThrough C

Using Standard Library Functions

Directly programming The Hardware

Calling BIOS / DOS Routines

Steps in Calling BIOS / Dos routine Issue an interrupt Find interrupt number

Push

Pop

Transfer control to BIOS / DOS routine

Restore values from stack back into CPU registers Resume original interrupted activity

Multiply interrupt no. by 4 Pick address of BIOS / DOS routine from IVT

Keyboard 9Disk 19Printer 23Mouse 51VDU 16Timer 8

Setup CPU registers with values required byBIOS /DOS routine being called

Store current CPU register values in stack

Let BIOS / DOS routine get executed Collect values returned by BIOS/ DOS routines into

ordinary variables

CPU Registers

Data RegistersAX - Accumulator BX - BaseCX - CountDX - Data

Segment RegistersCS - Code SegmentDS - Data SegmentES - Extra SegmentSS - Stack Segment

Offset RegistersBP - Base PointerSP - Stack PointerIP - Instruction PointerSI - Source indexDI - Destination index

Flag Registers

AH AL

AX

- AH, Al- BH, BL- CH, CL- DH, DL

Position Cursor

Interrupt no. 16DH - Row no.DL - Column no.AH - Service no.

Structures

z.i z.ch[0] z.ch[1]

main( ){

struct a{

int i ;char ch[2] ;

} ;struct a z ;z.i = 512 ;

printf ( ”%d %d %d”, z.i, z.ch[0], z.ch[1] ) ;printf ( ”%d”, sizeof ( z ) ) ;

}

4

512 G G

Size of a structure is sum of sizes of its elements.

Unions z.i

z.ch[0] z.ch[1]main( ){

union a{

int i ;char ch[2] ;

} ;union a z ;z.i = 512 ;

printf ( ”%d %d %d”, z.i, z.ch[0], z.ch[1] ) ;

printf ( ”%d”, sizeof ( z ) ) ;

}

2

0 2

High Low

00000010 00000000

00000000 00000010

HighLow

512

Binary of 512

Permits access to same memorylocations in more than one way

How Many Bytes

union a{

double d ;float f[2] ;char ch[5] ;} ;

union a z ; z.f[0] z.f[1]

z.ch[0]z.ch[0]

z.d

z.ch[1]z.ch[1]

Size of a union is size of the longest element of the union.

Positioning Cursormain( ){ struct WORDREGS

{int ax, bx, cx, dx, si, di, cflag, flags ;

} ;struct BYTEREGS{

char al, ah, bl, bh, cl, ch, dl, dh ;} ;union REGS{

struct WORDREGS x ;struct BYTEREGS h ;} ;

union REGS i, o ;clrscr( ) ;i.h.dh = 10 ; i.h.dl = 20 ; i.h.ah = 2 ; i.h.bh = 0 ;int86 ( 16, &i, &o ) ;printf ( ”Hi” ) ;

}

gotorc( )main( ){

}

union REGS i, o ;i.h.ah = 6 ; i.h.al = 0 ;

i.h.bh = 7 ;i.h.ch = 0 ;

int86 ( 16, &i, &0 ) ;

printf ( ”Hi” ) ;

}

cls( ) ;gotorc ( 10, 20 ) ;

gotorc ( int r, int c ){

}

union REGS i, o ;i.h.ah = 2 ; i.h.bh = 0 ;i.h.dh = r ; i.h.dl = c ;int86 ( 16, &i, &0 ) ;

cls( ){

i.h.cl = 0 ;i.h.dh = 24 ; i.h.dl = 79 ;

# include ”dos.h”

VDU Page no.

Lines to scroll, 0 to clear

Filler Attribute

B/g F/g

Color Byte

Intensitybit

Blinkingbit

R G BR G B

Delete Filesmain( ){

union REGS i, o ;

# include ”dos.h”

char fname[67] ;printf ( ”Enter file name” ) ;gets ( fname ) ;i.h.ah = 65 ;i.x.dx = fname ;intdos ( &i, &o ) ;if ( o.x.cflag == 0 )

printf ( ”Successful’ ) ;else

printf ( ”Unable to delete” ) ;}

Renaming Filesmain( ){

union REGS i, o ;

# include ”dos.h”

char old[67], new[67] ;puts ( ”Old Name:” ) ;gets ( old ) ;puts ( ”New Name” ) ;gets ( new ) ;i.h.ah = 86 ;i.x.dx = old ;

intdos ( &i, &o ) ;i.x.di = new ;

if ( o.x.cflag == 0 )printf ( ”Successful” ) ;

elseprintf ( ”Unable to rename” ) ;

}

Chapter 17Chapter 17

per = ( m1 + m2 + m3 ) / 3 ;

Arraysmain( ){

int m1, m2, m3, i, per ;[ 10 ]for ( i = 0 ; i <= 9 ; i++ ) {

printf ( ”Enter marks” ) ;scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;

[ i ]printf ( ”%d”, per ) ;[ i ]

}}

No Flexibility

# include ”alloc.h”main( ){

int m1, m2, m3, i, per ;printf ( ”Enter no. of students” ) ;int *p ;

malloc ( ) ;n * 2

{scanf ( ”%d%d%d”, &m1, &m2,

&m3 ) ;per = ( m1 + m2 + m3 ) / 3 ;* p( + i ) = per ;

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

printf ( ”%d”, ) ;*( p + i )}

MemoryMemory

n* 2

p

Dynamic Allocation

p = malloc ( n * 2 ) ;scanf ( ”%d”, &n ) ;

for ( i = 0 ; i < n ; i++ )p = ( int * ) malloc ( n * 2 ) ;

Memory Allocation

Array

Static

Compile Time

malloc( )

Dynamic

Execution Time

Better Still...int *p[ ] ;char ch = ’Y’ ;while ( ch = = ’Y’ ){

scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;

malloc ( ) ;2

ch = getche( ) ;}

p p p

Memory Leaks

55 63 28 45

?

p = malloc ( 2 ) ;= per ;*p*( p + i ) = per ;

printf ( ”Another student y/n” ) ;

p = ( int * ) malloc ( 2 ) ;p[ i ] = ( int * ) malloc ( 2 ) ;per = ( m1 + m2 + m3 ) / 3 ;

Memory Leak?

int *f( ) ;int *j ;

main( ){

} Memory Leaks

j

400j =printf ( ”%d”, *j ) ;

f( ) ;

f( ){

int a = 25 ;return ( a ) ;

}

int * f( )

40025

a

&DanglingPointer

Linked List

55 63 28 45 60400400

750750

900900200

120120

55 63 28 45 60

NULL

NULL

data

node

link

Best...

main( ){

struct node{

int data ;struct node *link ;

} ;

malloc ( ) ;q = ( struct node * ) malloc ( sizeof ( struct node ) ) ;r = s = p data = 55 ;q data = 63 ;r data = 28 ;s data = 45 ;p link = q ; q link = r ; r link = s ; s link = NULL ;

. . .. . .

Cont...

p q r s

55 63 28 45 N

sizeof ( struct node )p = malloc ( sizeof ( struct node ) ) ;

sLinked List

p = ( struct node * ) malloc ( sizeof ( struct node ) ) ;struct node *p, *q, *r, *s ;

# include ”alloc.h”main( ){ ...

...

...

...

..Cont p q r s

55 63 28 45 N

s

t t t

printf ( ”%d %d %d %d”, p data, q data, r data, s data ) ;

printf ( ”%d %d %d”, p data, p link data, p link link data ) ;

t = p ;while ( )t != NULL{

printf ( ”%d”, t data ) ; t = t link ;}

}

# include ”alloc.h”struct node{ int per ; struct node *link ;} ;

main( ){

struct node *p ;

char ch = ’Y’ ; int pp ; p = NULL ; while ( ch == ’Y’ )

scanf ( ”%d %d %d”, &m1, &m2, &m3 ) ;pp = ( m1 + m2 + m3 ) / 3 ;add ( ) ;printf ( ”Another student y/n” ) ;ch = getche( ) ;}

{

}

pp

Most General

How are TSRs Different

Remain inmemory

TriggeredExecution

Terminate butStay Resident

Calling Functionsmain( ){

*pdisplay( ) ;p = display ;( *p )( ) ;

display( )

printf ( ”Hello” ) ;}

One Way

One More Way

( *p )( ) ;void ( *p )( ) ;void display( ) ;

void display( )}

{

Some Definitions

void *p( ) ;void ( *p )( int, float ) ;void ( *p )( int *, char ** ) ;int **( *p )( char **, float * ) ;

void ( *p )( ) ;

Definep is a pointer to a function which accepts a double, an int pointer and a floatpointer and returns a far long int pointer.

p is a pointer to a function which accepts a double, an int pointer and a floatpointer and returns a far long int pointer.long int far *( *p )( double, int *, float * ) ;long int far *( *p )( double, int *, float * ) ;

Prototype of a function p which receivestwo doubles and a float pointer and returns a long double pointer.

Prototype of a function p which receivestwo doubles and a float pointer and returns a long double pointer.

long double * p( double, double, float * ) ;long double * p( double, double, float * ) ;

int *( *p[ 3 ] )( int *, int ** ) int *( *p[ 3 ] )( int *, int ** ) ?

our( )void interrupt our( )

# include ”dos.h”void interrupt ( *prev )( ) ; void interrupt our( ) ;int i ;char far *s = 0xB8000000 ;main( ){

prev = getvect ( 9 ) ;setvect ( 9, our ) ;keep ( 0, 1000 ) ;

}

{for ( i = 0 ; i <= 3999 ; i += 2 ){

if ( *( s + i ) >= 65 && *( s + i ) <= 90 )*( s + i ) += 32 ;

else{

if ( *( s + i ) >= 97 && *( s + i ) <= 122 )*( s + i ) = *( s + i ) - 32 ;

}}

}( *prev )( ) ;

IVT

ourBIOS X

Y

36 X Y

KB-INT 9

TheFirst

TSR

# include ”dos.h”void interrupt( *prev )( ) ; void interrupt our( ) ;

int i, color, count ; char far *s = 0xB800000 ;main( ){ prev = getvect ( 8 ) ;

setvect ( 8, our ) ;keep ( 0, 1000 ) ;

void interrupt our( )}

{

i = 1 ; i <= 3999 ; i += 2 ){

*( s + i ) =

if ( color > 255 )color = 0 ;

}

}( *prev )( ) ;

count++ ;if ( count = = 182 )

color ;color++ ;

count = 0 ;

for (

COLOR

Caps Locked# include ”dos.h”void interrupt ( *prev )( ) ;void interrupt our( ) ;

main( ){

prev = getvect ( 9 ) ;setvect ( 9, our ) ;keep ( 0, 1000 ) ;

void interrupt our( )}

{

}

( *prev )( ) ;

char far *kb = 0x417 ;

*kb = 64 ;

012345670101

Caps Lock1 - On2 - Off

# include ”dos.h”void interrupt ( *prev )( ) ;void interrupt our( ) ;main( ){

prev = getvect ( 9 ) ;setvect ( 9, our ) ;keep ( 0, 1000 ) ;

void interrupt our( )}

{

}

( *prev )( ) ;( *prev )( ) ;

How Many Hits

main( ){

prev = getvect ( 9 ) ;setvect ( 9, our ) ;keep ( 0, 1000 ) ;

}

Deactivating ’A’

void interrupt our( ){

}

if ( inportb ( 0x60 ) == 30 ){

outportb ( 0x20, 0x20 ) ;return ;

}else

( *prev )( ) ;

# include ”dos.h”void interrupt ( *prev )( ) ; void interrupt our( ) ;

Expansion Slots

SupportChips

p

Memory BankMath coprocessor

Mother Board

p Mem

Data Bus

PC Under The Hood

01110001

CPU

Microprocessor

Data Bus

AddressBus

Max.Memory

Mode ofoperation

8088 (PC, XT)

8086 (PC, XT)

80286 (AT)

80386 (AT386)

80486 (AT486)

Pentium

8 bits

16 bits

16 bits

32 bits

32 bits

64 bits

20 bits

20 bits

24 bits

32 bits

32 bits

64 bits

1 mb

1 mb

16 mb

4096 mb

4096 mb

244 mb

Real

Real

R/P

R/P

R/P

R/P

Protected Mode

Resources- Memory- Disk Space

Server

Terminal

Terminal

Terminal

Terminal

640 kb

AB0xB8000000

Purpose of Adapter

A 66

A

Display Monitors

Monochrome Monitors - Only Text Composite Monochrome - Text, Graphics, no colors

Composite Color TV Set RGB Monitor -Text, Graphics, Color

VGA Monochrome Monitor - Text, Graphics, No Colors

VGA Color Monitor - Text, Graphics, Colors

Amber

Poor Resolution

No VGA Support

GreenSoft White

MA

Hercules

CGA

EGA

MCGA

VGA

SVGA

XGA

Display AdaptersText

Text &Graphics

TextText - 25 x 80Non Standard

Text - 25 x 80 - colorsGraphics - 320 x 200 - 4 / 16 colors

- 640 x 200 - 2 colorsGraphics - 640 x 350 - 16 / 64 colors

- 320 x 200 - 256 colorsGraphics - 640 x 480 - 2 colors

Graphics - 640 x 480 - 65536 colors

- 1024 x 768 - 16 colors Graphics - 800 x 600 - 16 colors

Graphics - 640 x 480 - 256 colors- 1024 x 768 - 256 colors

Graphics Mode

640 kb

A

B

EGAMCGAVGASVGAXGA

Memory

HerculesCGA

MAHerculesCGAEGAMCGAVGASVGAXGA

Text Mode

640 kb

AB

Memory

Current Trends

VGA + VGA monoSVGA + VGA color

SVGA + Composite MonochromePCAT 486 - 32 mb memory

- 20 mb hard disk

Video Display ModesGraphics ModesText Modes

Why?

Pixels

Scanlines

20086408

CGA - 640 x 200VGA - 640 x 480SVGA - 800 x 600

Resolution

0 639

19925 rows x 80 columns25 rows x 80 columns

Why?

012

Pixels

= 25 rows

= 80 columns

Screen

Text Mode Graphics Mode

•••

••

A

To Draw

# include ”graphics.h”main( ){

int gm, gd = DETECT ;int x ;initgraph (

) ;&gd, &gm,”c: tc bgi”\\\\

for ( ) x = 10 ; x <= 110 ; x++ putpixel ( x, 20, WHITE ) ;

for ( y = 20 ; y <= 120 ; y++ ) putpixel ( 10, y, WHITE ) ;

for ( x = 10, y = 20 ; x <= 110 ; x++, y++ )

putpixel ( x, y, WHITE ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;

}

• •

••

• X

Y

(110, 120)

Brightness

(10, 120)

int y ;

(10, 20)(110, 20)

(0, 0)

Line Drawing(10, 10)

••

(100, 100) (25, 100)(91, 23)

(0, 0)(0, 0)

Ratio 1 : 1 Ratio 4 : 1 Ratio 23 : 91

line ( 10, 10, 100, 100 ) ;line ( 0, 0, 25, 100 ) ;line ( 0, 0, 91, 23 ) ;

Bresenham’sLine drawingAlgorithm

# include ”graphics.h”main( ){

int gm, gd = DETECT ;initgraph ( &gd, &gm, ”c:\\tc\\bgi” ) ;setcolor ( RED ) ;line ( 10, 10, 200, 10 ) ;moveto ( 20, 20 ) ;lineto ( 20, 250 ) ;moverel ( 50, -50 ) ;linerel ( 150, 0 ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;

}

CP

• •

••

• •

5050

150

(20, 250)

( 20, 20)(200,10)(10,10)

(0, 0) •

bar ( 120, 10, 220, 100 ) ;drawpoly ( ) ;ellipse (

) ;

# include ”graphics.h”main( ){

int gm, gd = DETECT ;

initgraph ( &gd, &gm, ”c:\\tc\\bgi” ) ;

x = getmaxx( ) ;

int x ; int y ;int a[ ] = { 300, 100, -, -,

-, -, 300, 100 } ;

y = getmaxy( ) ;setcolor ( RED ) ;rectangle ( 0, 0, x, y ) ; circle ( ) ;80, 275, 60

250, 275, 0, 360,60, 30

arc ( ) ;

400, 275, 90, 180,75

setcolor ( BLUE ) ;

rectangle ( 10, 10, 100, 100 ) ;

6,getch( ) ;closegraph( ) ;restorecrtmode( ) ;

}

Regular Shapes(10,10)

.

. .....

..

.

.

(120,10)

(100,100) (220,100)(300,100)

60 75.30 60(250,275)(80,275)

(400,275)

a

setlinestyle (

) ;

# include ”graphics.h”main( ){

int gm, gd = DETECT ;initgraph ( &gd, &gm,

”c:\\tc\\bgi” ) ;

0123

setcolor ( RED ) ;line ( 10, 10, 100, 100 ) ;

struct linesettingtype l ;

getlinesettings ( &l ) ;setlinestyle ( 2, 0, 3 ) ;line ( 10, 20, 100, 20 ) ;setlinestyle ( 4, , 3 ) ;0xFE7Fline ( 10, 30, 100, 30 ) ;

l.linestyle,l.upattern,l.thickness

line ( 10, 40, 100, 40 ) ; restorecrtmode( ) ;}

struct linesettingtype{

int linestyle ;unsigned upattern ;int thickness ;

}

getch( ) ; closegraph( ) ;

1111 1110 0111 1111F E 7 F

# include ”graphics.h”main( ){

int gm, gd = DETECT ;

initgraph ( &gd, &gm, ”c:\\tc\\bgi” ) ;int a[ ] = { 300, 100, 400, 150, 400, 50, 300, 100 } ;

setfillstyle ( 4, BLUE ) ; setcolor ( RED ) ;fillellipse ( 100, 100, 50, 25 ) ;setfillstyle ( 5, BLUE ) ;fillpoly ( a, 4 ) ;

}

setcolor ( RED ) ;circle ( 100, 180, 50 ) ;circle ( 100, 250, 50 ) ;setfillstyle ( 4, GREEN ) ;floodfill ( 100, 210, RED ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;

Hello

settextjustify ( ) ;

# include ”graphics.h”main( ){

int gm, gd = DETECT ;initgraph ( &gd, &gm, ”c:\\tc\\bgi” ) ;

CENTER_TEXT, BOTTOM_TEXTsettextstyle ( ) ; 2, 0, 5outtextxy ( 100, 150, ”Hello” ) ;setcolor ( RED ) ;line ( 100 - 3, 150, 100 + 3, 150 ) ;line ( 100 , 150 - 3, 100, 150 + 3 ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;

}

outtextxy ( 10, 10, ”Hello” ) ;

.Hello

.

Point would be at thecenter and below text