Docsity

Keep notice in information, Lecture notes of Computer Science

Partial preview of the text

Download Keep notice in information and more Lecture notes Computer Science in PDF only on Docsity!

Chapter... Functions ad 42 42 « Introduction to functions. + Function prototype. Function definition, Accessing a function and parameter passing « Recursion. Prescribed New w.e.f Academic Year 2019-2020 Introduction to Functions ee 3 414.1 Function Definition / Elements of Fumetion 4.1.2 Function Prototype _... 4.1.3 Accessing or Calling Function _.... 44.4 Parameter Passing eee 4.41.5 Advantages of Function ... Types of Function... 4.2.1 Function withno Retum Type and ne Argument... 4.2.2 Function with Arguments and no Retum Type... 4.2.3 Function with Return Type and no Arguments... 4.2.4 Function with Retum Type and with Arguments... Library Functions... — ee 410 UQ. Explain the purpose of following standard library functions - fi} Floor) (i) cea) (a) sqry REET z i ee Tre rer OR. = State any 2 Ebrary functions in math h along with its uses. Serene net eT = 2 C Programming (MU-FE-Sem tl) (Functions)....Page no. (4-2) OR ua. ua, 44° Scope of Variables... 45 Recursive Functions. ua. OR oR 454 ua. 45.2 ua. 45.3 ua. ua. OR ua. ua. ua. > a AZ Explain pow(), abs{) and ced() function {QE Write a program to calculate compound interest and amount. Using formula A=P(1+RM00)/n, where P=Piincipal Amt., R is Rate of interest, n= number of years. Your program should make use of user defined function to calculate power. Program should accept P, A and N, AA? Write a menu driven program to perform arithmetic operations on two integers. The menu should be repeated until the user selects ‘STOP option. Program shouldhave independent user defined function for aach case. Explain recursion concept. [i Whal do you mean by recursion ? (00 14, I / 16. Dec. 15,2 Marks ae Explain recursive tunction Ei[U BINS iar Advantages of Recursive Functions. What are advantages of recursion? [IEEE Disadvantages of Recursive Functions. Whal are disadvantages of recursion? [J] Programe on of Recursive Functions. Write a program which will add first n natural numbers using recursion ()UBS MSR EAPEEILES 4 White a program to reverse a number using recursion, f Marks oo socesscnmeneee 4223 Write a program to find Pd using recursion, 4-24 AS Hroempae a aie sian cement einianddeunnpcnsaesnaonieisecotioansnecinics| endaesbiiondacsanmesasaniadsidaudsoes 4-24 (MU-New Syllabus wef academic year 19-20(M2-05) fe Tech-Neo Publications_A SACHIN SHAH Venture © Programming (MU-FE-Sem (Functions) Page no. (4-4) Syntax of function - The syntax of the function is as fallows. return type Function name(list of formal parameters) { feral varialsle declaration ; statement 1; statement 2; returm slaiement; } Example of function int divin a, int be) $e 4 int result; if ih == Oy 4|*Earor tecan'l divided by zene”): Function header return resull; - Here div is the function name. It performs division. div returns an integer value. The result is focal variable. The variables a and b are two parameters of div. a and b are called as formal parameters. — C function can take any number of formal parameters but it can return al most one value per call. — The function is called in two ways as Call by Value and Call by Reference. YR 4.1.2 Function Prototype eg. Explain with the proper syntax Function - ceases iid hick anpacacaeeaeeeeecwseia ix cae M1) ans.: Function Prototype - Same as of variable, before using a function in program il can be declared. The declaration of function is called as funclion prototyping. - The function declaration follows following format_ retumn_lype function_namejlist of formal parameters); - Function declaration also referred as function prototype. It has four parts as listed. 1. Retum_type 2 Function_name 3. List of formal parameters 4. Semicolon — These elements are same as of the function header in function definition. — Wt is possible to have different parameter names in function prototype from the names present in the function defination. — But it is mandatory te match retum type in function prototype with return type in function definition. — Also type, order, and number of the formal parameters of list in function prototype should match with type, order and number of formal parameters in function definition. — Funetion decloration is done in global section i.e. after including the header files and above all the functions including main (). - Globally declared functions are available to all the functions in the program. Also we can declare a fonction inside a fonction this is called declaration so its life is limited to the function in which it is declared. It is better to place function prototype in global section. local Example of fancilon declaration # include #include ¢conioh = av dint a, int hj; ———* Fenton prototype — Wf rewrm ype is absent then it is assumed that the function returms int value. Parameter names are optional in function prototyping. We can declare function div in following way: ant div {int a, int b};, or div (int.a, int by, or diy (int, amt); — These al! declarations are valid_ — The prototype of a function which doesn’t accept any parameters and docsn'l return any value is written as follows: void addivosd); (MU-New Syllabus wefacacemic year 19-20 (h42-05) i Tech-Neo Publications... SACHIM SHAH Venture G Programming (MU-FE-Sem Il} - Prototype declaration is not essential but if il is mot declared before it is used, then compiler assumes that be available al linking details of thal functions wi time. WR 4.1.3 Accessing or Calling Function GQ. Explain with the propersyntax :function cal. (4 Marks) M1 Ans. : Accessing / calling a Function - 9 We have learned how to define the function. To use defined function we must call iL. Syntax - Following syntax is used to call a function. Function_name (list of actual parameters}; - Belore calling any function it should be cither declared or defined [ otherwise compiler will generate an error. st and then function call can be made, Calling function and called functlon - The function which calls another function is referred as calling function and the function which gets called is referred as called function. Actual and formal parameters - Parameters used im function call are referred as actual parameters whereas parameters used in the function definition and function declaration referred as formal parameters. | GQ. Write a program te find greater number using | f function. M1 Ans. : Program #inclucle #inclurle conto void greatertint inl |; = Fonction prototype int main) 4 int x=d.y greaterixy}: 0 OH Pumcnion call , ne Les void greateriint a, int bp (Functions)....Page no. (4-8) { ifta>b) { prinifi Function } elinuticn Cod is greater number", al; Cod is greater number", lrbs Output [Fieamecchee 5 is greater number Explanation = In this program main() is the calling function and the function greater(} is called function. While greater { } cets called by main()} further execution of main() is suspended and the contral goes to the definition of greater(} function and the values of x and y are mapped to a and b respectively. - After finding the greater number the control goes back tothe calling function ic. main () again and continues. its further execution. TH 4.1.4 Parameter Passing 1 GQ. Explain concept of parameter passingin function = M1 Ans. : Parameter Passing — When a function gels called there are two possibilities at order in which the actual parameters are passed to the definition and parameters. The possibilities are: function maps with formal oO Parameters are passed from leit to right. © © Parameters are passed from nght to lef. - In C, parameters are passed from right to lett. The order af parameter passing doesn't much essential for certain examples like following function call: ‘suurm (11h TA, FF IMU-New Syllabus wefacademic year 19-20)(h42-05) Tech-Neo Publications...A SACHIN SHAH Venture C Programming (MU-FE-Sem tl} (Funetions)....Page no. (4-7) messaget hs printfi”\n After function calla"): return J; u —_ void message (voi { printfi"nFunction with no return type and no arguments'n"l: JFunction with no return Type and no arguments: fter function cal) - Here function message doesn't accept any argument from calling function. — And also doesn’! return any value to calling function. The } brace of message{) denotes the end of function and returns the control back to maind j. TR 4.2.2 Function with Arguments and no fel ia racine ened No Recurn Type - When the function doesn’ return amy value void is written al the place of retum type. And when a function has arguments, these arguments are wrillen wilhin parenthesis. So general form of declaring the function with no retum type but with arguments is given below : Syntax void funetion_name (argument list}; - To-call the function with no retum type but with arguments following formal is used: function_name ( list of actual parameters ); - Every parameter is separated by comma in the list. Parameter list should match the order. type and number of parameters as given in function prototype or definition. Example — Forexample. if prototype of function is like: void sum(int a, int b, inte}; — Fallowing all are the valid function calls 1. sumi>, 120: 2 mt x=3. y= = 20, aumix.y2h: 3. sumnix_y 20h, 4, summ{x + 5.y-5,21; — All are valid because the function sumi } has three arguments of type integer. We can pass the constanls (as shown im 1.) variablestas shown 2h eapressions{as shown in 4), or any combination of thesefas shown in 3.) as fonction arguments. in — When expressions are used as function arguments then, first the expression is solved and corresponding result is passed and mapped with formal parameters. As shown above first be x+5=5+5=10, second argument of sum will be y-5= and third is z Le. 20 is passed. argument of sum. will - | GQ. Write a program toe demonstrate the function # include word cubetant a): { int mum = 3; prntfi\nThe number is:Sd"_ numb; 1. Function call to ewbe() cube(mam); —L | transier the contra to its return |; funchon definition. 2 2 Value of num ic. 5 copied } into a. void cube fint ab { ponlf( Cube of the number ts :Seel in", aa" al: After function execution control returned back bo main{}. (MU-New Syllabus w.ef academic year 19-20 (M2~05) hl Tech-Neo Publications...A SACHIN SHAH Venture C Programming (MU-FE-Sem tl) (Functions)....Page no. (4-8) the number i925 fube of the number is 212 Explanation When the main( ) function calls cubet ) function the value cf mum i.e. 5 is copied into formal parameter a and the comtrot goes to the cubet ) funciion. After executing lhe printf, }) statement the control goes back to calling function. Note that cube } function's retum type is void because it doesn't want to relam any value. The closing brace of cube () function indicates the end of the function so the comrol foes back to the calling function and continues execution af mainty. @& 4.2.3 Function with Return Type and no - dois used if the retum type is int otherwise Corresponding modifier is used to print the return value. 2 It prototype of function is like : int mull void); then, the following all are the valid function calls 1, sat resalt= suf}; 2. primti(—Ged™, mul); 2=5 + milf); - We can use a variable to store value returned by the function (as shown in I}, or without creating new vanable we can pom the returned value (as shown in 2.) by taking the function call as argument of printi{) fonction. The function call can be used in an expression (as shown in 3.) The return value of the function acts as the operand of expression. | GQ. Write 2 program to demonstrate the function Function with Return Type and No Arguments - When the function does not have any arguments we use void in the parenthesis. And when the function returns a Value, the data type for that value is written in the place ol return type. So general form of declaring the function with retum type but no arguments is given betow. Syntax retum_type fuscton_name (void); - To eall the function with rerum type bul no arguments following format is used - vaniable name = function mame (]; — variable_name is used to hold the value retumed by the function. Empty parenthesis indicates that the function doesn't have arguments. Examples 1. Wthe function retums meaningful value it can be stored in the variable or can be printed directly on the screen like: prinif(“Sed", function_mamef}}: Function call to square(} leads to ransfer the control to its definition. aml result = scqpase (); printli— The scpaare i: , resulty: return I: } — inl separeil { inl sum: eens statement relem ihe ponifi~\nEnter a mumber:\t'17 |; teanli—d", &num): $=bum*num: return s: } (MtJ-New Syllabus wef academic year 19-20\M2-05) Ly Tech-Neo Publications... SACHIN SHAH Venture C Programming (MU-FE-Sem Il} (Functions)....Page no. (4-10) else i Calculates the negative powers. while (p+ +} Al second calll lo pow) } pts 4 { so if block will be executed resull/=n; } Ketums the control hack to } maini) function with value of if He; ——P} result. — In this program we called the function pow(} twice with different inputs. - The value of x and y are given by user so 2 is stored in xand next 2 is stored in ¥ variable. - Al the first time we call the function with impuil x and 4 ie. the function calculates the 2 to power 4 Le. vis. - And at second time the pow) function is called with y and -3 as its arguments so the function calculates 2 Lo power -3 i.e. yr ouzs. - So each time the pow() function calculates the result and send it back to the expression im main(). 3 43 #8 Therefore #=5 +y +3=2 42 +3 = 16.000 + 0.125 + 3 = 19.125 is primed as result. M1) ans. : Library functions - Chas huge set of library functions which makes the C more powerful. These functions grouped under different header files. -— To use these library functions, header files should be included in the program. As we know every c program has a section called as header file section where the required header files are included. Different Header Files and Its Library Fanctlons — Some of the frequently used header files are: conio-h, sidio.h, sdlib.h, math.h, string-h, time.h, etc. GQ. Explain Mbrary functions under conle.h header ” ns eS acl or aseises eeeseseeeeeed Ans. : Fumcdions under conbo.h Header File - conio.h file includes the functions related to console. Some frequently used functions of them are explained below. clrser() — eirser{) clears the old text of output window and places the cursor in the upper ef comer of the window (at position 1,1 Declaration getch() and getche() - geteh() reads a single character from the console without echoing to the screen. Whereas getche(} reads a single character from the console and echoes to the Screen. Declaration int getch{ woud); int getchet void); Both are used for accepting a character from user. qgets() = Reads string from console. Declaration har *cgets(char *str}; — egets() will read string of characters from the console and stores the string (and the string length) in the location *str_ cpats() - Writes a string to the current text window on the screen and puts the cursor alter the string. (MU-New Syllabus wef academic year 19-20 (M2-05) & Tech-Neo Publications... SACHIN SHAH Venture C Programming (MU-FE-Sem tl) (Functions}....Page no. (4-11) M1 Ans.: pitference becween gerch() and getche() Function Description ac can =i putcharti writes a character to screen rameters getel -8e elearer() clears the errar i Concept Tt accepts the entered | Ho accepts the - character but doesn’L| entered — character Fopent) Opens file echo iton the screen. | and also echos it on felose() closes an opened file the screen. Ecrwt) reads an integer (rom file Example int main{) int main(} _pulwi) an integer to File i [ Fretc(i reads a character from file char ch; char ch, . —— putct) writes a character to [ile printf “\nEnter a) printt("\nEnter characler: "); a character: “k: Epute() writes a character to file ch = getcht); ch = getchet ts Egetst) reads string from a file, one line at a printf "\nEntered prinif(’n Entered ume characteris ec", chy, | character is tc", fputs() writes string bo a file return 1; chy, feof) finds end of file } return 1; fgetchar reads a character from keyboard a] Egetc() reads a character from file Output oof | Guipul of the above | Output oof the ay = Eprinitt) writes formatied data to a file example program is; above program is; Enter character: T Enter character: T Escantl] reads formatted data from a tile Entered characteris T | Entered character fgetchar reads a character from keyboard isT fputchar writes a character from keyboard i if = a a. seek} moves file pointer position to given : GQ. List any five library functions under stdio.h — location teen PMBSOL MO eee MN) [SEEK SET | moves file pointer position to the i ans: beginning of the file SEEK_CUR | moves file pointer position lo given Functlons under stdio.h Header File locati jocation - The stdio-h header file is referred as standard input SEEK_END | moves file pointer position te the end of output header file. This file includes standard macros fille. definition, constants and functions. felliy gives current position of file pointer - To perform all types of input oulpul operations it alse rewind(} moves file pointer position lo the includes the required dala type. beginning of the file = The most frequently used functions in stdioh file are: putct) swrites a charatlerba-file printf(),scanf(),putchri},getchart). sprint) writes formatied output ta string eee ea sscanfi) Reads formatted inpul from a string = Inbuill C functions in stdio.h file == removel) deletes a file ction Description flush) flushes a file printth print the character, string, float, integer, Rehan e nn adee See ee eee neon ae ee ee a octal and hexadecimal values on the GQ. List any five library functions under ctypeh | output screen : 2 scant) reads a character. string. numeric data Sn pea e DEH Va ots ns eT PASE ME from keyboard. M4] Ans. : getcth reads character from file Functions under ctype. h header file Exts() Feads line from keyboard ciyped file includes the functions which are used to Eetchart} reads character from keyboard manipulate characters. Some of them are explained below : pulst writes line Lo ofp screen (MU-Mew Syllabus wef academic year 19-20 )(h2-05) tl Tech-Neo Publications...A SACHIN SHAH Venture M1 Ans. : Purpose of math functions Function Purpose ceil(number) rounds up the given number. I retums the integer value which is greater than or equal to given number. Noor{number p rounds down the given mamber. It retums the integer value which is less than or equal to given mamber_ printfi"number rounded down $¢5.2if\n", down): printfi"number rounded up %¢3.2ifin", upt: primifi"sqquare rout of th mamber 5.21 is : 25.511", down, sqrlinumber) returns the square root of given number. pow base, retums the power of given number. exponent} abs(number) retums the absolute value of riven number. : GQ. Write a program which does following ‘ 1. Calculate absolute value of an integer number , ' and a long number : ‘ 2. Round down the number (Le. if input b+ 7 125.740, then the output should be 125.00) : . 3. Round up a number (Le. if input is 125.740, ; TENCUE SELES PCE SEO STOP LOOT? a Ans. : Program #include #include int main void) { long result; long x = 12345 int num = -1234: prnd(“rd is the alsolute value of integer: Sedin”_ abs! num) rum: abs tretums absolute value of an anieger result = Labeixt: prin Fld is the absolute vatue of ke double number = G20. double down, up: floor() ull rownd down the number ie. 3.8 down = Moornumlsert: hecomes 5.03 ceili} will round up the umber up = ceil(numbert: Le. 3.8 becomes O40 Gehdin*, resulta; sqprtichown bh; return U: } ‘Outpat + Reger ree | 1234 is the absolute value of in 24 234678 is the | absolute walue of long: -12345678 ‘iginal number 625.54 rounded down 625.00 Soware root of &h number 625.00 43 25..00000 Explanation - Here, x = -12345678L and num = -1234, So tw find absolute valuc of both following functions are used : - Labs{x) finds absolute value for long Le.= 12345678 and abs(num) finds absolute value for integer i¢.=1234 - Meert) will round the number 625.54 to 625 whereas. ceil() will round up the number 625.54 to 626. : ‘GQ. List any four library functions under stdlib.h H Looe besder fle. eee eee Mattel | © ans. : Functions under stdlib.h Header File - stdlib.h header file include general library functions for example: ane veeeet H string e.g. If Input string is abed then output will teoee be eeeioracersvocetereccers scene near? Ans. : Program #unchde #inchude #include swat) swaps char sourre[23] = "wSpal chS rtm 7: the bytes here it shader pull int maantvord) and store it into { target swaldsomree. Larget.strlenisourceyl: = prntfi"This is target: Gésin", target): return U; } (MU-New Syllabus wef academic year 19-20}M2-05) > Publicatons..A SACHIN SHAH Venture C Programming (MU-FE-Sem II} Output Explanation - swab() function accepts three arguments as source string, target string and length of source string - Here strlent is used to find the length of source which is bh. Swaps the source string as follows and store it in largel string = O 12 34 5 6 7 B BG 10 1912 13 ta 15 16 aa meisyeiate] felmjs}] Pefetejy [opol | J AAA 6 7 6 9 101112 13 141816 . 24 tsfefete] fitsfe] tsteyed tele] [| TJ Fig. 4.3.1 !GQ. Write a program to generate five random : : numbers from 0 to 35. _ 13 Marks) | M1 Ans.: Program ‘EF: #include #include =< atdietio int emazined vend ti int; print] five random numbers from te Pare cnn"; S limes loop wall be executed Forti { print" in" ich ; % A and) Se LU —) Prints random , numbers between return O; O1099 4) bitayyeheonec oat ee. five random numbers (Functions)...Paga no. (4-14) Explanation - For loop is used to call the ramd(} 5 times — sand() is a library function which is used Lo print the random values ‘GQ. Explain any two library functions under time.h | } header is M1 Ans. : Functions under tlme.h Header File time.h System lime. TL also contains functions which format the includes functions which manipulates the time while printing on the screen. Some of them are as follows ctlme(} clime() converts lime and date to string. The format of converted string is like. DDD MMM dd hh:mm:ss ¥Y¥YY where: DDD = Day(Mon, Tue, Wed. Thu, Fri, Sal. Sun) MMM = Moath(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Nov, Dec) dd = date (01,02,03JH,.. bh = Hour (01,02,03,04, ly 12) mm = Minutes(01,02,03,04 ,... 59) ss = Seconds(0102,03,04 ,... 59) YY¥YY = year Example The Oct 05 05:20:34 2017 strdate () It is used to convert the current date into string. The standard format of sirdatet) is: _sirdale(date}; This statement converts the current date into string and stores it into date. The length of date should be > characters long. The string date has following format: MM sD YY Where: MM = Month (01,02,....12) DD = Day (01,02,.....31) ¥¥ = Year(last two digits of year) (MU-New Syllabus wef academic year 19-20 )(M2-05) [al Tech-Neo Publications...A SACHIN SHAH Venture 1G Programming (MU-FE-Sem ly (Functions)....Page no. {4-16} ort bnitia wi 2 GQ. Write a function to calculate area ofa circle. F { } return a-h; i } M1 ans. : Output Program ; #inclucde #include Enter two inegers: float area(floalh; a int main vail) 1 a+b=15 a = Hd = 35 Alu rs a = . - . . 5 Ay nEnter cadious ef care a fb=2 prin scant" Pan); Explanation "Area of the circle is 83.20 area(el Accepts value of a and b from user ie. a= 10 and b=5 return O; main() } a b result Moat areal Aout 1) 10 5 —_ add(10,5) { iia) 7" : return re®3. 14; Io a } So result =15 Retumms 1045 =15 ‘Output Prints result ie. 15 anal subunSy inter radious of circle: result=sub(10,5) a b 10 5 of the circle is : 78.58 Retums |0h5 =5 Explanath janatlon. So result =5 Prints result ic. 5 - Here main() accepts radius from user ie. 5 mul 10,5) — Pass il to areaf bas ils argument. result= mul (10.5) a b - areatr) will suspend the execution of main(} and 10 5 transfers the control to function definition and copies 4 Returns 10*5 =50 into formal parameter of area{) ‘7 So result =50 Tt will calculate the area r?r*3.14 = 5*5*3.14 = TH50 Prints result ie. 50 and return the result back 19 maint). returned value is printed on screen ie. TH50 result= div 5 div( 10,5) Bei a a eS eee = aS ay CS) | GQ. Write program to reverse the number 1234 ° : * ow. (he, 43220 using function. , 10 5 rc ree re a So result =2 Returms [V5 =2 Prints result ie. 2 (MU-New Syllabus wef academic year 19-20 )(M42-05) ech-Neo Publications...A SACHIN SHAH Venture ‘C Programming (MU-FE-Sem i) (Functions)....Page no. (4-17) M ans. : Program #include int revrse (int al: int maint veicly { inf num; printf("\Enter an integers" | Obl a i scant(™ Srl" drmumb: , printf" reverse of entered number is: Sed", cian (a pc } Value of gum as cupid into a. —_ int revrse(inl nb 4 int new =O; Loop will execute ——* until n becomes 0. while (nt =O1 { rev =rev" 10 + gn 101: Hetam the reversed n=n/10; number to maim() i retum rev: } Explanation — User enters value for num = 687 - Revrse(num) passes the control lo function definition. And copies value of num ic. 687 into n. Iteration Ls Now rey=0, n=687 while(637!=0) )is truce so rey =rev * 104 (n5t10) = 0* 10 4(687%10)= 047 =7 n= 0/10 = 687/10 = 68 Lleration 2: Now rev=7_ n=6% while(68!=0) } is ruc so rev =rev * 104 (nS 10) = 7 * 10 +(68% 10) = 7048 = 73 n=p/10=68/10=6 Iteration 1: Now rev=70_n=6 while(6!=0) ) is true 30: rev =rev * 10+ (n€10)= 78 * 10+(6% 10) = T8046 = Th n=Wld=c/10=0 Iteration 4: mow n=0 (00>) és false so it will exit the loop - return rev will return the control back to main() and ; UQ. Write a program to calculate compound interest © My and amount. : ‘ Using formula A=P{1+R/100)*n, where } : P=Principal Amt, R is Rate of interest, + : n= number of years. Your program should make * . use ef user defined function to calculate power. ! i. Program should accept P, R and N, Display ! H interest earned for each year. 4 Ans. : Program #include #inchede < math b> maind) { oot RPAH: ant Nz foal comp_int_cale{ float Moat int): scanti™ed” & Ni: STER THE RATE OF INTE acanliGT £1: R=R/low, te: ‘Cl =comp_int_cale{P_R_N), LOULATED SIMPLE [INTEREST [5 RUPEES (MU-New Syllabus wef academic year 19-20(M2-05) Pal xecis-rico Publications... SACHIN SHAH Venture Programming (MU-FE-Sem tl) (Functions)....Page no. {4-19} ease 5: break: default: prinifi"in Invalid choice"); t ‘ t Output | Datestexe ~--Menu-- Addition Subtraction Multiplication Division STOP Select your choice : 1 unpbwh ” Enter two numbers :16 2 Addition is 12 Addition Subtraction Multiplication Division STOP Select your choice : 5 Vbw nN eee ne ee ne PH 4.4 SCOPE OF VARIABLES 1 GQ. Explain scope of variables with suitable example. ; emees:. M Ans. : Scope of varlables - In € variables are used to store dala. Every variable has ils scope means it can be used only by the block in which it is declared. Olher codes can't access that ime of that variable. This is referred as scope and fii variable in the program. — Scope of the variable defines certain area in which the variable is accessible. Types of varlables - Wariables can be of two types. 1. Global varlables 2. Losal variables Fig. 4.4.1: Types of variables boo. Global variables Scope of the global variable is throughout the program ie. every function in the program can access that variable. Global variables are declared outside all the function (ineluding maint}. > 2 Local variables Scope of the local variable is limited to the function in which il is declared. Other functions can't have access. to that variable. Local variables are declared within function. To understand the scope of variables see Program 5.8.1 Example #incluce void display int a); Global variable Loew van inl i = 20; ———# Je ol main() prinifi"In main(t function in a= Sedin i=l" ai; displayiil: vi; rel } void display! int j1 { inl k = 3a: + Local variables of display) printfi"indn display () function in a=Sedin j= Sedin k=", aks IMU-New Syllabus w.e.f academic year 19-20 (h42-05) Tech-Neo Publications...A SACHIN SHAH Venture (G Programming (MU-FE-Sem Il) (Functions)....Page no. (4-20) Outpat Pe) 3 In dusplay(] tunection aso Explanation - In this program, a is global variable so it can be accessed by both main) and displayi | functions. - iis local variable of main() function so it is only accessible by maini) itself. We pass value of i to display() function. = kand j are local variables of display function. RECURSIVE FUNCTIONS UG. Explain recursion concept [LUE Bemracu cd | ’ OR What do you mean by recursion? : ' MU - Dec.17, 2 Mark [eae een eee 1 ans. : Recursive function - The process of calling a function inside itself is called as recursion. The function which calls itself is referned as recursive function. - Recursion is the process of defining something in terms of itself I is lithe bit difficult to understand the recursion but in some cases it provides betier solution than looping. Y& 4.5.1 Advantages of Recursive Functions Advantages of recursion - = Recursive function has following advantages. - Whelps to reduce the time complexity of program - [helps to reduce the length of program. - Whelps in code reusability. - = Reduce unnecessary calling of function. — Throwgh Recursion one can solve problems in easy way while its iterative solution is very big and complex. TW 4.5.2 Disadvantages of Recursive Functions — Recursive solution is always more logical and it is very difficult to trace (debug and understand). - In recursive we must have an if statement somewhere fo force the function to return wilhout the recursive call being executed, otherwise the function will never return. - Recursion takes a lot of stack space, usually not considerable when the program is small and running on aPC. - Recursion uses more processor lime. YW 4.5.3 Programs on of Recursive Functions ; UQ. Write a recursive program te calculate factorial - i sfaccepted number. (LRA ris iy 1 Ans. : Program #include int Eecttint): mi nf ponlf ( “nEnter any number ™ } : scanf { “Cod™_ dn } = f= Gein}: (Factorial value Suspend execution of main) and transfers control to detiniion val Fact() and passes return 1; value of nlo nom, } —_) ant fect (ont mem (MU-New Syllabus w.ef academic year 19-20 (M42-05) Tech-Neo Publications... $.4CHIM SHAH Venture