0% found this document useful (0 votes)
3 views47 pages

Chapter 5

The document discusses the concept of functions in C programming, emphasizing their importance in organizing code through modularity and reusability. It distinguishes between library functions and user-defined functions, explaining their definitions, advantages, and examples. Additionally, it covers function components, calling conventions, argument passing methods, and the differences between global and local variables.

Uploaded by

Romharsh Oli
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)
3 views47 pages

Chapter 5

The document discusses the concept of functions in C programming, emphasizing their importance in organizing code through modularity and reusability. It distinguishes between library functions and user-defined functions, explaining their definitions, advantages, and examples. Additionally, it covers function components, calling conventions, argument passing methods, and the differences between global and local variables.

Uploaded by

Romharsh Oli
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
UNITS Functions y Function is a self -contained block of code or statement that performs @ particular task. > Every program must contain one function named main() from where the program execution begin > Complex problem can be solved by breaking them into set of sub-problems, called modules or functions. This technique is called divide and conquer. Each module can be implemented independently and later can be combined into single unit. Advantages of function /Importance of function > Functions in Programming help break down a program into smaller, manageable modules. Each function can be developed, tested, and debugged independently, making the overall program more organized and easier to understand. > Different programmers working on one large project divide the workload by writing different functions. A single function can be used multiple times which avoids rewriting of same code again and again. Program that use functions are easier to design debug and maintain. v v > Functions in Programming allow programmers to abstract the details of a particular operation. A programmer can use a function with a clear interface, relying on its functionality without needing to understand the internal complexities. isadvantages It increase the execution time because when function is called the control have to jump to function definition to perform the particular task, and after completion of task , control again come back to the function call. Assignment: ¥ What do you mean by functions in C programming? ¥ Without using functions also, we can write a program. But we need functions in our program. What are the benefits of using them? Types of functions C functions are classified into two categories. They are: 1. Library function These are the functions which are already written, compiled and placed in C Library and they ere not required to be written by a programmer. The function name, its return type, their argument number and types have been already defined. We can use these functions as required by just calling them. For example: printf(),scanfl),sqrt(),getch() are examples of library functions The library functions are also known as bullt-In functions and they are defined within a particular header file. 2. User defined function These are the functions which are defined by user at the time of writing a program. The user has. choice to choose its name, return type, arguments and their types. eg. int sum(int aint b).The task of each user-defined functions is as defined by user. A complex C program can be divided into number of user-defined functions. Differentiate between library functions and user-defined functions with examples. Library functions User defined functions 1. They are predefined functions/built in functions in C library, 1L They are the function which are created by the user as per his own requirements. 2. They are the part of header files (such as stdio.h, conio.h, math.h) which are called during runtime. 2. They are the part of program which is compiled at runtime. 3. The name of function ID is given by developers which can’t be changed. 3. The name of function id is declared by user which can be changed. 4, The function’s name, its return type, their ‘arguments number and their types have been already defined . 4, The user has choice to choose function name, its return type, number of argument and their types. [Link]. printf(),scanfl),sart() pow(),clrscr() etc. [Link]. int fact(int n), float sum(float xfloat y) Program to illustrate use of user defined function and library function: finclude fincludecmath.h> int square(int); int main() { int num=5,result; printf("Square of number using library function =9%d\n",result); result= square(num); printf("Square of number using user defined functior } int square(int x) { return (x * x); } Output: ‘Square of number using library function=25 1=-%d" result); Square of number using user defined function=25 Components associated with function 1) Function definition The collection of program statements that describes the specific task to be done by the function is called function definition. It consists of: Function header: which defines function’s name, its return type and its argument list, Function body : which isa block of code enclosed in parenthesis. Syntax: return_type function_name(data_type varibalet,data_type variable2,....,data_type variable n) { statements ; return value; t Note: If a function doesn’t return any value, then its return type is void Syntax: void function_name (data_type varibale1 data_type variable2, { statements ; data_type variable n) + 2) function declaration /function prototype ‘The function declaration or prototype is a blueprint of a function. If a function is used before it is defined in a program, then function declaration is needed to provide the following information to the compiler. > The name of fun: > The type of the value returned by the function > The number and type of arguments that must be supplied while calling the function. The syntax for function declaration is return_type function_name(typet, type2 ,type3 ....... type n); Here, return_type specifies the data type of the value returned by the function. A function can return value of any data [Link] there is no return value, the keyword void is used. The function declaration and declarator or header in function definition must use the same function name, number of arguments, argument types and return types. Some examples of function declaration are: int add(int a,int b); float simple_interest(); int factorial(int n); Note: The terms’ function declaration and function prototypes are often used interchangeably but they are different in the purpose and their meaning. Following are the major differences between the function declaration and function prototype in C: Function declaration Function prototype Function Declaration is used to tell the existence of a function. The function prototype tells the compiler about the existence and signature of the function. ‘A function declaration is valid even with only function name and return type. ‘Typically used in header files to declare functions. ‘A function prototype is a function declaration that provides the function’s name, return type, and parameter list without including the function body. Used to declare functions before their actual definitions. Syntax: feturn_type function_name(); Syntax: return_type function_name(parameter_list}; 3) Calling a function When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function- ending closing brace is reached, it returns the program control back to the main program. A function can be called by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. For example, the function add{) with two arguments is called by add(a,b) to add two numbers. During function call, function name must match with function declaration name, the type of return type, the number of arguments and order of arguments 4) Return statement: The job of return statement is to hand over some value given by function body to the point from where the call was made. The function defined with its return type must return a value of that type. For example: If a function has return type int, it returns an integer value from the called function to the calling function. The main functions return statement are: ‘« Itimmediately transfers the control back to the calling program after execution of return statement (ie. no statement within the function body is executed after the return statement.) ‘« Itreturns value to the calling function. The syntax for return is: return (expression); Where expression must evaluate to a value of the type specified in the function header for the return value 5) Function Arguments Explain formal arguments and actual arguments with an example program. Arguments enable data communication between the calling function and the called function. They are classified into actual arguments and formal arguments: Actual Arguments: Y These are the values or variables passed from the calling function to the called function. Y They are specified in the function call. Formal Arguments: Y These are the variables defined in the function definition to receive data sent by the calling function Y They can also be used to send data back to the calling function, For example, in a function, a and b are actual arguments passed during the function call, while x and y are formal arguments used in the function definition to process the received values. Program Hincludesstdio.h> int summ(int int); //function declaration int main() { int a, byresult; printf("Enter the first number\n"); scanf("%d" 8a); printf("Enter the second number\n"); scanf("96d", 8b); /* Calling the function here, the function return type is integer so we need an integer variable to hold the returned value of this function. v result =sum(a,b); /*actual arguments a and b are passed in calling function */ printf ("Sum of two numbers= %d, result); return 0; /*formal arguments x and y are passed in called function*/ int sum(int x, int y) _//function definition { int r; Ay /* Function return type is integer so we are returning an integer value, the sum of the passed numbers. “ return r; } Passing argument to function ¥ Distinguish between call by value and call by reference with examples. ¥ How arguments can be passed by using call by value and call by reference? Explain with examples. ¥ Explain the call by value and call by pointer with suitable example. The arguments in function can be passed in two ways, namely call by value and call by reference. Function call by value (or pass by value) > Inthis method the value of each actual arguments in the calling function is copied into corresponding formal arguments of the called function > With this method the changes made to the formal arguments in the called function have no effect on the values the actu[al argument in the calling function. Hinclude void swap(int x,int y); int main() { int a,b; a=10; 0; printf("Value before swapping a=94d and b=%d\n",a,b); swap(e,b; printf("Value after swapping 2=%d and b=%d\n",a,b); return 0; } void swap(int x,int y) { int temp; tem Output: Value before swapping a=10 and b=20 \Value after swapping o=10 and b=20 Explanation: In this example, the values of @ and b are passed in function swap() by value. The value of a is copied into formal argument x and value of b is copied into formal argument y. The copy of value of [Link] b to xand y means the original values of a. and b remain same and these values are copied into the variables x and y also. Thus when x and y are changed within the function, the values of the variables x and y are changed but the original value of a and b remains same. Function call by reference (Or pass by Reference] > Inthis method the address of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses the actual arguments can be accessed. In call by reference since the address of the value is passed any changes made to the value reflects in the calling function. v #include void swap(int *x,int *y); int main() printf("Value before swapping a= swap(&a,&b); printf('Value after swapping a=%d and b=%d\n",a,b); return 0; } sd and b=%d\n",a,b); void swap(int *x,int *y) { int temp; *ystemp; } Output Value before swapping a=10 and b=20 Value after swapping a= Explanation: in this example, the address of variables (ie. &a and &b) are passed in function .These addresses are received by corresponding formal arguments in function definition. To receive addresses, the formal arguments must be of type pointers which stores the address of variables. The address of a and b are copied to the pointer variable x and y in function definition. When the volues in addresses pointed by these pointer variables are altered, the values of original variables are also changed as the content of their addresses have been changed. Thus, while arguments are assed in function by reference, the original values are changed if they are changed within function. Category of functions Function can be categorized in four types, on the basis of arguments and return value. ‘Function with no arguments and no return values [Link] with arguments but no return values [Link] with no arguments but with return values [Link] with arguments and return values 1. Function with no arguments and no return values When a function has no arguments, it does not receive any data from the calling function. Similarly, when it doesn’t return a value, the calling function does not receive any data from the called function, Thus in such type of functions, there is no transfer between the calling function and the called function. This type of function is defined as. void function_name{ ) { /*body of the function*/ } The keyword void means the function does not return any velue. There is no arguments within parenthesis which implies function has no argument and it does receive any data from the called function. Program to i tion with no arguments and no return value Hinclude void sum(); int main() { sum(); return 0; } void sum() { int xy.r3 printf("Enter the two numbers\n"); scanf("%d%d", 8x, 8y); rexty; printf("The sum of numbers=%d",r); } 2. Function with arguments but no return value These type of function has arguments and receives the data from the calling function. The function completes the task and does not return any values to the calling function. Such type of functions are defined as, void function_name(argument list) { /*body of function*/ Void sum(int x,int y); int main() { int a,b; printf("Enter the two numbers\n"}; scanf("%d%d", &a,8b); sum(a,b); return 0; } void sum(int x,int y) { intr; rexty; printf("The sum of numbers=%d\n".r; } 3. Function no arguments but with return values These type of function does not receive any arguments but the function return values to the ing function. Such type of functions are defined as return_type function_name() { /*body of function*/ } Program to illustrate the “f #include int sum(); int main() { int result; result=sum(); printf("The sum of numbers=%d" result); return 0; } int sum() { int [Link] printf("Enter the two numbers\n"); scanf("%d%d", &x,&y); raxay; return r; 4. Function with arguments and return value The function of this category has arguments and receives the data from the calling function. After completing its task it returns the result to the calling function through return statement. Thus there is date transfer between called function and calling function using return values and arguments. These type of functions are defined as, return_type function_name(argument list) { /*body of the function*/ Pr fHinclude int sum(int x int x); int main() { int a,b,result; printf("Enter the two numbers\n"); seanf("%d%d", &a,&b); result=sum(a,b); printf("The sum of numbers=%d" result); return 0; } int sum(int x,int y) return; } Global vs Local va Global variables: Global variables are accessible to all functions defined in the program. Global variables are declared outside any function, generally at the top of program after preprocessor directives. It is useful to declare variable global if it is to be used by many functions in the program. The default initial values for this variable is zero. The lifetime is as long as the program execution does not come to an end. Local variable: The variables that are defined within the body of a function or block and local to that function or block only are known as local variables. The name and value of local variables are valid within the function in which it is declared. They are unknown to other. The local variables are created when the function is called and destroyed automatically when function is exited function. Example: Hinclude void fun(); int x=5; {/global declaration int main() { int a=10; {Nocal declaration printf("Value of x=96d,a=%d\n" xa); fun(); retumn 0; } void fun() { int b: {/local declaration printf("Value of x=%d,b=%d\n",x,b); } Output Value of Value of x=! Here x is global variable and both main (| function and fun() function can access them. a and b are local variables a can be accessed by only main() function and b can be only accessed only by fun() function. Storage classes in C What do you mean by storage class? Explain different types of storage classes in C? Use examples to illustrate. Write a short note on: storage class in c? In C language, each variable has a storage class which decides the following things: ‘© Scope: where the value of the variable would be available inside a program. © Default initial valu we do not explicitly initialize that variable, what will be its default initial value. «Storage location of that variable «Lifetime of that variable: for how long will that variable exist ‘Syntax: storage_class_specifier type_specifier variable_name Storage location | Default intial | Scope Lifetime value Auto | Memory Garbage value | local to function in | Till control which variable is | remains within defined. block where it is defined register | CPU register | Garbage value | local to function in | Till control which variable is | remains within defined. block where it is defined Static Memory Zero local to function in | Value of the which variable is | variable persist defined between int main() { register int i; for (I=0;i<5;1++) ( printf("96d\t", i); } return 0; } Output o 1 2 3 4 3. Extern storage class Y Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. ¥ External variables share the variables among the multiple C files. ¥ Ittells the compiler that the variable exists and its definition can be found in another source file. Storage Locetion | Memory Default initial value | Zero Scope (Global) Everywhere in the program Life time {As long as the program execution doesn’t come to end. Example 1: somefile.h ‘int num=! demo.c Hinclude include "somefile.h" int main() { extern int num; printf("value of num=%d",num); return 0; } From the above-given program, we are trying to access the extern veriables in the demo. file, which is declared in the program somefile.h. Output: value of num=5 4, Static variables (static storage class) ‘A static variable tells the compiler to persist/save the variable until the end of program. Instead of creating and destroying 2 variable every time when it comes into and goes out of scope, static variable is initialized only once and remains into existence till the end of the program. Storage Location Memory Default initial value | Zero Scope local to function in which variable is defined. Life time Value of the variable persist between different function call Example: Hinclude void increment(); int main() { increment(); increment(); incrementt); increment{);, return 0; } void inerement() { static int i= 1; printf ("séd\t 1) Difference between extern and global variables Extern global extern is only a declaration, meaning it tells, the compiler that a variable exists elsewhere, but does not allocate or initialize it. Aglobal variable is both declared and defined within the same file, thus it has both storage and an initial value. ‘extern provides access to @ variable defined elsewhere (between multiple files). ‘A global variable is defined in the current file or translation unit and has global visibility within that file. extern is useful for inter-file communication global variables are used for data shared across different parts of a single file or throughout the entire program. Does not allocate memory, Allocates memory and store the value. Preprocessor directives What is preprocessor directive? Preprocessor is a program that process source code before it passes through the compiler. It operates under the control of which is known as preprocessor directives. Preprocessor directives are preceded by a hash (H) sign Preprocessor directives are often placed in beginning of program before main function. No semicolon (;] is expected at the end of the preprocessor directive. Example: include Hdefine Hitdet undef if Helse Hendif We use preprocessor directive for 1. File inclusion Source code of the given “filename” is included in the main program in specified place. Syntax: #include Hinclude “filename” Egtinclude 2. Conditional compilation Set of commands are included or excluded in source program before compilation with respect to condition. Eg. tifdet Returns true if this macro is defined ifndef Returns true if this macro is not defined if Test if compile time condition is true Helse The alternative for if Hendif Ends preprocessor conditional 3. Macro expan: n Macros are a piece of code in a program which is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. ‘The ‘#define’ directive is used to define a macro. Eg. define PI 3.1415 Here, when P! is used in program its value is replaced with 3.1415 MACROS Write a short notes on: macros A macro is a fragment of code which has been given a name. Whenever the name is used, its replaced by the contents of the macro. Macro is defined by #define directive. fidefine macro_name macro_expansion ‘* macro_name is any valid C identifier, and it is generally in capital letters to distinguish it from other variables. © macro_expansion can be any text There are two types of macros: 1) Object-like Macros The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example: #define 13.14 Here, Pl is the macro name which will be replaced by the value 3.14. Example include define PI3.14 int main() { float rarea; printf("Enter the radius: scanf("96"", Bt}; are rer; printf("Are: return 0; 2) Fun n-like Macros The function-like macro looks like function call. For example: Htdefine max(a,b) ((a)>(b)?(a):()) Here, maxis the macro name. fincludecstdio.h> ##define max(a,b) ((a>b)?(a):(b)) int main() { intab; printi("Enter the two numbers\n"); seanf("s6d%a" a, &b); printi("Maximum number= return 0; 1d" max(a,b)); Differentiate between macro and function. Macro Function 1. Macro is preprocessed. 1. Function is compiled. 2. Before Compilation macro name is 2. During function call , Transfer of Control replaced by macro value. takes place 3. Macros are faster in execution than 3. Functions are bit slower in execution. function. 4. Useful where small code appears many 4, Useful where large code appears many time time 5. Generally Macros do not extend beyond | 5. Function can be of any number of lines one line 6. Increase the program size. 6. Makes program smaller and compact. 7. Macros do not check for compilation 7. Function checks for compilation error error which leads to unexpected output. and there is a less chance of unexpected output 8._ Macro can’t call it recursively &._ Function can call it recursively. 9. Amacro is defined using #define 9. A function is defined outside main preprocessor directive. Therefore it is program. It is processed after preprocessed before submission of submission of source code to compiler. source code to the compiler. Example: Program to find the square of a number by using both macro and function #include define NUM 5. define square(num) (num*num) void func|); int main() { printf("Square of number using macro=%d\n",square(NUM)); fune(); return 0; } void func) { Int result,a=5; result=a%a; printf("Square of number using function=%d"" result); } Output: ‘Square of number using macro=25 Square of number using function=25 Header files in C Aheader file isa file with extension .h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler. Including a header file is equal to copying the content of the header file but we do not do it because it will be error-prone andit is not a good idea to copy the content of a header file in the source files, especially if we have multiple source files in a program. Both the user and the system header files are included using the preprocessing directive include. Ithas the following two forms : Hinclude This form is used for system header files. It searches for a file named 'file'in a standard list of system directories. #tinclude “file” This form is used for header files of your own program. It searches for a file named ‘file’ in the directory containing the current file. Why header files in C are included in program? Give reasons. Also list out different header files you know. Illustrate the program showing the use of header file. Header files are the special files which stores the predefined library functions. Suppose if we are using printf() & scanf() functions in your program then we have to include header file. It is for standard i/o. If we don’t include the the header files we can’t run our program. Therefore we have to include the header files. Another header file is #include which is for console i/o. This header file stores clrscr(| & getch() functions. clrscr{) is for clearing the screen & getch() is holding the screen until we press any single character from keyboard. Also we have lots of different header files which stores different functions Header file function #includessidio.h> | Used to perform input and output operations in C like scani() and printi(). #include | Perform string manipulation operations like strlen and strepy #include | Perform console input and console output operations like crscr() to clear the screen and getch() to get the character fram the keyboard. #include | Perform standard utility functions like dynamic memory allocation, using functions such as malloc() and calloc(). #includecmath.h> | Perform mathematical operations like sart() and pow/). To obtain the square root and the power of a number respectively. #include | Perform signal handling functions like signal() and raise(). To install signal handler and to raise the signal in the program respectively #includecerrno.h> | Used to perform error handling operations like errno(). Program to illustrate the use of header file Hinclude fHinclude includesmath.h> int main() { int num, result; printf("Enter the number"); scanf("%d",&num); result=pow(num,2); printf("Square of a given number is %d" return 0; } Here, Function used Header file must included to use function printfl) and scanf() | stdio.h pow() math.h getch() conio.h Recursive function (Nesting of function) A function that calls itself is known as a recursive function. Recursion is a process by which function calls itself repeatedly until some specified concition will be satisfied. To solve a problem using recursive method, two conditions must be satisfied. They are 1. Problem could be written or defined in terms of previous result 2. Problem statement must include stopping condition Advantages > Avoid unnecessary calling of functions. y big and complex Reduces time complexity. Using recursion, the length of the program can be reduced Extremely useful when applying the same solution repeatedly. vy y isadvantages v y For each step we make a recursive call to a function. For which it occupies significant amount of stack memory with each step. Its usually slower due to the overhead of maintaining the stack May cause stack-overflow if the recursion goes too deep to solve the problem If the programmer forgets to specify the exit condition in the recursive function, the program will execute out of memory. v vy Through Recursion one can solve problems in easy way while its iterative solution is very Recursive solution is always logical and it is very difficult to trace. (debug and understand). 1. Write to find the factorial of a given number using recursive function. Hinclude Jong int fact{int n); int main() { intnum; long int f; printf("Enter the number\n"); scanf{"ssd", &num); f=fact(num); printf("The factorial of a given number is %ld! return 0; } long int fact{int n) { if(n==1 | { return 1; } else { return n*fact(n-1); } } 2. Write a program to find the sum of first n natural number using recursive function. Hinclude int snatural(int n); int main() { int num,s; printf("Enter the value of n \n"); scanf("%d",&num); s=snatural(num); printf("The sum of n natural number is %d",s); return 0; } int snatural(int n) { if(ns { return 4; } else { return n¢snatural(n-1); } ) 3) Write a program to generate the Fibonacci series upto nth term using recursive function. Fibonacci series is 0,1,1,2,3,5.. Hinclude int fibjint int main() { int n,result,i; printi("Enter how many terms you want to generate\n"); scanf("séd",&n); forlizO;icn;i++) printi("%d\t" result); } retum 0; } int fibjint n} { if (n: { return n; } else { return(fib(n-1) + fib(n-2)); } } 4) Write a recursive program to generate the first 15 numbers of Fibonacci series. include int fib(int n); int main() { int iresult; for(i=0;i<15;i++) printf("%d\t",result); } return 0; int fib(int n) { if (n==0| |n==1) { return n; } else { return(fil(n-1) + fib(n-2)); } 5) Write a recursive program to generate 10 terms Fibonacci sequence starting from 2. Hinclude int fib(int n); int main() { int i,result; } int fib(int n) { if (n==2| |n==3) { return n; } else { return(fid(n-1) + fib(n-2)); } 6) Write a program to find nth term of Fibonacci number using recursive function. fHinclude t fibint n); int main() { int n,result; printf("Enter the term\n"); seani("%6d",&n); printf("The %d th fibonacci term is %d",n result); return 0; } int fibint n) { if ( { return 0; } else iff { return 1; } else { return(fib(n-1) + fib(n-2)); } 1) 7) Write a program to read an integer number and find the sum of digits using recursive function. Hinclude Int sum(int n); int main() { int num, result; printf("Enter the number\n scanf("96d", &num); result = sum(num); printf("Sum of digits of given number=%d' result); return 0; } int sum (int n) { if(n { ) return 0; } else { return (n % 10 + sum(n/ 10); } 8) Use recursive functions calls to evaluate. a3 x8 x7 3st f[x)=: includecstdio,h> #includecmath.h> int fact{int n); int main() { float sum=0,nume,deno,x; int n,isign; printf("Enter the value of x and n\n"); scanf("%f96d", 84,8); forli=tjic=nji++) { nume=pow(x,2*i-1); deno=fact(2*i-1); sign=pow(-1,i#1); sum=sumssign*nume/deno; } printf("sum of series=%"",sum); return 0; } int fact(int n) { if(n==1||n==0) { return 1; } else { return (n*fact(n-1)}; } 9) Write a program to read an integer and find the number of digits present in it using recursive functi include int count{int n); int main() { int num, result; printf("Enter the number\n "); scanf("%d", &num); result = count(num); printfl"Number of digits in a given number=%d" result); return 0; } int count(int n) { if (n ==0) { return 0; } else { return (1+ count(n/10)); } } 10) Write a recursive program to raise the power of X to n. (i.e. X") OR Write a program to find power of a given number using recursive function. \clude float power (float x,int n); int main() { float x,result; int n; printf("Enter the value of x\n"); scanf(""6f", 8x); printf("Enter the value of n\n"); seanf("%d", Bn); result=power(x,n}; printf("Result=96f",result) return 0; } float powerifloat x,int n) { if(n==0) { return 1; } else if (n>0) { return x* power(x,n-1); } else { return (1/x)* power(x,n+1); } 11) Write a Program to check whether the given number is Armstrong number or not using recursive function. (for three digit number) #includesstdio.h> int armstrong(int); int main() { int numn,a; printf("Enter any three digit number\n"); scanf("%d",&num); a-armstrong(num); printf("The number is armstrong number\n"); } else { printf("The number is not armstrong number\n"); } } int armstrong{(int x) { iff { ) return 0; returm((x%10)*(x%10)*(x%610)+armstrong(x/10)); Recursion vs Iteration Recursion Iteration . The statement in a body of function calls the function itself. Allows the set of instructions to be repeatedly executed. Recursion is always applied to functions. Iteration is applied to iteration statements or "loops". In recursive function, only termination condition (base case) is specified Iteration includes initialization, condition, execution of statement within loop and updation (increments/decrements) the control variable If the function does not converge to some condition called (base case), it leads to infinite recursion. If the control condition in the iteration statement never become false, it leads to Infinite iteration . The stack is used to store the set of new Does not uses stack. local variables and parameters each time the function is called 6. Infinite recursion can crash the system. 6. Infinite loop uses CPU cycles repeatedly. 7. Slow in execution 7. Fast in execution. Describe the output generated by each of the following program. Hinclude int a=100,b=200; int functA(int ¢); it main() { int count,c; c=4*count; printf("%d\n" functa(c)); } return 0; } funct1(int x) { inc; =(x<30)?(a-x):(b+x); return (c); Here a=100,b=200 Where a and b are global [Link] that they can accessed from anywhere. count | c=4*count _| funct(e) =(<30)a-x) : (bx) | print c 1 (| ceamisa funct1(4) (4«30)?(True) 96 c=a-x=100-4=96 2 | c=4*2=8 funct1(8) (8<30)?(True) 2 =100-8=92 3 [era*zea2 | funct4(12) (12<30)?True 88 c=100-12=88 4 [ca*4=16 | functi(16) (16<30)?True 8a c=100-16=84 5 |e=4¥*5=20 | functi(20) (20-30)? True 80 €=100-20-80 @ | c=a*6=24 | functi(24) (24<30)?True 76 c=100-24=76 7 | c=4*7=28 | funct1(28) (28<30)?True nR €=100-28-72 @ | c4*8=32 | functi(32) (32<30)?False 232 b4x=20043: 9 [c=4*9=36 | funct1(36) (36<30)?False 236 c=b4x=200436=236 10 | e=4¥i0-40 | functi(40) (40<30)?False 240 c=b+x=200+40=240 Output: 96 92 88 84 30 76 n 232 236 240 Describe the output generated by each of the following program. finclude void funcL(int a); int main() { int i; for return 0; void funcl(int n) { } int num=3; printf("60\n\n'';n*num); Tracing Output: 3 6 9 12 ica funcd{i) a num print (n*num) 1<=4(T) funcl(1) 1 3 3 2<=4(T) func1(2) 2 3 6 3<=4(T) func1(3) 3 3 9 4<=A(T) func1(4) 43 12 5<=A(F) terminate PROGRAMS USING FUNCTION 1, Write a Program to calculate the area of two circles having different radius using the same user-defined function named area. #include float area(float r); int main() { float r1,r2,a1,a2; printf("Enter the radius of first circle\n"); seanf("S6F", 81); al=area(r1); printi("Enter the radius of second circle\n"); scanf("96f", &r2); a2-area(r2); printi("Area of first circle=96f\n",21); printf("Area of second circle=9%f\n" a2); return 0; Fs 3. float areafloat r) { float a; a=3.14*r*r; return a; } Write a program to find the factorial of a given positive integer using user-defined function. ffinclude Jong int factorial(int n); int main() { int num; long int result; printi("Enter the given positive integer\n"); scanf("sed", num); result=factorial|num); printf("Factorial of a given number is %d",result); return 0; } tong int factorial(int n) return fact; } Write a program to find the sum of n natural numbers using user-defined function. ffincludecsteio.h> int snatural{int n); int main() { int num printf("Enter the value of n\n"); scanf("%d",&num); s=snatural(num); printf("Sum of n natural number return 0; %d" 5); int snatural(int n) { int isum=0, for(i=1;i { sum=sum+i } return sum; } itt) |. Write a Program to calculate the area and perimeter of rectangle using user-defined function. fincludessteio.h> void area(float x, float y); void perimeter(float x,float y); int main() { float I,b; printf("Enter the length and breadth of rectangle\n"); scan‘("6f%f",&1,8b); areall,b); perimeter(I,b); return 0; } void area(float x float y) { float area; areasx*y; printi(""area=96f\n",area); } void perimeter(float x,float y) { float peri; periz2*(x+y); printf("Perimeter=9%t } 5._Write a program to check maximum of 3 numbers using user-defined function. finclude int max(int x,inty,int2); int main() { int a,b,cresult; printf["Enter the three numbers\n"); scanf("%d%d%6d" fa, Sib, 8c); result=max(a,b,¢); printf("Maximum number=%d"result); return 0; } int max(intx,int y,int z) { if(x>y&8ox>z) { return x; } else if(y>z) { return y; } else { return z; } } ‘Assignment: Write a Program to check the maximum of two numbers using function. 6. Write a Program to check the given number is prime or not using user defined function. #include fincludecstdlib.h> void checkprime(int n); int main) { int num; printf("Enter the number you want to check\n"}; scanf("%4d", &num); checkprime(num); return 0; } void checkprime(int n) { inti; if(n<=1) { printf("Number is not prime"); exit(0); } for(i=2;i void checkpalindromelint n}; int main() { int num; printf("Enter the number you want to check\n"); scanf("'%d",&num); checkpalindrome(num); return 0; } void checkpalindrome|int n} { int rem,rev=0,25 asnj while(n!=0) { rem=n%10; rev-rev"10+rem; n=n/10; } iffa { printf("Number is palindrome"); } else { printf("Number is not palindrome"); } ev) } Write a Program to find the reverse of a number using user-defined function. (Try yourself) 8. By using user-defined function write a program to generate the Fibonacci series upto nth term when initial value is given by user. finclude void fibo(int n,int x,int y); int main() { int a,b,num; printf("Enter the number of terms you want to generate\n"); scanf("%d",&num); printf("Enter the two inital values\n"); scanf("%d%d" 82,8); fibo(num,a,b); return 0; } void fibo(int n,int x,int y) { inticc; printf("%d\t%o" x,y); for(i=1ji<=n-2;i-+) { cexty; printf("\t%d",c); xy: Passing Array to Function Passing one dimensional Array to function InC, arrays are automatically passed by reference to a function. The name of the array represents the address of its first element. By passing the array name, we are in fact, passing the address of the array to the called function. The array in the called function now refers to same array stored in the memory. Therefore any changes in the array in the called function will be reflected in the original array. ¥ The corresponding formal argument in function definition is written in the same manner, ‘though it must be declared as an array. ¥ When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration. ¥ Topass an array as an argument to function, the array name must be specified, without brackets or subscripts, and the size of an array as arguments. Syntax for function declaration that receives array as argument return_type function_name(data_type array_namel ] ); Syntax to pass array to the function. function_name(arrayname); Note: We cannot pass a whole array by value as we did in the case of ordinary variables. Program to illustrate passing array to a function one element at a tim: ffinclude void displaylint x); int main() { inti; int a[5]={5,10,15,20,25); forli=Ojic5;i++) { display(alil); } return } void display(int x) ("Sede"); Write 2 program to pass one dimensional array to a function and display that array in that called function. Hinclude void displayiint xl], int n); int main() { int i int a[5]={5,10,15,20,25}; displayla,5); return 0; } void display(int x{],int n) { int i forli=O;i void add(int x{],int n); int main() { int af100},n,i; printi("Enter how many elements\n"}; scanf{"sed",&n); printf("Enter %d array elements\n",n); scanf("%d" Bali); } add(a,n); return 0; } void add(int x{Lint n) { Int ,sum=0; for(i=O;i void average(int x{] int n); int main() { int a[100},n,i; printf("Enter how many elements\n"); scant("%d",&n); printf("Enter the array elements\n’ forli=O;i void fun(int x{],int n); int main() { int a[100},n,j; printf("Enter how many elements\n"); scanf("%d",&n); printf("Enter the array elements\n"); for(i { scan‘("ed",&ali]); } fun(a,n); return 0; sisnjit) void fun(int x{].int n) { 4) int i,small large; large=x{0]; small=x[0]; for(i=O;ilarge) { large=xii]; } if xlil void sort(int x{],int n); void disp(int a],int 9); int main() { int a[100}.n.i; printf("Enter how many elements\n"); seani("%d",&n); printf("Enter the array elements\n"); for(i=O;ixfj+4]) ( temp=xij]; j}=x6+1; x{j+1}=temp; ' } } } void disp(int dl],int n) { int i for(i=O;i int checkprime(int n); int main() { int a[50},n,i,sum=0,result; printf("Enter the number of elements\n"); scanf("%d",&n); printf("Enter %d elements\n",n); forli=O;icn;i++) { scanf("%d" &ali}); } printf(""prime numbers are\n"); forli=O;icmi++) { printfl"%d\t",ali]); sum=sumsali]; f("\nThe sum of prime number is %d",sum); return 0; } int checkprime(int n) { inti; if(ne=1) { return 0; return 0; } } if(n=si) { return 1; } Practice Questions: 1) Write a program to input n numbers in an array and count number of odd and even numbers and find their sum using function. 2). Write a Program to input n number in an array and print in reverse order using function. 3) Write a Program to input n numbers in an array and check if given number is present or not using function. Passing 2D array to function v Just as in 1 dimensional array, when two-dimensional array is passed as a parameter, the base address of the actual array is sent to function y that is passed to function Any change made to element inside function will carry over to the original location of array > The size of all dimensions except the first must include in the function declaration and in function definition, Eg. void display(int{][10],int, int); is a valid declaration. 1) Write a program to input m*n order matrix and find sum of all elements using user- defined function. Hinclude void summatrix(int s{J|20],int r,int ¢); void disp(int diJ[20} int r,int ¢}; int is int main() { } int a[20][20],m,n; printf("Enter the order of matrix\n"); scani("%d%d", mn, &n); printf("Enter %d elements of matrix\n",m*n); ii int summatrix(int s{][20] int r,int ¢); void displint dl]{20).int rint c); int ij; int main() { } int a[20][20],m,n,result; printf("Enter the order of matrix\n' scani("%4dM%d",&m,&n); printf("Enter %d elements of matrix\n",m*n);, scanf("%d",Zali][i)); } } disp(a,m,n); result=summatrix(a,m,n); printf("sum of matrix elements=%d",result); return 0; int summatrix(int s[][20],int r,int c) { itt) for(j=0;) Vold transpose(int t{][20}, int [Link] ¢); void disp(int d{][20] int rint ¢); int iis int main() { Int a[20}[20},m,n; printf("Enter the order of matrix\n"); scani("%d%d",&m,&n); printf("Enter %d elements of matrix\n",m*n); for(i=O;i void input(int af][20},int int); void disp(int d{][20],int [Link].c); void addition(int a1(][20],int a2[][20],int r,int c); ii int main() { int matrix1[20][20],matrix2[20][20],m,n; printf("Enter the order of matrix\n"); sean‘("%d8%d"&m,8n); printf("Enter the first matrix\n"); input(matrix1 m,n); printf("Enter the second matrix\n"); input(matrix2,m,n); printf("The first matrix is\n"); disp(matrix1,m,n); printf("The second matrix is\n"); disp(matrix2,m,n); addition(matrix1, matrix2,m.n); return 0; } void input(int af}{20],int r,int ¢) { forli=O;i

You might also like