14648_C-Language (All Concepts)

129
 C Programming Basics C Programming Basics  Introduction to C  Data types in C  Variables  Type conversions  Standard input/output  Arithmetic relational logical operators  !eader "les and libraries  #oops and decisions  Scope o$ variables  Strings  %unctions call by value call by re$erence  Arrays  Structures  &nions  Pointers  %iles

Transcript of 14648_C-Language (All Concepts)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 1/129

 

C Programming BasicsC Programming Basics• Introduction to C

• Data types in C• Variables• Type conversions• Standard input/output• Arithmetic relational logical operators• !eader "les and libraries• #oops and decisions• Scope o$ variables• Strings

• %unctions call by value call by re$erence• Arrays• Structures• &nions

• Pointers• %iles

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 2/129

 

!istory o$ C'#anguage!istory o$ C'#anguage Developed by Dennis ()*itchie and BrianDeveloped by Dennis ()*itchie and Brian

+ernighan o$ AT,T Bell #abs in -.0+ernighan o$ AT,T Bell #abs in -.0 In -.12 the American 3ational StandardsIn -.12 the American 3ational Standards

Institute began the standardisation processInstitute began the standardisation process

In -.1. the International StandardsIn -.1. the International Standards4rganisation continued the standardisation4rganisation continued the standardisationprocessprocess

In -..5 a standard 6as "nalised 7no6n simplyIn -..5 a standard 6as "nalised 7no6n simplyas 8Standard C9as 8Standard C9

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 3/129

 

:hy teach C;:hy teach C; C isC is smallsmall <only 20 7ey6ords=)<only 20 7ey6ords=)

C isC is commoncommon <lots o$ C code about=)<lots o$ C code about=) C isC is stablestable <the language doesn>t change much=)<the language doesn>t change much=) C isC is quick runningquick running)) C is theC is the basis for many other languagesbasis for many other languages <?ava C@@<?ava C@@

a67 Perl=)a67 Perl=)

It may not $eel li7e it but C is one o$ the easiestIt may not $eel li7e it but C is one o$ the easiestlanguages to learn)languages to learn)

34T 4bviously programmers 6ill "nd this course34T 4bviously programmers 6ill "nd this courseeasier than everyone else) B&T this course is $or non'easier than everyone else) B&T this course is $or non'

programmers) I$ you cannot understand 6hat I sayprogrammers) I$ you cannot understand 6hat I sayplease please as7 me either in the lecture orplease please as7 me either in the lecture ora$ter6ards)a$ter6ards)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 4/129

 

:hy use C;:hy use C;

C is not sa$eC is not sa$e It assumes you 7no6 6hat youEre doingIt assumes you 7no6 6hat youEre doing

It has a lot o$ scope $or bugsIt has a lot o$ scope $or bugs

ItEs a good systems programmingItEs a good systems programminglanguagelanguage 3ot much is hidden3ot much is hidden

%aster than ?ava more predictable%aster than ?ava more predictableper$ormanceper$ormance

It has all the lo6'level operationsIt has all the lo6'level operations

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 5/129

 

Strengths:

C-Language

Weaknesses:

1. Efficiency2. Portability

3. Power 

4. Flexibility

5. Standard library

6. Integration with UI!

1. " #rogra$% can be error&#rone

2. " #rogra$% can be diffic'lt to 'nder%tand

3. " #rogra$% can be diffic'lt to $odify

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 6/129

 

 The Bene"ts And Pit$alls 4$ The Bene"ts And Pit$alls 4$CC

BeneftsBenefts

It>s a po6er$ul language <doesn>t restrictIt>s a po6er$ul language <doesn>t restrictyou=you=

%ast%ast

A practical language <real applications=A practical language <real applications=

PitallsPitalls

It>s a po6er$ul language <3o programmerIt>s a po6er$ul language <3o programmer

$ail'sa$es=$ail'sa$es= Compiled code is not portableCompiled code is not portable

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 7/129

 

Structured ProgrammingStructured Programming

C Pascal %ortran areC Pascal %ortran are procedural procedural programmingprogramminglanguages)languages) A program in a procedural language is a list o$A program in a procedural language is a list o$

instructions augmented 6ith loops and branches)instructions augmented 6ith loops and branches) %or small programs no other organiFational principle%or small programs no other organiFational principle

<paradigm= is needed)<paradigm= is needed) #arger programs are bro7en do6n into smaller units)#arger programs are bro7en do6n into smaller units) A procedural program is divided intoA procedural program is divided into functionsfunctions such such

that ideally each has clearly de"ned purpose andthat ideally each has clearly de"ned purpose andinter$ace to other $unctions)inter$ace to other $unctions)

 The idea o$ brea7ing a program into $unctions can be The idea o$ brea7ing a program into $unctions can be$urther eGtended by grouping $unctions that per$orm$urther eGtended by grouping $unctions that per$ormsimilar tas7s intosimilar tas7s into modulesmodules))

Dividing a program into $unctions and modules is theDividing a program into $unctions and modules is the

7ey idea o$7ey idea o$ structured programmingstructured programming))

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 8/129

 

Compiling and Linking

1. Preprocessing. (he #rogra$ i% fir%t gi)en to a #re#roce%%or*which obey% co$$and% that begin with + ,-nown a% directives.

#include <stdio.h> ( incl'de the info in /stdio.h> before co$#iling

test.c  &&&0 ,co$#iled &&&0 test.obj   ,lin-ed &&&0 executable file

2. Compiling. (he $odified #rogra$ now goe% to a co$#iler*which tran%late% it into $achine in%tr'ction% ,object code.

3. Linking. lin-er co$bine% the obect code #rod'ced by the

co$#iler with any additional code needed to yield a co$#lete

exec'table #rogra$.

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 9/129

 

Some programmer HargonSome programmer Hargon

Source code:Source code: The stu you type into the computer) The The stu you type into the computer) Theprogram you are 6riting)program you are 6riting)

Compile (build):Compile (build): Ta7ing source code and ma7ing a Ta7ing source code and ma7ing aprogram that the computer can understand)program that the computer can understand)

Executable:Executable: The compiled program that the computer The compiled program that the computercan run)can run)

Language:Language: <Special sense= The core part o$ C central to<Special sense= The core part o$ C central to6riting C code)6riting C code)

Library:Library: Added $unctions $or C programming 6hich areAdded $unctions $or C programming 6hich arebolted on to do certain tas7s)bolted on to do certain tas7s)

Header fle:Header fle: %iles ending in )h 6hich are included at the%iles ending in )h 6hich are included at thestart o$ source code)start o$ source code)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 10/129

 

ContdJ)ContdJ)

Compiler:Compiler: Translates program 6ritten in source Translates program 6ritten in source

language to target languagelanguage to target language

nterpreter:nterpreter: Translate and immediately eGecute Translate and immediately eGecute

!ssembler:!ssembler:

 Translate into machine language $or Translate into machine language $orparticular machineparticular machine

"acro Processor:"acro Processor:

 TeGtual substitutions TeGtual substitutions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 11/129

 

Keywords

In Standard "* the keywords in (able 2.1 ha)e %#ecial %ignificance

to the co$#iler and therefore can not be '%ed a% identifiers.

a!le ".1 - Keywords

a'to do'ble int %tr'ct

 brea- el%e long %witch

ca%e en'$ regi%ter ty#edef  

char extern ret'rn 'nion

con%t float %hort 'n%ignedcontin'e for %igned )oid

defa'lt goto %ieof )olatile

do if %tatic while

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 12/129

 

 The %ormat o$ C The %ormat o$ C Statements are terminated 6ith semicolonsStatements are terminated 6ith semicolons

Indentation is ignored by the compilerIndentation is ignored by the compiler

C is case sensitive ' all 7ey6ords andC is case sensitive ' all 7ey6ords andStandard #ibrary $unctions are lo6ercaseStandard #ibrary $unctions are lo6ercase

Strings are placed in double KuotesStrings are placed in double Kuotes 3e6lines are handled via Ln3e6lines are handled via Ln

Programs are capable o$ Magging success orPrograms are capable o$ Magging success or

error those $orgetting to do so have one orerror those $orgetting to do so have one orother chosenother chosen randomlyNrandomlyN

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 13/129

 

VariablesVariables Variables must be declared be$ore useVariables must be declared be$ore use

immediately a$ter 8O9immediately a$ter 8O9

Valid characters are letters digits and 89Valid characters are letters digits and 89

%irst character cannot be a digit%irst character cannot be a digit

2- characters recognised $or local variables2- characters recognised $or local variables<more can be used but are ignored=<more can be used but are ignored=

Some implementations recognise only QSome implementations recognise only Qcharacters in global variables <and $unctioncharacters in global variables <and $unction

names=Nnames=N &pper and lo6er case letters are distinct&pper and lo6er case letters are distinct

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 14/129

 

 printf printf andand scanfscanf printfprintf writeswrites integer values to screeninteger values to screen

6hen Ri is used6hen Ri is used

scanfscanf readsreads integer values $rom theinteger values $rom the

7eyboard 6hen Ri is used7eyboard 6hen Ri is used

88,9 V* important 6ith,9 V* important 6ith scanfscanf <reKuired to<reKuired to changechange the parameter thisthe parameter this

6ill be investigated later= ' absence 6ill6ill be investigated later= ' absence 6ill

ma7e program very illma7e program very ill

88,9 not necessary 6ith,9 not necessary 6ith printfprintf becausebecause

current value o$ parameter is usedcurrent value o$ parameter is used

h i S 4$ C

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 15/129

 

 The Basic Structure 4$ A C The Basic Structure 4$ A CProgramProgram

example_program.c

int

$ain ,

Global variables

Local variables

/* Program documentation */

#Preprocessor directives

Function prototypes

Function definitions

Global constants

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 16/129

 

!ello :orld Program!ello :orld Program

#include <stdio.! // input"output library#include <stdio.! // input"output libraryint main$int main$   // function main  // function main

%%

  printf&'ello (orld)n&$ // send string to standard outputprintf&'ello (orld)n&$ // send string to standard output

  return +return +

,,

Compile the source "le hello6orld)c 6ith the commandCompile the source "le hello6orld)c 6ith the commandgcc #ello$orld%c &o #ello$orldgcc #ello$orld%c &o #ello$orld 

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 17/129

 

!ello :orld Program!ello :orld Program

#include <stdio.!#include <stdio.!

includes the standard I/4 library 6hich allo6s you to read $romincludes the standard I/4 library 6hich allo6s you to read $romthe 7eyboard <standard in= and 6rite to the screen <standardthe 7eyboard <standard in= and 6rite to the screen <standardout=out=

int main$int main$   declares the main $unction) very C'program must have adeclares the main $unction) very C'program must have a

$unction named main some6here in the code$unction named main some6here in the code% ... ,% ... , -e symbols % and , mar te beginning and end of a bloc of code.-e symbols % and , mar te beginning and end of a bloc of code.

printf&'ello (orld)n&$printf&'ello (orld)n&$

ends output to te screen. -e portion in 0uotes &...& is te formatends output to te screen. -e portion in 0uotes &...& is te formatstrings and describes o1 te data is formatted.strings and describes o1 te data is formatted.

return +return +  This causes the $unction main to return an error code o$ 5 <no This causes the $unction main to return an error code o$ 5 <no

error= to the shell that started the program)error= to the shell that started the program)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 18/129

 

Compilation , #in7ingCompilation , #in7ing

hello6orld)cstdio)h

#include <stdio.!

hello6orld)o

hello6orld

header "le

compiler

lin7er

eGecutable "le

obHect "le

source"le

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 19/129

 

Variable DeclarationVariable Declarationint bint b

double xdouble x

unsigned int aunsigned int a

car ccar c

C is a typed language that means a variableC is a typed language that means a variablehas ahas a

namename

typetype

C standard typesC standard types int double char Moat short long longint double char Moat short long long

doubledouble

unsigned char unsigned short unsigned intunsigned char unsigned short unsigned int

unsigned longunsigned long

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 20/129

 

Primitive Data'TypesPrimitive Data'Types

• integer data'types char short int long unsigned char unsigned short

• Moating point data'types   Moat double long double• character data'type   char

character constants in single Kuotes >a> >Ln>

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 21/129

 

Primitive Data'TypesPrimitive Data'Types

 Type Type #o6#o6 !igh!igh Digits o$Digits o$PrecisionPrecision

BytesBytes

charchar '-01'-01 -0-0 '' --

shortshort '20Q1'20Q1 20Q20Q '' 00

intint ''0-12Q0-12Q

11

0-12Q0-12Q '' 00

longlong ''

0-12Q0-12Q11

0-12Q0-12Q ''

MoatMoat 2)G-52)G-5'21'21 2)G-52)G-52121

doubledouble -)G-5-)G-5'251'251 -)G-5-)G-5251251 -U-U 11

longlong 2)G-52)G-5'.20'.20 2)G-52)G-5.20.20 -.-. -5-5

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 22/129

 

Variable De"nitionsVariable De"nitions

int a

double x 2 3.4

car ans1er 2 5n5

double y2x

• A declaration introduces a variable>s name into aprogram and speci"es its type• A denition is a declaration 6hich also setsasides memory $or that variable <6hich is usually

the case=• In C it is possible to initialiFe a variable at thesame  time it is de"ned in the same 6ay one assigns avalue

  to an already de"ned variable)• Gamples o$ variable de"nitions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 23/129

 

ConstantsConstants• constants can be speci"ed using the preprocessor

  directive de"neeGample  #define P6 7.89834•  the preprocessor replaces the identi"er PI by theteGt

2)--U. throughout the program• the maHor dra6bac7 o$ de"ne is that the data typeo$   the constant is not speci"ed

• the preprocessor merely replaces all occurences o$the

string PI 6ith 2)--U.

C43V3TI43 reserve CAPITA# letters $or constantsand use small ca s $or variables and $unctions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 24/129

 

CommentsComments

• comments are al$ays a good thing to use because• not everyone is as smart as you are and needs mo  eGplanation in order to understand your program• you may not be as smart neGt month 6hen you ha  to change your program

• comments should clari$y your code and eGplain therational behind a group o$ statements

• comment syntaG <C style= /W W//* tis is a comment

1ic can go across multiplelines of code */

 

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 25/129

 

 Type Conversions Type Conversions

double pi27.89

car c25x5

• C is a hard'typed language meaning that eachvariable has a "Ged type that does not change and

6hich determines the possible assignments andapplicable operators

• Some type conversions occur automatically $or

eGample int to Moat or Moat to double but also char tointint i 2 8:

float x 2 i /* assigns 8: to x */

int ; 2 float y 2 i/; /* assigns 8:/ 2 = to y not =.3 */• Type conversions can be $orced by a programmerthrougha type castfloat > 2 float$ i / ; /* casts i into float before division */

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 26/129

 

#ibrary %unctions#ibrary %unctions• (any $unctionalities in C are carried out by library

functions)• These $unctions per$orm "le access data conversionand  mathematical computations)

#include <mat.! /* include eader file for mat functions */

int main$

%

  double x

  double y

  y28.3:

  x2siny$

,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 27/129

 

!eader %iles!eader %iles• a header "le contains the declaration o$ $unctions  you 6ant to use in your code• the preprocessor directive include ta7es care o$   incorporating a header "le into your source "le• eGample

#include <mat.!

#include &myprog.&• the brac7ets XY indicate that the compiler "rstsearches  the standard include directory 6hich contains the

  standard C header "les "rst• the Kuotation mar7s indicate that the compiler "rstsearches  $or header "les in the local directory• i$ you do not include the appropriate header "le

  you get an error message $rom the compiler

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 28/129

 

!eader and #ibrary %iles!eader and #ibrary %iles

myprog)cmath)h

myprog)h

#include <mat.!

#include &myprog.&

myprog)o

myprog

libm)a

user header "le

compiler

lin7er

library header "le

library "leobHect "le

eGecutable "le

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 29/129

 

Input / 4utputInput / 4utput/WProgram $or print the dierent data typesW//WProgram $or print the dierent data typesW/

#include <stdio.!#include <stdio.!int main$int main$

%%

  int aint a

  double xdouble x

  car ccar c  printf?@nter integerA&$printf?@nter integerA&$

  scanf?Bd&CDa$scanf?Bd&CDa$

printf?)n@nter doubleA&$printf?)n@nter doubleA&$

  scanf?Blf&CDx$scanf?Blf&CDx$

  printf?)n@nter caracterA&$printf?)n@nter caracterA&$

  scanf?Bc&CDc$scanf?Bc&CDc$

  printf?)n-e value of a is BdC of x is BlfC of c is Bc)n&CaCxCc$printf?)n-e value of a is BdC of x is BlfC of c is Bc)n&CaCxCc$

,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 30/129

 

Input / 4utputInput / 4utput

• A stream is an abstraction that re$ers to a Mo6 o$ data)

standardoutput

device

stdout variable aprint$<9Rd9a=Z

standardinput

device

stdin variable ascan$<9Rd9,a=Z

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 31/129

 

nput ' utputnput ' utput

print$ allo6s you to send output to standard outprint$ allo6s you to send output to standard out<screen=<screen=

 The special character 8Ln9 represents carriage return The special character 8Ln9 represents carriage returnline $eedline $eed

 The symbol Rd is a placeholder $or an integer The symbol Rd is a placeholder $or an integervariable in the $ormat stringvariable in the $ormat string

  printf?te value of a is Bd)n&Ca$printf?te value of a is Bd)n&Ca$  that 6ill be replaced by the value o$ the variable athat 6ill be replaced by the value o$ the variable a

6hen the print$ statement is eGecuted6hen the print$ statement is eGecuted PlaceholdersPlaceholders

integer Rdinteger Rd

long Rldlong Rld Moat R$ Moat R$ 

double Rl$ double Rl$ 

char Rcchar Rc

string Rsstring Rs

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 32/129

 

nput ' utputnput ' utput

scan$ allo6s you to read input $romscan$ allo6s you to read input $rom

standard in <7eyboard=standard in <7eyboard= scan$ uses the same placeholders as print$ scan$ uses the same placeholders as print$ 

scanf ?Bd&CDa$scanf ?Bd&CDa$

  the program reads an integer value $romthe program reads an integer value $romthe 7eyboard and places its value into thethe 7eyboard and places its value into the

integer variable ainteger variable a

3otice to put an , in $ront o$ the variable3otice to put an , in $ront o$ the variable

the reason becomes clear 6hen you learnthe reason becomes clear 6hen you learnmore about pointersmore about pointers

i # i d

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 33/129

 

!rit#metic and ncrement!rit#metic and ncrement

peratorsperatorsint a29int a29

int b27int b27

b2bEab2bEa

bE27 /* aritmetic assignment operatorCbE27 /* aritmetic assignment operatorCsame as b2bE7 */same as b2bE7 */

aEE /* increment operatorC same as a2aE8aEE /* increment operatorC same as a2aE8

*/*/a2bEEC /* postfix operator */a2bEEC /* postfix operator */

a27 * EEb /* prefix operator */a27 * EEb /* prefix operator */

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 34/129

 

Arithmetic 4peratorsArithmetic 4perators

• multiplication summation subtraction division

int i 2 8/7 /* integer division result + */float x 2 8.+/7 /* floating point division result +.7777 */

int ; 2 : B 7 // modulo operator remainder of :/7• pre"G and post"G'increment operator @@

int i27int ;2:

printf&Bd&C8+ * iEE$ /* outputs 7+C i as value 9 after1ards */

Printf&Bd&C8+ * EE;$ /* outputs =+C ; as value = after1ards */• arithmetic assignment operators

float x2.+xE27.3• is eKuivalent tox2xE7.3

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 35/129

 

*elational 4perators*elational 4perators

In C there is no special boolean type)In C there is no special boolean type)Instead int is used $or boolean eGpressionInstead int is used $or boolean eGpression6ith the convention that 5 is $alse6ith the convention that 5 is $alseeverything else is true)everything else is true)

*elational operators*elational operators Y greaterY greater X lessX less Y[ greater or eKualY[ greater or eKual X[ less or eKualX[ less or eKual

[[ eKual not to be con$used 6ith assignment[[ eKual not to be con$used 6ith assignment[[

N[ not eKualN[ not eKual

 

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 36/129

 

*elational 4perators*elational 4perators

• a relational operator compares t6o values o$ primitive  in data types such as char int Moat• typical relationships are eKual to less than andgreater than

• the result o$ a comparison is either true or $alse 6here5 is  $alse and any value dierent $rom 5 is true• C provides the $ollo6ing relational operators

  X Y [[ N[ X[ Y[• eGample  int x299

  int y28

  x 22 y$ /* false */

  x !2 y$ /* true */

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 37/129

 increment eGpression

test eGpression

initialiFation eGpression

• a loop causes a section o$ the program to be repeated  multiple times 6hile the loop condition remains true• C 7no6s three 7inds o$ loops

• $or loop• 6hile loop• do loop

• the $or loop repeats a code segment a "Ged number o$• the $or statement contains three eGpressions usually  re$ering to the same loop variable separated by semico

#oops#oops

for i2+ i<83 iEE $

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 38/129

 

%or #oop%or #oop

increment eGpressiotest eGpressioninitialiFation eGpression

for i2+ i<83 iEE $

initialiFationeGpression

body o$ loop

increment

eGpression

testeGpression eGit

true

$alse

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 39/129

 

%or #oop%or #oop

#include <stdio.!#include <stdio.!

int main$int main$

%%

  int aint a

  int iint i

  a28a28

  for i2+i<8+iEE$for i2+i<8+iEE$

  %%

  printf? H Bd 2 Bd)n&CiCa$printf? H Bd 2 Bd)n&CiCa$

  a*2a*2

  ,,

,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 40/129

 

%or #oop%or #oopfor i2+ i<8+iEE$for i2+ i<8+iEE$

initiali>ation expression A i2+initiali>ation expression A i2+  the initialiFation statement is called once 6hen thethe initialiFation statement is called once 6hen the

loop "rst starts) It gives the loop variable an initialloop "rst starts) It gives the loop variable an initialvalue)value)

 Test eGpression iX-5Z Test eGpression iX-5Z  the test statement is called each time through thethe test statement is called each time through the

loop the body o$ the loop is eGecuted as long asloop the body o$ the loop is eGecuted as long asthe test statement is truethe test statement is true

Increment eGpression i@@Increment eGpression i@@  The increment eGpression is called at the end o$ The increment eGpression is called at the end o$

the loop and changes the value o$ the loop variablethe loop and changes the value o$ the loop variable

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 41/129

 

%or #oop%or #oop#include <stdio.!#include <stdio.!

int main$int main$%%

  int numberint number

  int iint i

  long factlong fact

  fact28fact28

  printf?@nter numberA&$printf?@nter numberA&$

  scanf?Bd&CDnumber$scanf?Bd&CDnumber$

  for i2number i!+ i""$for i2number i!+ i""$

  fact*2ifact*2i

  printf?Factorial of Bd is Bld)n&CnumberCfact$printf?Factorial of Bd is Bld)n&CnumberCfact$

,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 42/129

 

Indendation and #oop StyleIndendation and #oop Style

I it is good programming practice to indent loopsI tere is some variation of te style used for loops

  1atever style you use do it consistently

for i2+ i<8+ iEE$ /* indent body but not te bracets */

%

  printf&Bd)n&Ci*i$,

for i2+ i<8+ iEE$ /* indent body and bracets */

  %

  printf&Bd)n&Ci*i$  ,

for i2+ i<8+ iEE$ % /* opening bracet after loop statement */

  printf&Bd)n&Ci*i$

  ,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 43/129

 

:hile / Do':hile #oop:hile / Do':hile #oop

1ile a!b$1ile a!b$

%%

JJ

,,

the body o$ the loop is eGecuted as long as the testthe body o$ the loop is eGecuted as long as the teststatement is true <possibly Fero times=statement is true <possibly Fero times=

dodo

%%

JJ

, 1ile a!b$, 1ile a!b$

the body o$ the loop is eGecuted and then repeatedthe body o$ the loop is eGecuted and then repeatedas long as the test statement is true <at least once=as long as the test statement is true <at least once=

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 44/129

 

:hile #oop:hile #oop

test eGpression1ile c 2 5y5 $%

J

,

body o$ loop

testeGpression eGit

true

$alse

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 45/129

 

:hile #oop:hile #oop#include <stdio.!#include <stdio.!

int main$int main$%%

  int numberint number

  int iint i

  long factlong fact  fact28fact28

  printf?@nter numberA&$printf?@nter numberA&$

  scanf?Bd&CDnumber$scanf?Bd&CDnumber$

  i2numberi2number

  1ile i!+$1ile i!+$

  fact*2i""fact*2i""

  printf?Factorial of Bd is Bld)n&CnumberCfact$printf?Factorial of Bd is Bld)n&CnumberCfact$

,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 46/129

 

:hile #oop:hile #oop

• the 6hile loop is used 6hen the number o$ iterations  is un7no6n be$ore the loop is started• the 6hile loop is repeated as long as the test eGpress  remains true

car c25n5

1ile c 2 5y5$

%

  printf&Ko you 1ant to continueA y/n$)n&$

  scanf&Bc&CDc$

,

 

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 47/129

 

Do #oopDo #oop

test eGpressiondo% J ,

1ile c 2 5y5 $

body o$ loop

testeGpression eGit

true

$alse

D :hil #D :hil #

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 48/129

 

Do ' :hile #oopDo ' :hile #oop#include <stdio.!#include <stdio.!

int main$int main$

%%

  J  J

  i2numberi2number

  dodo

  %%

fact*2i""fact*2i""

  , 1ile i!+$ /* do not forget te semicolon */, 1ile i!+$ /* do not forget te semicolon */  printf?Factorial of Bd is Bld)n&CnumberCfact$printf?Factorial of Bd is Bld)n&CnumberCfact$

,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 49/129

 

Do #oopDo #oop

• in the do loop the test eGpression is evaluated at th  end o$ the loop there$ore the body is eGecuted at  least once

car cdo

%

  printf&Ko you 1ant to continueA y/n$)n&$

  scanf&Bc&CDc$,

1ile c 2 5y5$

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 50/129

 

I$ J lse StatementI$ J lse Statement

test eGpressionif x ! 8++$%

J

,

else%

J

,

body o$ i$ 

testeGpression

eGit

true

$alse

body o$ else

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 51/129

 

I$ J lse StatementI$ J lse Statement

• depending on 6hether the test condition is true or $al  either the i$ or the else branch is eGecuted

int x

Printf&@nter a numberA &$canf&Bd&CDx$

if x ! 8++$

  printf&Bd is greater tan 8++)n&Cx$

else

  printf&Bd is smaller or e0ual tan 8++)n&Cx$

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 52/129

 

I$Jlse StatementI$Jlse Statement

#include <stdio.!#include <stdio.!int main$int main$

%%

  int aCbint aCb

  scanf?Bd Bd&CDaCDb$scanf?Bd Bd&CDaCDb$  if a!b$if a!b$

  printf?Bd is larger tan Bd)n&CaCb$printf?Bd is larger tan Bd)n&CaCb$

  elseelse

  if a22b$if a22b$  printf?Bd is e0ual to Bd)n&CaCb$printf?Bd is e0ual to Bd)n&CaCb$

  elseelse

  printf?Bd is smaller tan Bd)n&CaCb$printf?Bd is smaller tan Bd)n&CaCb$

 ,,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 53/129

 

I$Jlse StatementI$Jlse Statementif a!b$if a!b$

%%

JJ

,,

elseelse

%%

JJ

,, the i$ part is eGecuted i$ the test statementthe i$ part is eGecuted i$ the test statement

is true other6ise the else part is eGecuted)is true other6ise the else part is eGecuted)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 54/129

 

3ested I$Jlse Statement3ested I$Jlse Statement

if a!b$if a!b$  %%

  if b!c$if b!c$

  printf?sorted 2 Bd Bd Bd)n&CaCbCc$printf?sorted 2 Bd Bd Bd)n&CaCbCc$

  elseelse

  if a!c$if a!c$

printf?sorted 2 Bd Bd Bd)n&CaCcCb$printf?sorted 2 Bd Bd Bd)n&CaCcCb$

  elseelse

  printf?sorted 2 Bd Bd Bd)n&CcCaCb$printf?sorted 2 Bd Bd Bd)n&CcCaCb$

  ,,

elseelse

%%  if a!c$if a!c$

  printf?sorted 2 Bd Bd Bd)n&CbCaCc$printf?sorted 2 Bd Bd Bd)n&CbCaCc$

  elseelse

  J  J

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 55/129

 

#ogical 4perators#ogical 4perators

• logical and ,,  x !2 3$ DD x <2 83$ /* true if x in 3C83M */• logical or \\  x 22 3$ NN x 22 8+$ /* true if x23 or x28+ */

• logical negation N  x 22 3$ /* true if x is not e0ual to 3 */

 x 2 3 /* is e0uivalent */• conditional operator ; J  XconditionY ; Xtrue eGpressionY X $alse

eGpressionYif alpa < beta$

min 2 alpa

else

min 2 beta2 * *

S it h St t tS6itch Statement

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 56/129

 

S6itch StatementS6itch Statement

variableeKualsconst -

eGit

true

$alse

"rst case body

variableeKuals

const 0

true

$alse

second case body

de$ault body

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 57/129

 

S6itch StatementS6itch Statement• the s6itch statement is used i$ there are more than  t6o alternatives and the decision depends on the val

  o$ the same variable• the s6itch statement can replace a ladder o$ multipl  nested i$))else statements

s1itc<variable!$

%

  case <constant8!A

  J

  brea  case <constant!A

  J

  brea

  default A

  J

,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 58/129

 

S6itch StatementS6itch Statement

car cprintf&@nter your coice a/b/c$ A &$

canf&Bc&CDc$

s1itc c$

%

  case 5a5A  printf&ou piced a)n&$

  brea

  case 5b5A

  printf&ou piced a)n&$

  brea

case 5c5A

  printf&ou piced a)n&$

  brea

  defaultA

  printf&ou piced neiter aCbCc )n&$

 ,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 59/129

 

Scope o$ VariablesScope o$ Variables• a bloc7 is a section o$ code delimited by a pair  o$ brac7ets O J ]

• a declaration introduces a variable into a scope  < a speci"c part o$ program teGt=

• the scope o$ a variable is the bloc7 6ithin 6hich  the variable is declared

• a variable declared outside a $unction is global)

• a declaration o$ a variable in an inner bloc7 canhide  a declaration in an enclosing bloc7 or a globalvariable

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 60/129

 

li$etime o$ outer ivisibility o$ outer i

Scope o$ VariablesScope o$ Variables

int i /* global variable */

int main$

%

  int i27 /* local variable */

  %

  int ;23 /* local variable */

  int i2: /* local i ides outer i */

  printf&Bd)n& i$ /* outputs : */  , /* end of scope of ; and inner i */

 printf&Bd)n& i$ /* outputs 7 */

, /* end of scope of outer i */

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 61/129

 

CharactersCharacters

 Type Type char char 

Characters are small integers <5'Characters are small integers <5'0UU=0UU=

Character constants are integersCharacter constants are integersthat denote correspondingthat denote correspondingcharacterscharacters

–'0','1','A','B','a','b','\n''0','1','A','B','a','b','\n'

ASCII code maps characters toASCII code maps characters tointegersintegers

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 62/129

 

ASCII CodeASCII Code

00   11   22   33   44   55   66   77   88   99

4848 4949 5050 5151 5252 5353 5454 5555 5656 5757

 A  A    BB   CC   DD   EE   FF   GG   HH   II   J J 

6565 6666 6767 6868 6969 7070 7171 7272 7373 7474

aa   b b   cc   d d      ff   !!   ""   ii   ##

9797 9898 9999 100100 101101 102102 103103 104104 105105 106106

 $%&& $%&&'(0)'(0)

BE&BE&'(!)'(!)

*AB*AB'(t)'(t)

 $E+&I$E $E+&I$E'(n)'(n)

,-ACE,-ACE

00 77 99 1010 3232

StringsStrings

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 63/129

 

StringsStrings

String is collection o$ CharactersString is collection o$ Characters

<or = group o$ elements)<or = group o$ elements)

Character arrays that are 3&##Character arrays that are 3&##

terminated)terminated)GampleGample

 char arr^_ [ 8hi9Zchar arr^_ [ 8hi9Z

`̀h>h> `̀i>i> 3&3&####

;;

+M 8M M 7M

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 64/129

 

StringsStrings

 T6o interpretations T6o interpretations Arrays 6hose elements are charactersArrays 6hose elements are characters

Pointers pointing to charactersPointers pointing to characters

Strings are al6ays terminated 6ith a 3&##Strings are al6ays terminated 6ith a 3&##

character <EL5E or 5=character <EL5E or 5=  char a[]=h!""#\n$ %& si!( &%char a[]=h!""#\n$ %& si!( &%

  char& b=)h!""#\n*$char& b=)h!""#\n*$

olleh n n'll

7b

111189189181184 18 8

7,b:1 7,b:2 7,b:3 7,b:4 7,b:5 7,b:6a;8< a;1< a;2< a;3< a;4< a;5< a;6<

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 65/129

 

String InitialiFationString InitialiFation

6nitiali>ation6nitiali>ation

 Q char m[9] = “I like C”;char m[9] = “I like C”;

 Q char m[ ] = “I like C”;char m[ ] = “I like C”;

 Q char m[] = { ‘I’, ‘ ’, ‘l’, ‘i’, ‘k’, ‘e’, ‘ ’,’C’ };char m[] = { ‘I’, ‘ ’, ‘l’, ‘i’, ‘k’, ‘e’, ‘ ’,’C’ };

‘I’ ‘l’ ‘i’ ‘k’ ‘e’ ‘C’ \0

m[0] m[1] m[2] m[3] m[4] m[5] m[] m[!] m["]

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 66/129

 

char #[30] = $c %r&'rammi(' $; )) &k, %re*erre+char #[30] = $c %r&'rammi(' $; )) &k, %re*erre+

char #[30] = {$c %r&'rammi(' $}; )) &k, re+(+a(-char #[30] = {$c %r&'rammi(' $}; )) &k, re+(+a(-

char #[30] = {c %r&'rammi(' }; )) ille'alchar #[30] = {c %r&'rammi(' }; )) ille'alchar #[30] = {c,%,i};char #[30] = {c,%,i};  )) ille'al )) ille'al

char #[30] = {’./,’I/,’I/,’/}; )) &k, i(c&(e(ie(-char #[30] = {’./,’I/,’I/,’/}; )) &k, i(c&(e(ie(-

char #-ri('ar[30];char #-ri('ar[30];   )) &k, (&- i(i-ialie  )) &k, (&- i(i-ialie

char # = “c”; ))#[0]=‘c’,#[1]=‘’,#[2]=‘’, #[3]=0; )) &k, i(i-ialiechar # = “c”; ))#[0]=‘c’,#[1]=‘’,#[2]=‘’, #[3]=0; )) &k, i(i-ialiechar #-r[20] = “I(i-ial ale”; )) &k, i(i-ialiechar #-r[20] = “I(i-ial ale”; )) &k, i(i-ialie

-I ( i i

a l a  \0l e 6

66 6 6 6

7ll charac-er 

String Initialization

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 67/129

 

3ull is the end o$ it3ull is the end o$ it

8i(cl+e cl:h8i(cl+e cl:h

8i(cl+e c&(i&:h8i(cl+e c&(i&:h

8i(cl+e #-+i&:h8i(cl+e #-+i&:h

8i(cl+e #-ri(':h8i(cl+e #-ri(':h

i(- mai(<i(- mai(<

{{

  char >[ ];char >[ ];

  #-rc%?<>,$.(&&%? i# (&- a ca-$;#-rc%?<>,$.(&&%? i# (&- a ca-$;

  >[11] = /\0/;>[11] = /\0/;

  %ri(-*<$> = @#$,>;%ri(-*<$> = @#$,>;

  'e-ch<;'e-ch<;

}}

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 68/129

 

char #[5]=$.II$;char #[5]=$.II$;

char +e%-[5], +=+e%-;char +e%-[5], +=+e%-;

char (ame[20];char (ame[20];

(ame = “(ame = “Ae-er Aa(Ae-er Aa($;$;

#-rc%?<(ame,“#-rc%?<(ame,“Ae-er Aa(Ae-er Aa($;$;

#-rc%?<+e%-,$I$;#-rc%?<+e%-,$I$;%ri(-*<$@# @# @#\($,+,#,+e%-;%ri(-*<$@# @# @#\($,+,#,+e%-;

+ = #-rc%?<#,$BB$;+ = #-rc%?<#,$BB$;

%ri(-*<$@# @# @# @#\($,(ame,+,#,+e%-;%ri(-*<$@# @# @# @#\($,(ame,+,#,+e%-;

char c1[30], c2[30]=“hi# i# (e c1 #-ri('”;char c1[30], c2[30]=“hi# i# (e c1 #-ri('”;

char #[30] = $c %r&'rammi(' $;char #[30] = $c %r&'rammi(' $;

char #-r1[30];char #-r1[30];

char #-r;char #-r;

#-rc%?<c1, c2;#-rc%?<c1, c2;

#-r = #-rca-<#,$i# 'rea-DD$;#-r = #-rca-<#,$i# 'rea-DD$;

#-r1 = #-rca-<#,$i# 'rea-DD$;#-r1 = #-rca-<#,$i# 'rea-DD$;

Rae sure tat you aveRae sure tat you ave

enoug memory space toenoug memory space to

assign te stringC oter1isassign te stringC oter1is

e some cars 1ill be lost.e some cars 1ill be lost.

String Assignment

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 69/129

 

In'Class GampleIn'Class Gample

&i+ mai(<&i+ mai(<

{{ char *ir#-[100], la#-[100];char *ir#-[100], la#-[100];

i(- i;i(- i;

#-rc%?<*ir#-,$Ae-er$;#-rc%?<*ir#-,$Ae-er$;

#%ri(-*<la#-, $Aa($;#%ri(-*<la#-, $Aa($;

  %ri(-*<$m? (ame i# @#, @#\($, la#-, *ir#-;%ri(-*<$m? (ame i# @#, @#\($, la#-, *ir#-;

  *&r <i=0; i5; i*&r <i=0; i5; i

  %ri(-*<$@# \($,la#-;%ri(-*<$@# \($,la#-;

  'e-ch<;'e-ch<;

}}

%unctions%unctions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 70/129

 

%unctions%unctions• a $unction groups a number o$ program statements

  into a unit and gives it a name• the $unction can be invo7ed $rom other parts o$ theprogram• dividing a program into $unctions is one 6ay tostructure  your program <structured programming=• a $unction declaration speci"es the name o$ the$unction  the type o$ the value returned and the number and

  type o$ arguments that must be supplied in a call o$   the $unction• a $unction denition contains the body o$ the $unction• typically $unction declarations ta7e place in header

"les <)h=

:hat is a $unction;:hat is a $unction;

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 71/129

 

:hat is a $unction;:hat is a $unction; The The functionfunction is one o$ the most basicis one o$ the most basic

things to understand in C programming)things to understand in C programming) AA functionfunction is a sub'unit o$ a programis a sub'unit o$ a program

6hich per$orms a speci"c tas7)6hich per$orms a speci"c tas7) :e have already <6ithout 7no6ing it=:e have already <6ithout 7no6ing it=

seen one $unction $rom the C library seen one $unction $rom the C library printf+printf+

:e need to learn to 6rite our o6n:e need to learn to 6rite our o6n$unctions)$unctions)

%unctions ta7e%unctions ta7e argumentsarguments <variables=<variables=and may return anand may return an argument.argument.

 Thin7 o$ a $unction as eGtending the C Thin7 o$ a $unction as eGtending the C

language to a ne6 tas7)language to a ne6 tas7)

An eGample $unctionAn eGample $unction

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 72/129

 

An eGample $unctionAn eGample $unction

Prototy#e the f'nction

"all the f'nction

(he f'nction it%elf 

f'nction header 

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 73/129

 

%actorial program <and thoughts=%actorial program <and thoughts=

int ain-.

/  int nb!r= 4$

  int ans!r$

  int c#nt$

 

ans!r= 1$  c#nt= nb!r$

  hi"! -c#nt = 0. /

  ans!r= ans!r& c#nt$

  c#nt$

 

  printf - = \n,

  nb!r,ans!r.$

  r!trn 0$

nb!r= 4

ans!r= 1c#nt= 4

!nt!r hi"! "##p

ans!r= 1&4=4

c#nt=3

!nt!r hi"! "##p

ans!r=4&3= 12

c#nt=2

!nt!r hi"! "##p

ans!r=12&2= 24

c#nt= 1

!nt!r hi"! "##pans!r= 24&1= 24

c#nt= 0

!nt!r hi"! "##p

ans!r= 24&0= 0

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 74/129

 

%unctions%unctions

int facint n$ /* function declaration */

int x2:

printf&facBd$2Bd)n&CxC facx$$ /* call function fac$*/

int facint n$ /* function definition */

%

  int i

  int result28  for i28 i<2n iEE$

  result*2i

  return result /* exits function and returns value */

,

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 75/129

 

%unctions%unctions

int po1int aC int b$ /* function declaration */

int a27

6nt b29

printf&Bd H Bd 2Bd)n&CaCbCpo1aCb$$ /* call function fac$*/

int po1int aC int b$ /* function definition */

%

  int result28

  int i  for i28 i<2b iEE$

  result*2a

  return result /* exits function and returns value */

,

P*E+SP*E+S

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 76/129

 

Pointers are variables that containPointers are variables that contain memory memory  

addressesaddresses as their values)as their values)

A variable nameA variable name directly directly  re$erences a value)re$erences a value)

A pointerA pointer indirectly indirectly  re$erences a value)re$erences a value)*e$erencing a value through a pointer is called*e$erencing a value through a pointer is calledindirectionindirection))

A pointer variable must be declared be$ore itA pointer variable must be declared be$ore itcan be used)can be used)

P*E+SP*E+S 

P*E+SP*E+S

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 77/129

 

P*E+SP*E+S

A pointer is an address o$ a storageA pointer is an address o$ a storage

locationlocation By convention Fero represents the nullBy convention Fero represents the null

pointerpointer

A pointer is a number and must itsel$ beA pointer is a number and must itsel$ be

storedstored

 The siFe o$ a pointer depends on the The siFe o$ a pointer depends on theamount o$ memory to be addressedamount o$ memory to be addressed

A -Q'bit pointer can address Q+ locationsA -Q'bit pointer can address Q+ locations A 20'bit pointer can address trillionA 20'bit pointer can address trillion

locationslocations

P4I3T*SP4I3T*S

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 78/129

 

P4I3T*SP4I3T*S Gamples o$ pointer declarationsGamples o$ pointer declarations

 intint  ,a ,aZZ MoatMoat ,b,bZZ

 charchar ,c,cZZ

 The The asteris7asteris7 6hen used as above in the 6hen used as above in thedeclaration tells the compiler that the variabledeclaration tells the compiler that the variableis to be a pointer and the type o$ data that theis to be a pointer and the type o$ data that thepointer points to butpointer points to but 34T34T the name o$ thethe name o$ thevariable pointed to)variable pointed to)

PointersPointers

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 79/129

 

PointersPointers

ach variable in a program occupies aach variable in a program occupies apart o$ the computer>s memory $orpart o$ the computer>s memory $oreGample an integer variable occupies 0eGample an integer variable occupies 0bytes o$ memorybytes o$ memory

 The location o$ the piece o$ memory used The location o$ the piece o$ memory usedto store a variable is called the addressto store a variable is called the addresso$ that variableo$ that variable

An address is some 7ind o$ numberAn address is some 7ind o$ number

similar to house numbers in a street thatsimilar to house numbers in a street thatis used to locate the in$ormation stored inis used to locate the in$ormation stored inthat particular variablethat particular variable

P i

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 80/129

 

PointersPointers

Pointers are used toPointers are used to Access array elementsAccess array elements

Passing arguments to $unctions 6hen thePassing arguments to $unctions 6hen the$unction needs to modi$y the original$unction needs to modi$y the originalargumentargument

Passing arrays and strings to $unctionsPassing arrays and strings to $unctions

4btaining memory $rom the system4btaining memory $rom the system

Creating data structures such as lin7edCreating data structures such as lin7edlistslists

& $ , d W& $ , d W

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 81/129

 

&se o$ , and W&se o$ , and W :hen is , used;:hen is , used;

:hen is W used;:hen is W used;

, '' address operator 6hich gives or, '' address operator 6hich gives or

produces the memory address o$ a dataproduces the memory address o$ a datavariablevariable

W '' dere$erencing operator 6hich providesW '' dere$erencing operator 6hich provides

the contents in the memory location speci"edthe contents in the memory location speci"edby a pointerby a pointer

rogram to s6ap t e va ues o t6o var a es nrogram o s6ap e va ues o 6o var a es nmemorymemory

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 82/129

 

includeXstdio)YincludeXstdio)Y

void eGchange<intWintW=void eGchange<intWintW=int main<=int main<=

OO int abZint abZ

p$<8nter values o$ a and b9=Z s$<8RdRd9,a,b=Zp$<8nter values o$ a and b9=Z s$<8RdRd9,a,b=Z

p$<8Be$ore eGchange a[Rd b[Rd9ab=Zp$<8Be$ore eGchange a[Rd b[Rd9ab=Z

eGchange<,a,b=Z p$<8A$ter eGchange a[Rd b[Rd9ab=ZeGchange<,a,b=Z p$<8A$ter eGchange a[Rd b[Rd9ab=Zreturn 5Zreturn 5Z

]]

void eGchange<int Waptr int Wbptr=void eGchange<int Waptr int Wbptr=

OO int tempZint tempZ

temp[WaptrZtemp[WaptrZWaptr[WbptrZWaptr[WbptrZWbptr[tempZWbptr[tempZ

]]

P4I3T* VA*IAB#SP4I3T* VA*IAB#S

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 83/129

 

P4I3T* VA*IAB#SP4I3T* VA*IAB#S A pointer variable is a variable that holds addressA pointer variable is a variable that holds address

valuesvalues

ach data type has its o6n pointer variable pointerach data type has its o6n pointer variable pointertoto intint pointer to pointer to doubledouble pointer to pointer to c#arc#ar J J

C uses theC uses the address-of address-of  operator , to get the addressoperator , to get the addresso$ an variableo$ an variable

C uses theC uses the indirectionindirection oror contents-ofcontents-of operator W tooperator W toaccess the value o$ the variable pointed byaccess the value o$ the variable pointed by

int i28:int i28:

int* ptr /* defines a pointer variable for integer variables */int* ptr /* defines a pointer variable for integer variables */

ptr2 Di /* assign te address of i to pointer */ptr2 Di /* assign te address of i to pointer */

printf&te value of i can be printed as Bd or Bd)n&C *ptrC i$printf&te value of i can be printed as Bd or Bd)n&C *ptrC i$

printf&te address of i is Bd)n&C ptr$printf&te address of i is Bd)n&C ptr$

P i t V i blP i t V i bl

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 84/129

 

Pointer VariablesPointer Variables

5G-5Uint i-int *ptr

ptr2Di

 a d d r e s

 s  o $

printf&value of i 2 Bd)n&C*ptr$

 c o n  t e

 n  t s  o

 $

P i t V i blP i t V i bl

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 85/129

 

Pointer VariablesPointer Variables

int v // defines variable v of type intint v // defines variable v of type int

int 1 // defines variable 1 of type intint 1 // defines variable 1 of type int

int *p // defines variable p of type pointer to intint *p // defines variable p of type pointer to int

p2Dv // assigns address of v to pointer pp2Dv // assigns address of v to pointer p

v27 // assigns value 7 to vv27 // assigns value 7 to v*p2: // assigns value : to v*p2: // assigns value : to v

p2D1 // assigns address of 1 to pointer pp2D1 // assigns address of 1 to pointer p

*p28 // assigns value 8 to 1*p28 // assigns value 8 to 1

&sing the indirection operator Wp to access the&sing the indirection operator Wp to access thecontents o$ a variable is calledcontents o$ a variable is called indirectindirectaddressingaddressing

  oror dereferencingdereferencing the pointerthe pointer

P b V lP b V l

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 86/129

 

Passby'ValuePassby'Value• 6hen passing arguments by value the $unction creat  ne6 local variables to hold the values o$ the variable  argument• the value o$ the original variable are not changed 

void fint val$ /* te parameter val olds a local copy of tevariable argument */

%

  valEE

,

int x29

fx$ /* call function f passing x by value */

printf&x2Bd)n&Cx$ /* x still as te value 9 W/

Pointers as -unction !rgumentsPointers as -unction !rguments

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 87/129

 

gg

C oers t6o dierent 6ays to pass argumentsC oers t6o dierent 6ays to pass argumentsto a $unctionto a $unction

by value void $<int G=Zby value void $<int G=Z

by re$erence void $<intW G=Zby re$erence void $<intW G=Z

In pass'by'value the $unction obtains only aIn pass'by'value the $unction obtains only a

local copy o$ the variable so that changes tolocal copy o$ the variable so that changes tothe local variable have no impact on thethe local variable have no impact on theargument 6ith 6hich the $unction 6as invo7edargument 6ith 6hich the $unction 6as invo7ed

In pass'by're$erence the $unction manipulatesIn pass'by're$erence the $unction manipulatesthe original variable rather than merely itsthe original variable rather than merely itscopycopy

Pass'by'*e$erencePass'by'*e$erence

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 88/129

 

void s6ap< doubleW ptr- doubleW ptr0=void s6ap< doubleW ptr- doubleW ptr0=

OO  double tmp[Wptr-Zdouble tmp[Wptr-Z

  Wptr-[Wptr0Z /W de're$erencing pointer W/Wptr-[Wptr0Z /W de're$erencing pointer W/

  Wptr0[tmpZWptr0[tmpZ

]]

int main<=int main<=OO  double a[2)5Zdouble a[2)5Z

  double b[U)5double b[U)5

  s6ap<,a ,b=Z /W call by re$erence using the addresses o$ as6ap<,a ,b=Z /W call by re$erence using the addresses o$ a

and b W/and b W/  print$<8a[Rl$ b[Rl$Ln9ab=Zprint$<8a[Rl$ b[Rl$Ln9ab=Z

]]

ac or a o a g ven num er us ngac or a o a g ven num er us ngpointersW/pointersW/

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 89/129

 

po e s /p /

main<=main<=

OO int n$actorialZint n$actorialZprint$<8enter a number9=Zprint$<8enter a number9=Z

scan$<8Rd9,n=Zscan$<8Rd9,n=Z

$actcompute<n,$actorial=Z$actcompute<n,$actorial=Z

print$<8the $actorial o$ Rd9n$actorial=Zprint$<8the $actorial o$ Rd9n$actorial=Z

]]$actcompute<ab=$actcompute<ab=

int aWbZint aWbZ

OO

int mZ Wb[-Zint mZ Wb[-Z

$or<m[-ZmX[aZm@@=$or<m[-ZmX[aZm@@=

Wb[WbWmZWb[WbWmZ]]

AArra s

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 90/129

 

ArraysArrays

 The idea o$ an array is to group The idea o$ an array is to groupsimilar obHects into units)similar obHects into units)

Arrays are structures that groupArrays are structures that group

items o$ the same data type)items o$ the same data type) The elements o$ an array are The elements o$ an array are

accessed by an indeG number thataccessed by an indeG number that

allo6s random access)allo6s random access)

AArrays

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 91/129

 

ArraysArrays

int po1eroft1o8+M /*array definition */int po1eroft1o8+M /*array definition */int po1eroft1o+M28 /* first element as index number + */int po1eroft1o+M28 /* first element as index number + */

int iint i

for i28i<8+CiEE$for i28i<8+CiEE$

  po1eroft1oiM2po1eroft1oi"8M*po1eroft1oiM2po1eroft1oi"8M*

for i2+i<8+CiEE$for i2+i<8+CiEE$

  printf? H Bd 2 Bd)n&CiCpo1eroft1oiM$printf? H Bd 2 Bd)n&CiCpo1eroft1oiM$

 

AArrays

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 92/129

 

ArraysArrays

double avgint s>C double arrayM$ /* function definition*/double avgint s>C double arrayM$ /* function definition*/double x3M2%8.C .3C 8.:C 9.C 7.4, /* initiali>e array */double x3M2%8.C .3C 8.:C 9.C 7.4, /* initiali>e array */

printf?average is Blf)n&Cavg3Cx$$printf?average is Blf)n&Cavg3Cx$$

double avgint s>C double arrayM$double avgint s>C double arrayM$%%

int iint i

  double sumdouble sum

  for i2+ i<s> iEE$for i2+ i<s> iEE$  sumE2arrayiMsumE2arrayiM

  return sum/s>return sum/s>

,,

(ulti Dimensional Arra s(ulti Dimensional Arrays

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 93/129

 

(ulti'Dimensional Arrays(ulti'Dimensional Arrays

#define ST( 3#define ST( 3#define UTL #define UTL

double matrixST(MUTLMdouble matrixST(MUTLM

double aUTLMdouble aUTLM

double bST(Mdouble bST(M

int iC;int iC;

fori2+i<ST(CiEE$fori2+i<ST(CiEE$

 %%

  biM2+.+biM2+.+ for;2+;<UTL;EE$for;2+;<UTL;EE$

  biME2matrixiM;M*a;MbiME2matrixiM;M*a;M

,,

/W :rite a c'program to "nd the largest/W :rite a c'program to "nd the largestnumber in an array W/number in an array W/

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 94/129

 

number in an array W/number in an array W/ includeXstdio)hYincludeXstdio)hY

de"ne (ASI -55de"ne (ASI -55

main<=main<=OO

int nImaG[5elements^(ASI_Zint nImaG[5elements^(ASI_Zprint$<8enter the no o$ elements9=Zprint$<8enter the no o$ elements9=Z

scan$<8Rd9,n=Zscan$<8Rd9,n=Z

$or<i[5 iXn i@@=$or<i[5 iXn i@@=OO

print$<8enter value $or element Rd9i=Zprint$<8enter value $or element Rd9i=Z

scan$<Rd9,elements=Zscan$<Rd9,elements=Z

]]

$or<i[5ZiXnZi@@=$or<i[5ZiXnZi@@=OO

i$<maGXelements^i_=i$<maGXelements^i_=

maG[elements^i_ZmaG[elements^i_Z]]

print$<the maGimum is Rd9maG=Zprint$<the maGimum is Rd9maG=Z

]]

Arrays in PointersArrays in Pointers

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 95/129

 

yy Array indeGing is syntactic sugar $or pointersArray indeGing is syntactic sugar $or pointers

a[i]a[i] is treated asis treated as *(a+i)*(a+i)  To Fero out an array To Fero out an array

– for (i = 0; i < size; i++) a[i] = 0;for (i = 0; i < size; i++) a[i] = 0;

– for (i = 0; i < size; i++) *(a+i) = 0;for (i = 0; i < size; i++) *(a+i) = 0;

– for (p = a; P < a+size; p++) *p = 0;for (p = a; P < a+size; p++) *p = 0;

BecauseBecause a[i]a[i] meansmeans *(a+i), i[a]*(a+i), i[a] is eKually legalNis eKually legalN

Pointers and ArraysPointers and Arrays

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 96/129

 

yy  There is a close association bet6een pointers and There is a close association bet6een pointers and

arraysarrays

Arrays can be accessed using pointersArrays can be accessed using pointers

 The name o$ an array is also a constant pointer to the The name o$ an array is also a constant pointer to thedata type o$ the elements stored in the arraydata type o$ the elements stored in the array

int array3M 2 % 7C 3C 8C 79C 8: , /* array of 3 ints */int array3M 2 % 7C 3C 8C 79C 8: , /* array of 3 ints */

for int i2+ i<3 iEE$for int i2+ i<3 iEE$

  printf&Bd)n&CarrayiM$ /* using index to access elements */printf&Bd)n&CarrayiM$ /* using index to access elements */

for int i2+ i< 3 iEE$for int i2+ i< 3 iEE$  printf&Bd)n&C *arrayEi$$ /* using pointer to access elements */printf&Bd)n&C *arrayEi$$ /* using pointer to access elements */

/* te variable array is of type pointer to integer *//* te variable array is of type pointer to integer */

Arrays and StringsArrays and Strings

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 97/129

 

y gy g In C there is no particular type $orIn C there is no particular type $or

strings) Instead strings are stored instrings) Instead strings are stored inarrays o$ type character)arrays o$ type character)

#include <strings.!#include <strings.!

car lastname3M2?'ansen&car lastname3M2?'ansen&car firstname3M2?Tle&car firstname3M2?Tle&

car fullname38Mcar fullname38M

strcpyfullnameCfirstname$strcpyfullnameCfirstname$

strcatfullnameC& ?$strcatfullnameC& ?$strcatfullnameClastname$strcatfullnameClastname$

printf?full name is Bs)n&Cfullname$printf?full name is Bs)n&Cfullname$

StructuresStructures

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 98/129

 

A structure is a collection o$ simple variables that can beA structure is a collection o$ simple variables that can beo$ dierent type)o$ dierent type)

 The data items in a structure are called members o$ the The data items in a structure are called members o$ thestructure)structure)

struct complex /* structure declaration */struct complex /* structure declaration */

%%

double re /* members of te structure */double re /* members of te structure */  double imdouble im

,,

complex multstruct complex aC struct complex b$complex multstruct complex aC struct complex b$

struct complex aCbCc /* variable declaration of type complex */struct complex aCbCc /* variable declaration of type complex */

a.re2.+ /* accessing members of struct complex */a.re2.+ /* accessing members of struct complex */

a.im28.3a.im28.3

b.re2.7b.re2.7

b.im2"8.=b.im2"8.=

c2multaCb$c2multaCb$

C StructuresC Structures

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 99/129

 

Collection o$ related variables under one nameCollection o$ related variables under one name

Derived data typesDerived data types Variables declared 6ithin the braces o$ theVariables declared 6ithin the braces o$ thestructure de"nition are the members o$ thestructure de"nition are the members o$ thestructurestructure

(embers o$ the same structure type must have(embers o$ the same structure type must haveuniKue namesuniKue names

 T6o dierent structure types can contain T6o dierent structure types can containmembers o$ the same name 6ithout conMictmembers o$ the same name 6ithout conMict

struct card Ostruct card O

int $aceZint $aceZ

char suit^05_Zchar suit^05_Z

]Z]Z

struct card aCard dec7^U0_ WcardPtrZstruct card aCard dec7^U0_ WcardPtrZ

StructuresStructures

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 100/129

 

StructuresStructures Structures are collections o$Structures are collections o$

variables o$ dierent types as invariables o$ dierent types as inthe $ollo6ing eGample)the $ollo6ing eGample)

%tr'ct abc

  int a=

  long b=

  char c=

>yStr'ct=

Str'ct're

?efinition

)ariable

declaration

Str'ct're(y#e

 a$e

C Structures and %unctionsC Structures and %unctions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 101/129

 

C Structures and %unctionsC Structures and %unctions

struct point ma7epoint<struct point pt int G int y= Ostruct point ma7epoint<struct point pt int G int y= Opt)G [ GZpt)G [ GZ

pt)y [ yZpt)y [ yZ

return ptZreturn ptZ

]]int main<= Oint main<= O

struct point ptZstruct point ptZ

pt [ ma7epoint <pt U Q=Zpt [ ma7epoint <pt U Q=Z

print$<8pt)G [ Rd pt)y [ RdLn9 pt)G pt)y=Zprint$<8pt)G [ Rd pt)y [ RdLn9 pt)G pt)y=Z]]

C Structures and %unctionsC Structures and %unctions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 102/129

 

C Structures and %unctionsC Structures and %unctions

void ma7epoint<struct point Wpt int G int y= Ovoid ma7epoint<struct point Wpt int G int y= Opt'YG [ GZpt'YG [ GZ

pt'Yy [ yZpt'Yy [ yZ

]]

int main<= Oint main<= Ostruct point ptZstruct point ptZ

ma7epoint <,pt U Q=Zma7epoint <,pt U Q=Z

print$<8pt)G [ Rd pt)y [ RdLn9 pt)G pt)y=Zprint$<8pt)G [ Rd pt)y [ RdLn9 pt)G pt)y=Z

]]

%or very large structures pass the pointer to itN%or very large structures pass the pointer to itN

/WProgram to display the month names o$ both/WProgram to display the month names o$ both

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 103/129

 

datesW/datesW/ Struct mydateStruct mydate

OO int yyyyZint yyyyZ

int mmddZint mmddZ]Z]Z

main<=main<=

OO struct mydate date-date0Zstruct mydate date-date0Z

int month-month0Zint month-month0Z

char Wmonths^_[O8 89Han99$eb99mar9J)9dec9]Zchar Wmonths^_[O8 89Han99$eb99mar9J)9dec9]Zp$<8enter "rst date<mmdd=9=Z s$<8Rd9,date-)mmdd=Zp$<8enter "rst date<mmdd=9=Z s$<8Rd9,date-)mmdd=Z

p$<8enter second date<mmdd=9=Z s$<8Rd9,date0)mmdd=Zp$<8enter second date<mmdd=9=Z s$<8Rd9,date0)mmdd=Z

month-'date-)mmdd/-55Zmonth0[date0)mmdd/-55Z//ta7emonth-'date-)mmdd/-55Zmonth0[date0)mmdd/-55Z//ta7emonth alonemonth alone

p$<8"rstt month is Rs9months^month-_Z9p$<8"rstt month is Rs9months^month-_Z9p$<8second month is Rs9months^month0_=Zp$<8second month is Rs9months^month0_=Z

]]

/WProgram to illustrate the use o$ structure pointer/WProgram to illustrate the use o$ structure pointer

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 104/129

 

/WProgram to illustrate the use o$ structure pointer/WProgram to illustrate the use o$ structure pointer

Struct currencyStruct currencyOO int rupeesZint rupeesZ

int paiseZint paiseZ]Z]Z

main<=main<=

OO struct currency mycurr[O-020U]Zstruct currency mycurr[O-020U]Zsho6it<,mycurr=Zsho6it<,mycurr=Z

]]

sho6it<struct currency Wmyptr=sho6it<struct currency Wmyptr=

OOp$<8rupees RdRd9myptrp$<8rupees RdRd9myptrrupeesmyptrrupeesmyptrpaise=Zpaise=Z

]]

&nions&nions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 105/129

 

&nions&nions

&nions loo7 similar to structures) They have identical&nions loo7 similar to structures) They have identicaldeclaration syntaG and member access but theydeclaration syntaG and member access but theyserve a very dierent purpose)serve a very dierent purpose)

  /nin %tp /nin %tp

  int iaint ia  fat fafat fa

  c"ar sac"ar sa

 

  /nin %tp :/nin %tp :

Accessing members o$ a union is via 8Accessing members o$ a union is via 8;;9 member9 memberoperator or $or pointers to unions theoperator or $or pointers to unions the <= <=  operator)operator)

&nions&nions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 106/129

 

&nions&nions

A union holds the value o$ one'variable at a time)A union holds the value o$ one'variable at a time)  The compiler allocates storage $or the The compiler allocates storage $or the biggest biggest  

member o$ the union)member o$ the union)

 The type retrieved $rom the union must be the The type retrieved $rom the union must be the

type most recently stored) 4ther6ise the resulttype most recently stored) 4ther6ise the resultis implementation dependent)is implementation dependent)

  /nin %tp /nin %tp

  ;fa > 56;4;fa > 56;4 ? "ds tp fat; ?? "ds tp fat; ?

  printf'@f(n@ ;fa) ? ; ? printf'@f(n@ ;fa) ? ; ?

  printf'@d(n@ ;ia) ? Ipntatin printf'@d(n@ ;ia) ? Ipntatin

dpndnt; ?dpndnt; ?

&nions&nions

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 107/129

 

&nions&nions &nions are used to store one o$ a set o$ dierent&nions are used to store one o$ a set o$ dierent

types)types)

Commonly used to implement a 8variant9 array)Commonly used to implement a 8variant9 array)

<This is a $orm o$ generic programming)=<This is a $orm o$ generic programming)=

 There are other uses also but they are Kuite There are other uses also but they are Kuiteadvanced <e)g) concern the alignment propertiesadvanced <e)g) concern the alignment properties

o$ unions=)o$ unions=)

/W :rite a c'program $or student mar7s/W :rite a c'program $or student mar7si $ t t W/using an array o$ structures W/

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 108/129

 

using an array o$ structures W/using an array o$ structures W/ struct mar7sstruct mar7s

OO int sub-Z int sub0Zint sub-Z int sub0Z

int sub2Z int totalZint sub2Z int totalZ ]Z]Z

main<=main<=

OO int iZint iZ

static struct mar7s student^2_[Ostatic struct mar7s student^2_[O OUQUQU]OUQUQU]OU.UUU]UQUU]]ZOU.UUU]UQUU]]Z

static struct mar7s totalZstatic struct mar7s totalZ

$or<i[5ZiX[0Zi@@= O$or<i[5ZiX[0Zi@@= O

student^i_)total[student^i_)sub-@student^i_)sub0@student^i_)sub2Zstudent^i_)total[student^i_)sub-@student^i_)sub0@student^i_)sub2Z

total)sub-[total)sub-@student^i_)sub-Ztotal)sub-[total)sub-@student^i_)sub-Z

total)sub0[total)sub0@student^i_)sub0Ztotal)sub0[total)sub0@student^i_)sub0Z

total)sub2[total)sub2@student^i_)sub2Ztotal)sub2[total)sub2@student^i_)sub2Z

]]

Contd))Contd))

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 109/129

 

print$<8ST&D3Tprint$<8ST&D3T  T4TA#9=Z T4TA#9=Z  $or<i[5ZiX[0Zi@@=$or<i[5ZiX[0Zi@@=

print$<8student^Rd_ Rd9i@-student^i_)total=Zprint$<8student^Rd_ Rd9i@-student^i_)total=Z

print$<8S&B?CTprint$<8S&B?CT  T4TA#9=Z T4TA#9=Z

print$<8RsRdRsRdRsRd9print$<8RsRdRsRdRsRd9

99subHect -9 total)sub-subHect -9 total)sub-

  99subHect 09 total)sub0subHect 09 total)sub0

  99subHect 29 total)sub2=ZsubHect 29 total)sub2=Z

print$<8rand total[Rd9total)total=Zprint$<8rand total[Rd9total)total=Z

]]

%ile Input In C%ile Input In C

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 110/129

 

%ile Input In C%ile Input In C

" #rogra$

FI@E

(he " ty#e* AFI@EB allow% for a con%i%tent a##roach to in#'tregardle%% of the act'al #hy%ical de)ice

s t  r  e a m 

 s t r e a m

KefaultA stdin

%ile 4utput In C%ile 4utput In C

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 111/129

 

%ile 4utput In C%ile 4utput In C

" #rogra$

FI@E

Si$ilar to file in#'t* the " ty#e AFI@EB allow% for a con%i%tenta##roach to o't#'t regardle%% of the act'al #hy%ical de)ice

 s  t r e a

 m

s t  r  e a m 

stream

KefaultA stdout

Declaring a %I# VariableDeclaring a %I# Variable

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 112/129

 

Declaring a %I# VariableDeclaring a %I# Variable

%ormat%ormat %I# WX%I# WXname of pointer to lename of pointer to leYZYZ

GampleGample %I# W$pZ%I# W$pZ

Be sure to include the $ollo6ingBe sure to include the $ollo6ing

preprocessorspreprocessors include Xstdio)hYinclude Xstdio)hY include Xstdlib)hYinclude Xstdlib)hY

4pening %iles4pening %iles

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 113/129

 

p gp g %ormat%ormat

%I# W $open <const char W "lename const char%I# W $open <const char W "lename const charW mode=ZW mode=Z

GampleGample

$p [ $open <8data9 8r9=Z$p [ $open <8data9 8r9=Z

$p [ $open <8/home/pro$s/tamH/data9 8r9=Z$p [ $open <8/home/pro$s/tamH/data9 8r9=Z

Error conditionsError conditions %ile does not eGist)%ile does not eGist)

Insucient permissions to open the "le)Insucient permissions to open the "le)

4pening %iles <0=4pening %iles <0=

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 114/129

 

%ilename%ilename

(ust reside in the same directory as C program being run(ust reside in the same directory as C program being run

Alternatively you can include the path to the "leAlternatively you can include the path to the "le

Some %ile open modesSome %ile open modes

(ode(ode ectect

rr 4pen teGt "le $or reading4pen teGt "le $or reading

66 4pen teGt "le $or 6riting4pen teGt "le $or 6riting

aa 4pen teGt "le $or 6riting start4pen teGt "le $or 6riting start6riting at the end6riting at the end

r@r@ 4pen "le $or reading and 6riting4pen "le $or reading and 6riting

6@6@ 4pen "le $or 6riting and reading4pen "le $or 6riting and reading

Closing %ilesClosing %iles

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 115/129

 

Disassociates the "le 6ith the physical deviceDisassociates the "le 6ith the physical device

*emaining contents o$ the stream a Mushed*emaining contents o$ the stream a Mushed %ormat%ormat

int $close <%I# W $p=Zint $close <%I# W $p=Z

GampleGample   $close<$p=Z$close<$p=Z

.riting *o ! -ile /print0.riting *o ! -ile /print0

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 116/129

 

%ormat%ormat

$print$ <%I# W$p 8const char Wcontrolstring9$print$ <%I# W$p 8const char Wcontrolstring9

arguments=Zarguments=Z

GampleGample

char arr^1_ [ 8hiya9Zchar arr^1_ [ 8hiya9Z $print$<$p 8Rs9 arr=Z$print$<$p 8Rs9 arr=Z

 Similar to print$ eGcept you can also 6rite to a "leSimilar to print$ eGcept you can also 6rite to a "leotherother

than the screen <standard out=)than the screen <standard out=)

*eading %rom A %ile 8$scan$9*eading %rom A %ile 8$scan$9

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 117/129

 

%ormat%ormat

$scan$ <%I# W$p 8Xcontrol stringY9$scan$ <%I# W$p 8Xcontrol stringY9addresses=Zaddresses=Z

GampleGample char arr^1_Zchar arr^1_Z

$scan$ <$p 8Rs9 chun7=Z$scan$ <$p 8Rs9 chun7=Z

Similar to scan$ eGcept you can also read $romSimilar to scan$ eGcept you can also read $roma "le other than the 7eyboard <standard in=a "le other than the 7eyboard <standard in=

*eading %rom A %ile 8$gets9*eading %rom A %ile 8$gets9

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 118/129

 

*eading %rom A %ile $gets*eading %rom A %ile $gets

%ormat%ormat$gets<char Wline int n %I# W$p=Z$gets<char Wline int n %I# W$p=Z

GampleGample   $gets<chun7 15 $p=Z$gets<chun7 15 $p=Z

-ile ': -irst Example-ile ': -irst ExampleTh $ ll l b $ d i CThe $ull e ample can be $ound in C

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 119/129

 

 The $ull eGample can be $ound in C The $ull eGample can be $ound in C

include Xstdio)hYinclude Xstdio)hYinclude Xstdlib)hYinclude Xstdlib)hYint const #3T! [ 15Zint const #3T! [ 15Zmain <=main <=OO

  %I# W$pin W$pout Z%I# W$pin W$pout Z  char arr^#3T!_Zchar arr^#3T!_Z  char $nin ^#3T!_Zchar $nin ^#3T!_Z  char $nout ^#3T!_Zchar $nout ^#3T!_Z

  print$<nter name o$ input "le =Zprint$<nter name o$ input "le =Z  scan$<Rs $nin=Zscan$<Rs $nin=Z  print$<nter name o$ output "le =Zprint$<nter name o$ output "le =Z  scan$<Rs $nout=Zscan$<Rs $nout=Z

-ile ': -irst Example (1)-ile ': -irst Example (1)

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 120/129

 

  $pin [ $open<$nin r=Z$pin [ $open<$nin r=Z   $pout [ $open<$nout 6=Z$pout [ $open<$nout 6=Z

  i$ <N$pin=i$ <N$pin=   OO   print$<CanEt open input "leLn=Zprint$<CanEt open input "leLn=Z   return<'-=Zreturn<'-=Z   ]]

  i$ <N$pout=i$ <N$pout=   OO

  print$<CanEt open output "leLn=Zprint$<CanEt open output "leLn=Z   return<'-=Zreturn<'-=Z   ]]

%ile I/4 %irst Gample <2=%ile I/4 %irst Gample <2=

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 121/129

%ile I/4 %irst Gample <2=%ile I/4 %irst Gample <2=

  6hile <$eo$<$pin= [[ 5=6hile <$eo$<$pin= [[ 5=   OO

  // &sing $scan$ it stops scanning at 6hitespace// &sing $scan$ it stops scanning at 6hitespace

  $scan$<$pin Rs arr=Z$scan$<$pin Rs arr=Z

  $print$<$pout Rs' arr=Z$print$<$pout Rs' arr=Z

  ]]

  return<5=Zreturn<5=Z

]]

-ile ': Second Example-ile ': Second Example

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 122/129

 

 This eGample is identical to the "rst eGample eGcept This eGample is identical to the "rst eGample eGcept$or the loop$or the loop

6hile <$eo$<$pin= [[ 5=6hile <$eo$<$pin= [[ 5=

OO

  // rabs 6hole line up . characters or the end'o$'// rabs 6hole line up . characters or the end'o$'"le <6hichever comes "rst="le <6hichever comes "rst=

  $gets <arr 15 $pin=Z$gets <arr 15 $pin=Z

  // :rites out to output "le as'is)// :rites out to output "le as'is)  $print$ <$pout Rs arr=Z$print$ <$pout Rs arr=Z

]]

-ile ': *#ird Example-ile ': *#ird Example

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 123/129

 

include Xstdio)hYinclude Xstdio)hY

include Xstdlib)hYinclude Xstdlib)hY

int const #3T! [ 15Zint const #3T! [ 15Zmain <=main <=

OO  %I# W$pinZ%I# W$pinZ  char arr^#3T!_Zchar arr^#3T!_Z  char $nin ^#3T!_Zchar $nin ^#3T!_Z

  print$<nter name o$ input "le =Zprint$<nter name o$ input "le =Z  scan$<Rs $nin=Zscan$<Rs $nin=Z

-ile ': *#ird Example (1)-ile ': *#ird Example (1)

$ i $ <$ i =$ i $ <$ i =

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 124/129

 

  $pin [ $open<$nin r=Z$pin [ $open<$nin r=Z   i$ <N$pin=i$ <N$pin=   OO

  print$<CanEt open input "leLn=Zprint$<CanEt open input "leLn=Z   return<'-=Zreturn<'-=Z   ]]

  6hile <$eo$<$pin= [[ 5=6hile <$eo$<$pin= [[ 5=   OO

  // rabs 6hole line up . characters or the end'o$'"le// rabs 6hole line up . characters or the end'o$'"le   $gets<arr 15 $pin=Z$gets<arr 15 $pin=Z

  // :rites out to output "le as'is) 4utput "le is the screen// :rites out to output "le as'is) 4utput "le is the screen   $print$<$print$<stdoutstdout Rs arr=Z Rs arr=Z   ]]

  return<5=Zreturn<5=Z ]]

/W :rite a program to detect error 6hile opening a/W :rite a program to detect error 6hile opening a"le that does not eGist)W/"le that does not eGist)W/

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 125/129

 

includeXstdio)hYincludeXstdio)hY

main<=main<=

OO char W"lenameZchar W"lenameZ%I# W$p-W$p0Z%I# W$p-W$p0Z

int i numberZint i numberZ

$p-[$open<8TST9969=Z$p-[$open<8TST9969=Z

$or<i[-5ZiX[-55Zi@[-5=O$or<i[-5ZiX[-55Zi@[-5=O

put6<I$p-=Zput6<I$p-=Z$close<$p-=Z$close<$p-=Z

print$<8 Input %ile 3ame9=Zprint$<8 Input %ile 3ame9=Z

open"leZopen"leZ

scan$<8Rs9"lename=Zscan$<8Rs9"lename=Z

i$<<$p0[$open<"lename9r9==[[3&##=Oi$<<$p0[$open<"lename9r9==[[3&##=O

print$<8Cannot open the "le9=Zprint$<8Cannot open the "le9=Zprint$<8Type "lenme again9=print$<8Type "lenme again9=

goto open"leZgoto open"leZ

]]

Contd))/W**4* !A3D#I3 I3 %I# 4P*ATI43SW/Contd))/W**4* !A3D#I3 I3 %I# 4P*ATI43SW/

elseelse

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 126/129

 

elseelse

$or<i[-ZiX[05Zi@@=$or<i[-ZiX[05Zi@@=

OOnumber[get6<$p0=Znumber[get6<$p0=Z

i$<$eo$<$p0==i$<$eo$<$p0==

OO

print$<8*an out o$ data9=Zprint$<8*an out o$ data9=Zbrea7Zbrea7Z

]]

elseelse

print$<8Rd9number=Zprint$<8Rd9number=Z]]

$close<$p0=Z$close<$p0=Z

]]

+EC2+SIt is the process o$ calling o$ a $unction by itsel$) The

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 127/129

 

p g y$unction 6hich calls itsel$ is 7no6n as recursive$unction)

A(P# T4 CA#C&A#T %ACT4*IA# 4% A 3&(B*

 int $actorial<int=Zvoid main<=

Oint num$Zprint$<8enter number 6hose $actorial is to

be calculated9=Zscan$<8Rd9,num=Z

$[$actorial<num=Zprint$<8Rd9$=Z]

ContdJ

int $actorial<int G=O

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 128/129

 

Oi$<G[[-=

return -Zelsereturn GW$actorial<G'-=Z]

7/26/2019 14648_C-Language (All Concepts)

http://slidepdf.com/reader/full/14648c-language-all-concepts 129/129

*H!3