Unit 9
User-Defined Function in ‘C’
- Explain built in user define function
User defined functions are the functions defined by the programmer or user.
C++ provides the facility to user to define their own functions.
When the function gets call anywhere from program the function body gets execute.
Structure
#include<iostream>
Void function_name(){
}
Int main(){
Function_name();
}
Example
#include<iostream>
Using namespace std;
Int add(int, int);
Int main(){
int a, b, sum;
cout<<"Enters two numbers ";
cin >> a >> b;
sum = add(a, b);
cout << "Sum = " << sum;
return 0;
}
Int add(int a, int b)
{
int add;
add = a + b;
return add; }
}
2. What is function definition and declaration?
Function is declared globally to inform the compiler about function name, function parameters and return type.
Return_type function_name([arguments type)];
Example
Void create_function(){
}
Function call
Function call has parameter list with function name. Using function call function can be called anywhere in program.
Function_name([actual arguments]);
Example
Void createfunction() {
cout << "Function created";
}
int main() {
createfunction();
return 0;
}
Function definition.
Function definition consists of block of statements which contains actual execution code. When function gets called in program control comes to the function definition.
Return_type function_name([arguments])
{
Statements;
}
Example
Int main() {
createfunction();
return 0;
}
void createfunction() {
cout <<”Functoin created.”;
}
Void mycreateunction();
int main() {
createfunction();
return 0;
}
void createfunction() {
cout << “Function created”;
}
3. What is pass by value and pass by reference in function explain with examples?
Function arguments in c programming
Basically, there are two types of arguments:
- Actual arguments
- Formal arguments
The variables declared in the function prototype or definition are known as Formal arguments and the values that are passed to the called function from the main function are known as Actual arguments.
The actual arguments and formal arguments must match in number, type, and order.
Following are the two ways to pass arguments to the function:
- Pass by value
- Pass by reference
Pass by Value
Pass by value is a method in which a copy of the value of the variables is passed to the function for the specific operation.
In this method, the arguments in the function call are not modified by the change in parameters of the called function. So the original variables remain unchanged.
Example of passing arguments by value to function in C
// arguments pass by value
# include <stdio.h>
Int add (int a, int b)
{
return( a + b );
}
Int main()
{
int x, y, z;
x = 5;
y = 5;
z = add(x,y); // call by value
Return 0;
}
//end of program
In this program, function add() is called by passing the arguments x and y.
The copy of the values of x and y are passed to a and b respectively and then are used in the function.
So by changing the values of a and b, there will be no change in the actual arguments x and y in the function call.
Pass by reference
Pass by reference is a method in which rather than passing direct value the address of the variable is passed as an argument to the called function.
When we pass arguments by reference, the formal arguments in the called function becomes the assumed name or aliases of the actual arguments in the calling function. So the function works on the actual data.
Example of passing arguments by reference to function in C
// arguments pass by reference
#include <stdio.h>
Void swap (int *a, int *b) // a and b are reference variables
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Int main()
{
int x = 2, y = 4;
printf("before swapping x = %d and y = %d\n", x, y);
swap(&x, &y); // call by reference
return 0;
} //end of program
In the above program, the formal arguments a and b becomes the alias of actual arguments x and y when the function was called.
So when the variables a and b are interchanged x and y are also interchanged. So the output becomes like this.
Output
Before swapping x = 2 and y = 4
After swapping x = 4 and y = 2
Now, if the function was defined as:
Void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
This is the pass by value method so here even if the values are swapped in the function the actual value won’t interchange and output would become like this:
Before swapping x = 2 and y = 4
After swapping x = 4 and y = 2
4. What is calling by value explain with examples?
Call by value in C
- In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
- In call by value method, we can not modify the value of the actual parameter by the formal parameter.
- In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
- The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given below:
- #include<stdio.h>
- Void change(int num) {
- Printf("Before adding value inside function num=%d \n",num);
- Num=num+100;
- Printf("After adding value inside function num=%d \n", num);
- }
- Int main() {
- Int x=100;
- Printf("Before function call x=%d \n", x);
- Change(x);//passing value in function
- Printf("After function call x=%d \n", x);
- Return 0;
- }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by Value Example: Swapping the values of the two variables
- #include <stdio.h>
- Void swap(int , int); //prototype of the function
- Int main()
- {
- Int a = 10;
- Int b = 20;
- Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
- Swap(a,b);
- Printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20
- }
- Void swap (int a, int b)
- {
- Int temp;
- Temp = a;
- a=b;
- b=temp;
- Printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
- }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
5. What is call by reference explain with examples?
Call by reference in C
- In call by reference, the address of the variable is passed into the function call as the actual parameter.
- The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
- In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.
Consider the following example for the call by reference.
- #include<stdio.h>
- Void change(int *num) {
- Printf("Before adding value inside function num=%d \n",*num);
- (*num) += 100;
- Printf("After adding value inside function num=%d \n", *num);
- }
- Int main() {
- Int x=100;
- Printf("Before function call x=%d \n", x);
- Change(&x);//passing reference in function
- Printf("After function call x=%d \n", x);
- Return 0;
- }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
- #include <stdio.h>
- Void swap(int *, int *); //prototype of the function
- Int main()
- {
- Int a = 10;
- Int b = 20;
- Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
- Swap(&a,&b);
- Printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20
- }
- Void swap (int *a, int *b)
- {
- Int temp;
- Temp = *a;
- *a=*b;
- *b=temp;
- Printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
- }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
6. What is recursion?
Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.
In the following example, recursion is used to calculate the factorial of a number.
- #include <stdio.h>
- Int fact (int);
- Int main()
- {
- Int n,f;
- Printf("Enter the number whose factorial you want to calculate?");
- Scanf("%d",&n);
- f = fact(n);
- Printf("factorial = %d",f);
- }
- Int fact(int n)
- {
- If (n==0)
- {
- Return 0;
- }
- Else if ( n == 1)
- {
- Return 1;
- }
- Else
- {
- Return n*fact(n-1);
- }
- }
Output
Enter the number whose factorial you want to calculate?5
Factorial = 120
We can understand the above program of the recursive method call by the figure given below:
7. What is recursive function explain with examples?
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.
Pseudocode for writing any recursive function is given below.
- If (test_for_base)
- {
- Return some_value;
- }
- Else if (test_for_another_base)
- {
- Return some_another_value;
- }
- Else
- {
- // Statements;
- Recursive call;
- }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
- #include<stdio.h>
- Int fibonacci(int);
- Void main ()
- {
- Int n,f;
- Printf("Enter the value of n?");
- Scanf("%d",&n);
- f = fibonacci(n);
- Printf("%d",f);
- }
- Int fibonacci (int n)
- {
- If (n==0)
- {
- Return 0;
- }
- Else if (n == 1)
- {
- Return 1;
- }
- Else
- {
- Return fibonacci(n-1)+fibonacci(n-2);
- }
- }
Output
Enter the value of n?12
144
8. Explain Memory allocation of Recursive method
Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.
Let us consider the following example to understand the memory allocation of the recursive functions.
- Int display (int n)
- {
- If(n == 0)
- Return 0; // terminating condition
- Else
- {
- Printf("%d",n);
- Return display(n-1); // recursive call
- }
- }
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which prints the corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the recursive functions.
9. Explain mathematical function with examples
C Math
C Programming allows us to perform mathematical operations through the functions defined in <math.h> header file. The <math.h> header file contains various methods for performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header file are given below.
No. | Function | Description |
1) | Ceil(number) | Rounds up the given number. It returns the integer value which is greater than or equal to given number. |
2) | Floor(number) | Rounds down the given number. It returns the integer value which is less than or equal to given number. |
3) | Sqrt(number) | Returns the square root of given number. |
4) | Pow(base, exponent) | Returns the power of given number. |
5) | Abs(number) | Returns the absolute value of given number. |
C Math Example
Let's see a simple example of math functions found in math.h header file.
- #include<stdio.h>
- #include <math.h>
- Int main(){
- Printf("\n%f",ceil(3.6));
- Printf("\n%f",ceil(3.3));
- Printf("\n%f",floor(3.6));
- Printf("\n%f",floor(3.2));
- Printf("\n%f",sqrt(16));
- Printf("\n%f",sqrt(7));
- Printf("\n%f",pow(2,4));
- Printf("\n%f",pow(3,3));
- Printf("\n%d",abs(-12));
- Return 0;
- }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
10. Explain string function with examples
C String Functions
There are many important string functions defined in "string.h" library.
No. | Function | Description |
1) | Strlen(string_name) | Returns the length of string name. |
2) | Strcpy(destination, source) | Copies the contents of source string to destination string. |
3) | Strcat(first_string second_string) | Concats or joins first string with second string. The result of the string is stored in first string. |
4) | Strcmp(first_string, second_string) | Compares the first string with second string. If both strings are same, it returns 0. |
5) | Strrev(string) | Returns reverse string. |
6) | Strlwr(string) | Returns string characters in lowercase. |
7) | Strupr(string) | Returns string characters in uppercase. |