new UNIT-IV
new UNIT-IV
new UNIT-IV
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known as procedure
or subroutine in other programming languages.
Advantage of functions in C
● There are the following advantages of C functions.
● By using functions, we can avoid rewriting same logic/code again and again in a
program.
● We can call C functions any number of times in a program and from any place in a
program.
● We can track a large C program easily when it is divided into multiple functions.
● Reusability is the main achievement of C functions.
● However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.
Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions
as it is declared in the function declaration.
Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.
SN C function aspects Syntax
Types of Functions
There are two types of functions in C programming:
Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
User-defined functions: are the functions which are created by the C programmer, so that he/she
can use it many times. It reduces the complexity of a big program and optimizes the code.
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
Example without return value:
void hello(){
printf("hello c");
}
If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the function.
float get(){
return 10.2;
}
Now, you need to call the function, to get the value of the function.
Example 2
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
The sum is 34
Example 2: program to calculate the area of the square
#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
3. Example for Function with argument and without return value
Example 1
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:
The sum is 34
Example 2: program to calculate the average of five numbers.
#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
4. Example for Function with argument and with return value
Example 1
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
Example 2: Program to check whether a number is even or odd
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific operations.
For example, printf is a library function used to print on the console. The library functions are
created by the designers of compilers. All C standard library functions are defined inside the
different header files saved with the extension .h. We need to include these header files in our
program to make use of the library functions defined in such header files. For example, To use
the library functions such as printf/scanf we need to include stdio.h in our program which is a
header file that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
S Header Description
N file
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.
9 signal.h All the signal handling functions are defined in this header file.
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 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.
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function are limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location
Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on
numbers.
To use them, you must include the math.h header file in your program:
#include <math.h>
1.Square Root
To find the square root of a number, use the sqrt() function:
Example
printf("%f", sqrt(16));
2.Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds
a number downwards to its nearest integer, and returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
3.Power
The pow() function returns the value of x to the power of y (xy):
Example printf("%f", pow(4, 3));
Other Math Functions
A list of other popular math functions (from the <math.h> library) can be found in the table
below:
Function Description
String Functions
There are many important string functions defined in "string.h" library.
No Function Description
.
3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.
4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.
Recursion in C
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.s
#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:
Recursive Function
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.
Working
The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.
Case 1
Case 2
Case 3
ALGORITHM
The implementation of the binary search algorithm function uses the call to function again and again. This call c
● Iterative
● Recursive
Iterative call is looping over the same block of code multiple times
Recursive call is calling the same function again and again.
Example
#include <stdio.h>
int iterativeBinarySearch(int array[], int start_index, int end_index, int element){
while (start_index <= end_index){
int middle = start_index + (end_index- start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] < element)
start_index = middle + 1;
else
end_index = middle - 1;
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 16;
int found_index = iterativeBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}
Output
Element found at index : 4
Example
#include <stdio.h>
int recursiveBinarySearch(int array[], int start_index, int end_index, int element){
if (end_index >= start_index){
int middle = start_index + (end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return recursiveBinarySearch(array, start_index, middle-1, element);
return recursiveBinarySearch(array, middle+1, end_index, element);
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 9;
int found_index = recursiveBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}
C Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer
depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integ
er.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e.,
fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printi
ng p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer th
erefore if we print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Pointer to array
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.
Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a function
Pointer to structure
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings,
trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code
and improves the performance.
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u to display
the address of a variable.
#include<stdio.h>
int main(){
int number=50;
printf("value of number is %d, address of number is %u",number,&number);
return 0;
}
Output
value of number is 50, address of number is fff4
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't
have any address to be specified in the pointer at the time of declaration, you can assign NULL
value. It will provide a better approach.
int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).
Pointer Program to swap two numbers without using the 3rd variable.
#include<stdio.h>
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
return 0;
}
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
Reading complex pointers
There are several things which must be taken into the consideration while reading the complex
pointers in C. Lets see the precedence and associativity of the operators which are used regarding
pointers.
Data type 3 -
Explanation
This pointer will be read as p is a pointer to such function which accepts the first parameter as
the pointer to a one-dimensional array of integers of size two and the second parameter as the
pointer to a function which parameter is void and return type is the integer.
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it
actually increments by the number equal to the size of the data type for which it is a pointer.
Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of
an int), and the new address will point to 1004. While if a float type pointer is incremented then
it will increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it
actually decrements by the number equal to the size of the data type for which it is a pointer.
Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of
an int), and the new address will point to 996. While if a float type pointer is decremented then it
will decrement by 4(size of a float) and the new address will be 996.
Note: It is assumed here that the architecture is 64-bit and all the data types are sized
accordingly. For example, integer is of 4 bytes.
Example of Pointer Increment and Decrement
#include <stdio.h>
// pointer increment and decrement
//pointers are incremented and decremented by the size of the data type they point to
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value
float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value
char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value
return 0;
}
Output
p = 6422288
p++ = 6422292
p-- = 6422288
q = 6422284
q++ = 6422288
q-- = 6422284
r = 6422283
r++ = 6422284
r-- = 6422283
Note: Pointers can be outputted using %p, since, most of the computers store the address value
in hexadecimal form using %p gives the value in that form. But for simplicity and understanding
we can also use %u to get the value in Unsigned int form.
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
// Driver Code
int main()
{
int x = 6; // Integer variable declaration
int N = 4;
// Pointer declaration
int *ptr1, *ptr2;
ptr1 = &N; // stores address of N
ptr2 = &x; // stores address of x
Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. Comparison of pointers of the same type
We can compare the two pointers by using the comparison operators in C. We can implement
this by using all operators in C >, >=, <, <=, ==, !=. It returns true for the valid condition and
returns false for the unsatisfied condition.
Step 1: Initialize the integer values and point these integer values to the pointer.
Step 2: Now, check the condition by using comparison or relational operators on pointer
variables.
Step 3: Display the output.
Example of Pointer Comparision
// C Program to illustrate the pointer comparison
#include <stdio.h>
int main()
{
// code
int num1 = 5, num2 = 6, num3 = 5; // integer input
int* p1 = &num1; // addressing the integer input to pointer
int* p2 = &num2;
int* p3 = &num3;
// comparing the pointer variables.
if (*p1 < *p2) {
printf("\n%d less than %d", *p1, *p2);
}
if (*p2 > *p1) {
printf("\n%d greater than %d", *p2, *p1);
}
if (*p3 == *p1) {
printf("\nBoth the values are equal");
}
if (*p3 != *p2) {
printf("\nBoth the values are not equal");
}
return 0;
}
Output
5 less than 6
6 greater than 5
Both the values are equal
Both the values are not equal
Here,
pointer_type: Type of data the pointer is pointing to.
array_name: Name of the array of pointers.
array_size: Size of the array of pointers.
Note: It is important to keep in mind the operator precedence and associativity in the array of
pointers declarations of different type as a single change will mean the whole different thing. For
example, enclosing *array_name in the parenthesis will mean that array_name is a pointer to an
array.
Example:
int main()
{
// declaring some temp variables
int var1 = 10;
int var2 = 20;
int var3 = 30;
return 0;
}
Output
Value of var1: 10 Address: 0x7fff1ac82484
Value of var2: 20 Address: 0x7fff1ac82488
Value of var3: 30 Address: 0x7fff1ac8248c
Explanation:
As shown in the above example, each element of the array is a pointer pointing to an integer. We
can access the value of these integers by first selecting the array element and then dereferencing
it to get the value.
Syntax:
char *array_name [array_size];
After that, we can assign a string of any length to these pointers.
Example:
char* arr[5]
= { "gfg", "geek", "Geek", "Geeks", "GeeksforGeeks" }
This method of storing strings has the advantage of the traditional array of strings. Consider the
following two examples:
Example 1:
return 0;
}
Output
String array Elements are:
Geek
Geeks
Geekfor
In the above program, we have declared the 3 rows and 10 columns of our array of strings.
But because of predefining the size of the array of strings the space consumption of the program
increases if the memory is not utilized properly or left unused. Now let’s try to store the same
strings in an array of pointers.
Example 2
Output
geek
Geeks
Geeksfor
Here, the total memory used is the memory required for storing the strings and
pointers without leaving any empty space hence, saving a lot of wasted space. We can
understand this using the image shown below.
The space occupied by the array of pointers to characters is shown by solid green blocks
excluding the memory required for storing the pointer while the space occupied by the array of
strings includes both solid and light green blocks.
int main() {
int x = 50, y = 5;
Output
Sum : 55
Difference : 45
Product : 250
Quotient : 10
Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20 // Thus actual values of a and b remain unchanged even after exchanging the
values of x and y in the function.
2.Call by Reference
● In call by reference method of parameter passing, the address of the actual parameters is
passed to the function as the formal parameters.
● Both the actual and formal parameters refer to the same locations.
● Any changes made inside the function are actually reflected in the actual parameters of
the caller.
Example of Call by Reference
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
return 0;
}
t = *x;
*x = *y;
*y = t;
Output
Inside the Function:
x = 20 y = 10
Inside the Caller:
a = 20 b = 10
Thus actual values of a and b get changed after exchanging values of x and y.
Values of variables are passed by the Pointer variables are necessary to define to store
Simple technique. the address values of variables.