0% found this document useful (0 votes)
22 views17 pages

Img 2491

Bca C notes

Uploaded by

srigopi1415
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)
22 views17 pages

Img 2491

Bca C notes

Uploaded by

srigopi1415
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/ 17
sf10NALICONTROL sr, ‘ATEME| NTS, goto break: wate tat 2 £010 BTeaKS the no the oe Roto label: a lone iy. Such a jump is known » rept ter the goto label; some se al Sequential nese P Will be f execution, : formed of the progra S a Backward fase Sie ae eM eee atement will be akfo ory ome bi a ill be ee Skipped and the ju ‘and, if the label: is ie jump is known as a etomen fo read further data float yi read: printf('Enter number to get its -"); ue eee get its square root: "); ‘f(x <=0) goto read; y= sqrt); printi('Square root of %d is %.2f", x, y)i etch); return 0; } Output: Enter number to get its square root: 16 Square root of 16 is 4.00 4 a the above program a number is 2 to or less than 0, the goto statement Prompted from the user. This continues till a p* calculated. When the input is read and square root pack to the line where input transfers the control ositive number is provided, 2.3.1(Function Basics ae are many situations wht once in a es may lead to ere we might need to unnecessary EN _eceiilileaa srovides an approach in Which y, anguazeP is ogeammet 50; CIS ne form of a function and it can by ep? Calg a ma 3 = at ge ag it as aS User defined Predelned J User: oe bons, 10 jesse neti: a ey es ear’ 4 Library functions are those functions which are already defined in C library, example q printf(), ea strcat() etc) You just need to include appropriate header files to use these 4 functions. These are already declared and defined in C libraries. 2.3.2(User Defined Functions > e ! 4 User-defined functions on the other hand, are those functions which are defined by ie the user at the time of writing program. for saving time and space. ) In C every user defined function must be declared make function call the function definition gets executed, following program in which we create afucntion called adit a return value. — Example Program: These functions are made for code reusability and TJ coNDETaUnns wr ene STATEMENTS giz TES) een getcn0 } JpraaastonGnta int) // function definition [ return a+b 7 1 a ‘output: Enter any two integer numbers : 10 20 sum = 30 bove example : sa Bie that ae oe the function declaration statement "int addition(int,int)" tells ee chan: is a function with name addition which takes two integer values as param 2 s an integer value. The function call statement takes the execution control to the additon() definition along with values of num1 and num2. Then function definition executes the code written inside it and comes back to the function call along with return value. ‘ In the concept of functions, the function call is known as "Calling Function” and the function definition is known as "Called Function". When we make a function call, the execution control jumps from calling function to called function. After executing the called function, the execution control comes back’to calling function from called function. When the control jumps from calling function to called function it may carry one or more data values called “Paramenters" and while coming back it may carry a single value called "return value’, That means the data values transferred from calling function to called function are called as Parameters and the data value transferred from called funcion to calling function is called Return value. (unetion declaration/ prototype General syntax for function declaration is, \Natimntype FanctionNName(ypel parameter), type2 parameter.) ‘a function must also be declared before its used. Function about the function name, parameters is accept, and its function can be defined separately. It's also called as tion consists of 4 parts. . Like any variable or an array, declaration informs the compiler tetum type. The actual body of the Function Prototyping. Function declaral > returntype > function name > parameter list ® ‘terminating semicolon TT returntype) form some sort of cae pasty Cera a When a function is declared to pe! in such cases, a retu add ones provide with some result at th type of value(int, float, char, doubj yecifies the tyP* fs atthe end of function body (Retuen POP gy wich called the function.) that function is expected to return to Id bi A ‘ranation doesn’t return any valu, the rerum, type would be void. Note: In case a function does Cc functionName ) Function name is an identifier and it spec name is any valid C identifier and therefore mus| variables in C language.) >( parameter list) (the parameter list declares the type and number of arguments that the function when it is called) Also, the parameters in the parameter list receives the argument val when the function is called. They are often referred as formal parameters. ifies the name of the function. The funeti {follow the same naming rules like ec terminating semicolon Function declaration has to terminated with a semicolon. > (Function definition") (The function definition or function body contains the declarations and the statements(algorithm) necessary for performing the required task. The body is enclosed within curly braces {..) and consists of three parts.) ce local variable declaration(if required). . function statements to perform the task inside the function. 3. a return statement to return the result evaluated by the functionif return type is void, then no retum statement is required). i f | (Return values and their types ) a es arty oe my not return a result. But if it does, we must use the retum nt to output the result) return statement also end. i i a must be the last statement Of any eeu es function: If i statement, it won't be executed?) 2 bau owig any; statement after the rerun) Mii conpsTTONAL CONTROL STATEMENTS #includecstdioh> ‘multiply{int o, int b); maing) ragalt = multpty, + int muttiply(int a, int b) ) the datatype of the value returned using the return statement should be same as the eum type mentioned at function declaration and definition’ If any of it mismatches, you fallget compilation error. > on the data flow between the calling function and called function, the functions axe dassified as follows 1, Function with no arguments and no return value 2, Function with no arguments and a return value — 3, Function with arguments and no return value 4, Function with arguments and a return value 2) Function with no arguments and no return value Such functions can either be used to display information or they are -ompletely’ dependent on user inputs. ©) Below is an example f a function, which takes 2 numbers as input from user, and display which is the greater number. f Output: Enter 2 numbers that you ‘The greater number is: 45 _ Function | with no argum: ts and return value example to make the function greatNum() return t We have modified the above exam which is eet nimbers. Output: Enter 2numbers that you wapt to compare 25.45 NAL CONTROL STATEMENTS conprtt eee { if(x>y) : prin{("The greater number 9d", md", YY printf("The greater number is: } J Output: Enter 2numbers that ‘The greater number is: 45 ‘you want to compare: 25 45 iG Function with arguments and a return value “This is the best type, as this makes the function completely independent of inputs outputs, and only the logic is defined inside the function body. #finclude finclude int greatNum(int a, int); // function declaration. intmain() [ inti, j, result; printf("Enter 2 numbers that ‘you want to scanf("Y%od%d”, &i, &); compare: ae sreatNum(i,)); // function call Printf("The greater number is; 9d" getch0; ed", result); return 0; int cae Heese // function definition if(x>y) { return x; yr qsssrtonae CONTROL STATEMENTS te enter 2 numbers that you want to compare: 25 45 chegreater number is:45 : esting of Functions iG pee a ee nesting of functions ie to call oe Functibn inside another ancion’s body: e careful while using nested functi i jnfinite neStINE- ‘S tions, because it may lead to fanction10 ( // fanction! body here function2(; // function! body here ! iF function2() also has a call for function}() inside it, then in that case, it will lead to an iafrite nesting. They will keep calling each ‘other and the program will never terminate. Tuts consider that inside the main() function, fanction1( is called and its execution sare, hen inside function, we have a call or fanction20, 50 the control of program wilt goto the function2(). But as function2() also thas a call to function1() in its body, it wil call fureion10, which will again call function2() and this will go on for infinite times, until You forcefully exit from program execution. (Function call When a function is called, control of the PrOBT= gets transferred to the function. >) fantionName(argumentl, argumen®,-)i Se fant Inthe example above, the statement ‘multiply(,j); inside the ain( function is function ie to a function! QOpnpward Communication TP this type of inter function communicatio 2 n, the data i Factor Gs calcd function but not onan Culine. am ae ction. e pus oNAECONTEOL Saran eer ws wen sh ectetathecac ot ary re function along with oa “onand finally comes bi ly comes back to dept consider the following ee calling function without any return value. F pample Program: fain Jpocudecconiol> jon, the execution control jumps from void mainO ( int uml, num? ; ‘void: addition(int, int) ; // function declaration dirser) ‘num? = 20; ‘nfc\nBefore swap: numl = Yd, num? =%d", num, num2) ; viiiton(nuuml, num2) ;// calling function : getch) } oid addition(int a, int b) // called function { printf("SUM = %d", a+b) ; ) Output: Enter any two integer numbers : 1526 SUM=41 ce Upward Communication Sy i data is transferred from called function (fn this type of inter-functis is to calling-function but 1 oo te called-function. The functions without parameters and with return value are considered under upward ‘communication. In the case of upward communication, the execution control jumps from calling-function to called= function without parameters an‘ “executes the function definition, the calling function along with 2 return value, For example, consider —= | CONDITIONAL CONTROL States, nee Example Program: Hincludecstdioh> #inelude void main) t int result; : intaddition( ; // function declaration clrser) result = addition() ; // calling function rintf(’Sum = %a', result); etch ; } intaddition) // called function ' int num, num2; ‘num = 10; ‘num? = 20; retum (num1+num2); = Enter any two integer numbers : 15 26 Sum =41 > (Bi- Directional ) Example Program: #include #include coNDsTIONAL CONTROL STATEMENTS oe EEE (enum, umd, result FpraaatonGint in); // Fonction declaration rst punt = 107 pum = 20; enitaddition(our, num2); // calling funct Enter any two integer numbers : 15 26 Sum = 41 2.3.4\Standard Functions ) .e functions which are already defined in C library, Gtandard (Library) functions are thos example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these functions, These are already declared and defined in C libraries. ‘A User-defined functions on the other hand, are those functions the user at the time of writing program. These functions are made for for saving time and space. which are defined by code reusability and Mathematical functions ey The header file rath h in the standard library of C programming language designed for baie mathematical operations) (ost of the functions involve the use of floating point a C++ also implements these functions for compatibility reasons and declares them inthe header emath, All functions that take or return an angle work in radians. Gi these functions take doubles for floating-point arguments, unless otherwise specified\To work with floats or long doubles, append an for an Ito the name, respectively. —_ SS ee i ‘ ime an, ‘Glick the time function of your choice to i date output. "€ to see a source code \Cexample: aversion Functions: 4 asctime() - Convert tm structure to stri . ctime() - Convert time_t value to aoe gintime()~ Convert calendar time to Ux « localtime()- Convert calendar eee Ss x strftime() - Format date and time re asctime( ) : Convert tm structure to string ‘syntax of asctime() = asctime (const struct tm * ptr_time); Parameters: ptr time is a pointer to a tm structure which in turn contains a calendar time. Return Value: ‘The function returns a C string containing the date and time information. The string is followed by a new-line character ('\n’) and the terminating nuull-character. time and asctime share the array which holds this string. If either one of The functions ct these functions is called, the content of the array is overwritten. structure as calendar time and The function asctime( ) interprets the contents of the tm s\ converts it to a string. The returned string contains a human-readable version of the date and time. The string that is returned will have the following format: www mmm dd hh:mm:ss YYVY www = which day of the week. mmm = month in letters: dd = the day of the month. hh:mm:ss = the time in hout, minutes, seconds. yyyy = the year. _ CONDITIONAL CONTROL STATEMg, 1=24 For example, ‘A function to evaluate factorial Of #includecstdioh> ffinclude Int factorial(int x); //declaring the funclo® int main() ( a,b; printf(Enter a number: "); scanf(“%d", &a); : b= factorial(a);.//calling the function named. factorial printf("Factorial of Ye is %d, a,b); etch; return 0; a int factorial(int oe the function intr=1; f= 1) else 1 =x*factorial(x-1); 4 //recursion, since the function calls itself I Output: Enter a number: 5 Factorial f5is 120 >" Nee ‘. us See how the recursion works. Assume n = 3. Since the vs statement fact = x"* factorial (x= 1); will be executed with x = 3. That is, fact = 3 * factorial (2); oNDETIONAL CONTROL STATEMENTS Pont 2.50 | session on the right-hand side includes a call to factorial with x = 2. This call will return. eProllowing value: 2*factorial(1) S te i ey ee ae This time, the function returns 1 . The sequence supe = 3* factorial(2) = 3*2° factorial(1) = 3*2*1=6 of O Recursive pecans a be oT used to solve problems where solution is expressed in terms of successively applying the same solutions to subsets of the problems. We defn’ and extern. (Gere are two different ways to characterize variables: by data type, and by storage cas. Data type refers to the type of information represented by a variable, e.g., integer umber, floating-point number, character, etc. Storage class refers to the permanence of a {arable and its scope within the program, ic,, the portion of the program over which the ‘aiable is recognized") Chere are four diferent storage-class specification in Care: 1. automatic, 2. external, 3. static and 4, register (@heyare identified by the keywords auto, extern, cad Peace static, and register, respectively. =) Figure: Storage class Spectors + Gunatian and are local to the function

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy