[go: up one dir, main page]

0% found this document useful (0 votes)
66 views21 pages

Unit-5 ITP

The document discusses functions in C programming, explaining their structure, advantages, types, and how to declare, define, and call them. It covers user-defined and library functions, as well as the importance of function parameters and return types. Additionally, it touches on function calling methods, recursion, and file operations in C.

Uploaded by

nagas2820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
66 views21 pages

Unit-5 ITP

The document discusses functions in C programming, explaining their structure, advantages, types, and how to declare, define, and call them. It covers user-defined and library functions, as well as the importance of function parameters and return types. Additionally, it touches on function calling methods, recursion, and file operations in C.

Uploaded by

nagas2820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 21
Unit -& Functions A farction ih a group of statements that together Peyor a tek, every C prograrn has at Least one farctow, which fA maint ); Syntars yeturnbype function —name ( axguments) aE go \ Skmt's 5. ' 4 Function Advanteges ® + By wing function, we GP avoid cewrting — Logic Jcode again and tee Ha pegem- * we Ger call C functtoo ang nur ber pagan and fem any place in a prgram. + we Can-tvack (a darge c- prqram ean ly when itis vided toto multiple functions . Rewabilt GF in the main achievement of © fdnietions Types of functions « There axe two types of functions tm C prgramming- of times TW a he Libvoxy Functions ave the functions’ which are in the Cc header file Such Os StanP(), peinte( ), getse x, PutsC ) , cetld), floor ( ) ete i ran 3. USex defined Function s axe the -functtons uslhich ave created | by the C poyammer, SO that helshe Con use Tt mony Hines. Le yeatuces the Complexily of 4, .b'g pegrem and -optimizes the Cole. declared | Three lypes of Skeps have follow im user defined henctron. Ie-fanclion declaration ov prrolype 2 function definttton 3+ fmclton call ls Function declaration or prototipe A function mut be declared globally To aC prgram to tell the Compiler about the function name, -fanction parameters , and veturo type. Syntax: < function _name > (argument _ list) <* vod rwbo( 9; ; &- Function defination: Ie contains the actual Statements which ave to be ereceted. It ts the moat Important axpects, to which: the . conto! Come, ishen the function ih Called. Here , we must mnotice that only one value Con be setumed Fors the funchon . Syotert 7 7 (parametey lab) Function body 5 4 to 3- Function callt + Funckion Call be Called “fom anyehere in the pogen - The pasormetey list weet not, dither a _ Pak iw fonction calling and «-fenction decloxation « We rout pas the Same number of functions ay it % declared tm the -fenction declaration. Syotant funclion name (argurs ent int) Parts of junctton s + PRetuwm values A C function vey 08 rey not seturn a value -for the function . Lf you dlontt have to return any values for the function , wre void “for the vetumn ‘Gre: Let'S Seea Simple example of ¢ function thet cloesn't elu any value om the function. Example without retain value 2 Void hello ( ) Prntt (hello c'), 4 sh HF gou want to return any Value trom the fainction, you need to tre amy data type Such a int, Long> Chav, ete. The vetum type cle penck on the value 40 be velumed from the function, debls see a Simple exarople af C function that veturns int value fom the function . Example with yetum value int get) t Teturn (05° se ON This is the actual name of henets Function name: dey Wat 4 the -fancken’ tame and: the parare’ “the, Comtihete the function Signet parame ley ts ike q. ta involved, gor P% ve. Paxamelers ov Axgaments ¢ A Placeholdey. when a function &® value to parameters Thin Value ?S sefpered tb a® actual porametey oY argument . the porametey At seter to toe type, ovdey and number of the the pavametey of 42 Ue ype , order aad a hencben. Parametess ave optional that in a -fenction Mey Contam no parameter . Function body = The -funchon bedy containk a Collection of Statements that define, what the function doe- EX fe function veluwning the Wa Heo two numbers */ int max (int wut, int num 2) ¢ int wesult 5 Tf (oun 1y num2) Tesult enumsy else vebulb =num2 5 return versalt § 5 . The Source Cade of function Called moxl ), This finclion takes too parameters num4 KX vumz and be returns the maximum between the tuo in above example j function declaration TA int mot (Int mum 4 int num2); Prameter names are vot Tmpor tant tn fanction only anc Uype 78 vequined * ext Tne warCint, int) Name of the fanction TA mart). p.return type of the finction fot: 3. too argumen ts of type Tnt ave posed to furctona. Cakegory of functions (oe types of function defination )dibfaent axrpects waction Calling: — © diplrenk axpects of function calling A funckon may or may not accept any arguments tk rey oy maynot return any value - Bared on thae facts ,There axe fouv dizpervent aspects of funckion calls. ' Function usithout axgument and without velo type. & Function usithout argument and wil velurn type. 3: Function with axgum ent ard without yeturo type. 4 Function usith argument and with return type- b Functton csi thout avgument and _usithout vetur type > In thig, coregory , the -funclhon ha, no axgumenta WE does not xeceive any data vem the calling function. Similarly, H does not we tum any value. Se calling Rnction doen't receive any data Gorm the aalled function. So, there 1s no Communi cation Plas a Calling ond called functon. 5 4 ex: dPinclude Zstdio-h> Void suml )5 maint } t Sum ( );5 JetehOrs 4 Void Sum( ) < Int a,b,c 3 Print # (‘enter the value “)s Sant (“Ad yd", wa wb); Cc =atb; Punt t C%d “os a 8. Functon usithout argument and, with rebum lypes The function have no axgumenta and it doesn't weceive any alata from the Calling function, but | Tk vetinmm a value to the calling funckon . The on | calling function wece?vex alata from ihe Called fancbn Be sFinclude int Sum 3 Tmt main ( ) i Int ¢ 5 C =Sum()3 . Print # (“Sum a/ea', ¢)5 5 PB int Sum) int a/b, 6} Print# (“enter 2 no's"); Sant (“Ad ed", wa Wb), CHath3 wertunne 5 I 3: Function with argument and without seturo types ee ee AS / be Function fas Some arguments, it veceiver data for the calling funchon, but Ht down} to the calling functions ~ BF eieclude Zstdio.h> void main(int , rot) void main ) t int a,b» Pvintt (enter 2values %; SNF (“Yd Yo" or, Hb) 5 Sum (a,b) 5 yetain a value Void Sum (inta, int b) { mt ct, CHAtbs Print# ("sum = pd" c+ J 4 Fumetion with axgument aod with wetuyo ly pes Sorne arguencots amd it veceives dlata frory the calling fancbon. stentledly avalue tv the calling fanct on. The Receive data from the Funclion have , TL welurny calling faunckien function: called B Arinclude £Stdio.h> fat Sues (int, int ) main C ) cc wt a,b, c5 Print (Center 2 numbers"), Sto s mF Od tad *, wah) » © =Sue Ca,b)3 Prmtt Cd", cds 45 Trt Sum (int a pint b) ra : int cy c -atbs, weturn C5 5. Function call: This calls the actual function. Symicars function nowne (oxgument. List) 5 a 4 ‘There ne wr vxays that aC function canbe Called fom a progr: \s coll by value & Call by reference: 1+ call by value: + The value of votiable 74 passed to junction a pararnetey + The value of aclual parametey Cannot be wood fied - + Dijperent memory ik allocated’ fos both ‘actual and Formal parameters . Because, value of actual parameter Ts copied +o -forrnet parameters. CFanetional Catt) ee Canetion Aefiniten) Hrinclude estdio.h> Void Sw0p Cinta, tat b) 5 tot main¢ y Int m=20m=30; PrinEF (“values bejere swap may, SHEP (m9, 1 5 VIF suoapCint a, ink b) t APHID aKa ny Moctuak parameter // 4 For roal parameters ink temp 5 = azbs be temp 5 Prot (*\n Values after Swap m=td\n and neted Lash) 5 Be i: a , & call by veperence / pototer / naldrers + ° funch * The addres of the voviable 74 passed to the function Os pecrarne lev. “The value off the actual payormetey can be modified by “fotwnal parermedter - + Same memory in ured for bolh actual and formal parameters since only addren 1 wed by both Paramet evr. BeFE* petual payameters «This, ih the axgament. whieh ts wed im fancton call- Forrrad pavametera —This wt the argument which ts | wed to function defination + | Exe pogram Cmodijytng parameters trutde Junction uatag pointer) | Include void swap (int xa, int xb) 5 Tmt maint ) t int m=20 ,n=105 Printe (‘valued belose swap m=%e4\ 9 0 =7.d “).9)5 swap (um jun) , void Swap (int x0, tnt #b) t it Lermps temp = ¥O5 ane = #65. ; tbe temp 5 Paiatt (values apter swap a-7.d\y b-Td "a ,eb)5 too function : Passing Arney $B we need to pas a (it of clernents a4, then ever jt %& better arguments to any function FO C dog vage , do we an array for this. AFinclude £6tdio-h> int calsurn (int maresl J) € int is int Suro = 05, for (i205 145 5744) t Sam = Suro+ marks CITY 5 Teluw Sums 3 int main ( ) t Int wesult, masks [J = {10,2055 ,60, 70} Besult = Galsumn (mares); Print =(*Reult © ze * seturn oO Ds Recursion = The pwces of aalling a fanction by itself th called wecursion and the functon which -call, pbeaulk )s itaely 1 alled vecursive function. Recursion Th wed to Solve yarious wothe matical peoblems by divideng jt into Amaller problems. Syntaxt elu. type — eceursive_ function (Gorgument tat J) Prygrare § Fackovial of number by using yecursion function. Finclude teinclade int fact (n)s Noid main( ) t jnk 1, result 5 Print# (“enter ushich Foctovial you wont") +,” Scan f(« hd * un); Fault > fact(n)s ‘Hhenetion tall J PwtF (“factorial ~ hd" werielt)5 4 . Ot int fact (int n) t int wess ‘ iF (n==0) gE wes =15 5 elae at ; ye =e fact (n-1), 4 j welkurn yess “FP sack Oy) -fock (3) fact (2) = i lo= +0 fe (n= 20) eC if (0 9) ° - else yes 3x10) else ves 24 £(1) else BeS= UR L(3) Tae ves =1 xf (0) + Files wa. collection of vecovds (ory Win a place on harddisk where data ‘ : Permanently ard to accom. otter that eee ofa data , wohen evef mecemany- Bok wma ae (6 Stoving Lhe data) tohrle js stoved Why files ave needed? 1 6 . - when a program is levmninated, the entixe deta will be lost . Stovingy’a File will preserve yout data even i the progam terminates. * You can eaxily move your data from one Computer to another Computer: Types of files : \. Text File &. Binary file Ie Text filess + Text files ave the nowmal -tut files. you Gn early create text files uring simple text editors Such ax notepad . * when Fr open thore -frles, youll See all the Cortents usithin the file ax plain text You can cantly edit ox delete the cm¥enty. « They take minimum & to maintain, oye easly veodable , aod provide the Least S: and ‘takes bigge’ strange Space a Biney Bis * * Binoy files ave montly the PD fles tH you’. Comnpute¥ + tmtead of Storing chta in sen text) they Stove it im bieary fore (0's and 19). . “hey tm hold a higher amount st data , eee Yeodable easly, and provider’ better Secu tran text files. File operations : mC, you GO perform five majos operations on Files, either text ox binary: (- creating a new file (Fopen( ) & Opening an exinting file (4opent 2) _ ef fF (felesec )) A+ Reading orn a file (Fonte, tgets,,fgete) Bs bbwting into ot file (tscanet 3, fputse ),fpute ¢ )) Ulorking usith files : when voosking with Files, you necd to declare © pointer of type file. This declaration is needed -for Communtation between the file ond the papam, FILE *fp; - fo Creation and edit. Opening a Eis uret to Create a new File of open grist File. * Opening a file is perfamed using the fopent ) function defined tm the sidio.h header alen Sypters fp = open ("Filename "mode" 3 Ex: =" FILE .*4p FP = Fopen (“D:\ sample - tut HO wis the sat functon creates anew file named Sarnple-txt and Ft is for coriting as per the mode ~ File Opening modes I. “¥"_4 opens a file -fr seading JThe file must exist. 2. “W" > creates an exply file for comeing : 3. “a" Appends +0 a file. Uniting operations , Append data atthe end of the File. Ae et THT pers a File to update bo th Yeading ard coating . The file wut ext.’ S wt" + creates an emply file fev beth vod ard tovitings’ . Ae 6. "A+" 9 ‘open ‘a Ble fov veadhion acd ; p ' Yeading axid appendiig Note? HF you ase going to handle binary. tiles then You will we Follosieg acces modes Tnbheod, of the above mentored omes."tb", “wo “abt, “abt “wht, "abt" — LT lored The file Choth text and binary) should be <'0* ‘ ot farmed after reading /wviting « closing a file ts pestn wasing Klay function {clase ( ). Fclose (4p); fp tp is a file pointed ancciat Cloned. ed with file tobe C prvides a number of function that helps +o Pextprm baxte file operations . Fallousing ave the fench on Fopen( ) —> Creates a new file ov open a erintiog Felose( ) —+ file closer a file- Foviott() —y writes a Set of data toa file FscomF() —> Readn a Set ok data for a file. GEN AGeteC) > Reods o character froma file Putc\fputec ) — write a character intoa file. Beet Meant al integer from a File. Putwl) 9 Lorde a inlegen toa file Fgetsl) — Te red a Shing fom a file Fputs () —> To write a Skiing into a file. fread) —» To vead an ewlixé-vecord froma ble. fute () — To write an entie vecord Into a fle. tseekL) —y set the position to, desixe point. - ftellC) — gives current position im the file pilwind() —» set the position to the beginning Point. | o o Character F/p functions ox (Unforrooted To foneki L fgetccy 1 used to axcad a Chatactet bor a file Syntaxs char - variable = tgete (1P) ; B FILE *¢p Chay ch; ch= fgete (¢p) 5 2. Fpute (): wed to write a chaxacter tote a file gators fpute (char vor fp ) 5 eerie tp Chat chs: pate (eh #95 sting te Functor, (Uriformated Ifo Fanctions ): Ie vead ov write Le a ile to the form oF anny of chavactern. : i gees Read Shing rors File Spots fgets Coahy He value, fp); Denotes num of chavacters a) 2 SRG, 2 fpats(): wove a Sting mb a File» Syptert puts (suing , fp); Ee APinclude Astdio.h> ‘ dtinclude: Leonio -h> Void main FILE * fp 5 chay Stv[30] 5 int ny Paott (“enter number of sig ) Sent (tel un); £P = fopen( Sarnple-txt ", "\s fee Cieo ste; 44) ¢ Print (“enter sbiag hd”, i); Jets (sty); puts (st«,#p)3 close (4); fp = fopen(* Sarnple-txt",* x‘); for (i205 1205 i++) £ fgets (stv, 20, Fp) 5 Pant Cstang yd" ,i)3 Puk (stv) 5 J £ close (4p); I Formated to function I Forint ()5 pace is ured to whe ink, floaty Chav oF Shang values, om pile. Syntor? tpantt (4p."conbal shieg "lish of eaten & Fseane (1 which iS ured -berrvead' hot, float char ov String values from a file. Symtorx? fscant (+p /“Control_stang “, " wlist of Vos ables) ; Ex: = bw rofrarn fox stoving the details ob an v9 emplges ima file ond print the Same include Lstdio. h> dEinclude Z conto. hy Void maim ( ) ‘ t FILE “Fp , Int eno; ChaY ename [30] 5 Float Salary , fo p20 (Semp a 3t)g Print (“enter the details of eno, ename » Solow) 5 Stan So Nef or mt (Sndysne? 2¥end ,wename ; usalary) +, forint we vac tal PH (66, "Md ere ineafle Ff close (4p); 7 ENO, Ename , salary); fp = fopen (emp. tet “ ys); used ew foent (Hp Yd PS 7-4", Beno, bename, wsalary)>, cod data Print ees: Print (remnployee eno ted“, eno) ; Punt iC employe ename = 7.5 ', ename) ; Prin lt ( exnp layoe calor « 1", Salary )s Close (4p); J

You might also like