Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT-IV 10 Hours

User defined functions: Introduction, Need for user-defined functions, a multi-function


program, Elements of user defined function, Definition of functions, Return values and their
types, Function calls, Function declaration. Category of functions: Based on call by value,
call by reference, argument and return type and recursion.

Structures: Defining a structure, Declaring structure variables, Accessing structure members,


Initialization, Arrays of structure, Arrays within structures, Structures and within structures,
Structures and functions.

User defined functions:

A function is a block of code that performs a particular task. There are many situations where
we might need to write same line of code for more than once in a program. This may lead to
unnecessary repetition of code, bugs and even becomes boring for the programmer. So, C
language provides an approach in which you can declare and define a group of statements
once in the form of a function and it can be called and used whenever required.

These functions defined by the user are also known as User-defined Functions. C functions
can be classified into two categories,

Library functions
User-defined functions

Library functions are those functions which are already defined in C library, for
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.

User-defined functions on the other hand, are those functions which are defined by the user at
the time of writing program. These functions are made for code reusability and for saving
time and space.

Benefits of Using Functions


It provides modularity to your program's structure.
It makes your code reusable. You just have to call the function by its name to use it, wherever
required.
In case of large programs with thousands of code lines, debugging and editing becomes easier
if you use functions.
It makes the program more readable and easy to understand.

Function Declaration
General syntax for function declaration is,
returntype functionName(type1 parameter1, type2 parameter2,...);

Like any variable or an array, a function must also be declared before it is used. Function
declaration informs the compiler about the function name, parameters is accept, and its return
type. The actual body of the function can be defined separately. It's also called as Function
Prototyping. Function declaration consists of 4 parts.

Return type
Function name
Parameter list
Terminating semicolon

Return type
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is added at
the end of function body. Return type specifies the type of value(int, float, char, double) that
function is expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.

Function Name
Function name is an identifier and it specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same naming rules like other variables in
C language.

Parameter list
The parameter list declares the type and number of arguments that the function expects when
it is called. Also, the parameters in the parameter list receive the argument values when the
function is called. They are often referred as formal parameters.
Example
Let's write a simple program with a main() function, and a user defined function to multiply
two numbers, which will be called from the main() function.

#include<stdio.h>

int multiply(int a, int b); // function declaration

int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);

result = multiply(i, j); // function call


printf("The result of muliplication is: %d", result);

return 0;
}

int multiply(int a, int b)


{
return (a*b); // function defintion, this can be done in one line
}

Function definition Syntax


Just like in the example above, the general syntax of function definition is,
returntype functionName(type1 parameter1, type2 parameter2,...)
{
// function body goes here
}

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known


as function header and the statement(s) within curly braces is called function body.
Note: While defining a function, there is no semicolon(;) after the parenthesis in the function
header, unlike while declaring the function or calling the function.

Function body
The 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.

local variable declaration(if required).


function statements to perform the task inside the function.
a return statement to return the result evaluated by the function(if return type is void, then no
return statement is required).

Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
In the example above, the statement multiply(i, j); inside the main() function is function call.

Passing Arguments to a function


Arguments are the values specified during the function call, for which the formal parameters
are declared while defining the function.

It is possible to have a function with parameters but no return type. It is not necessary, that if
a function accepts parameter(s), it must return a result too.

While declaring the function, we have declared two parameters a and b of type int. Therefore,
while calling that function, we need to pass two arguments, else we will get compilation
error. And the two arguments passed should be received in the function definition, which
means that the function header in the function definition should have the two parameters to
hold the argument values. These received arguments are also known as formal parameters.
The name of the variables while declaring, calling and defining a function can be different.

Returning a value from function


A function may or may not return a result. But if it does, we must use the return statement to
output the result. return statement also ends the function execution, hence it must be the last
statement of any function. If you write any statement after the return statement, it won't be
executed.
The datatype of the value returned using the return statement should be same as the return
type mentioned at function declaration and definition. If any of it mismatches, you will get
compilation error.

Recursive function
A recursive function is a function that calls itself during its execution. The process may repeat
several times, outputting the result and the end of each iteration. ... Recursive functions allow
programmers to write efficient programs using a minimal amount of code.

Recursion is the process of repeating items in a self-similar way. In programming languages,


if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.

void recursion()
{
recursion(); /* function calls itself */
}

int main()
{
recursion();
}

The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop. Recursive functions are very useful to solve many
mathematical problems, such as calculating the factorial of a number, generating Fibonacci
series, etc.

Working of recursion
Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main()
{
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);


return 0;
}

int sum(int n)
{
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Output
Enter a positive integer: 3
sum = 6

Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to
the sum() function. This process continues until n is equal to 0. When n is equal to 0,
the if condition fails and the else part is executed returning the sum of integers ultimately to
the main() function.
Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops instead as
recursion is usually much slower. That being said, recursion is an important concept. It is
frequently used in data structure and algorithms. For example, it is common to use recursion
in problems such as tree traversal.

The following example calculates the factorial of 12 using a recursive function,

#include <stdio.h>

unsigned long long int factorial(unsigned int)

int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

unsigned long long int factorial(unsigned int i)


{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}

When the above code is compiled and executed, it produces the following result
Factorial of 12 is 479001600

The following example generates the Fibonacci series of first 10 digits using a recursive
function
#include <stdio.h>

int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main()
{
int i;

for (i = 0; i < 10; i++)


{
printf("%d\t\n", fibonacci(i));
}
return 0;
}

When the above code is compiled and executed, it produces the following result
0
1
1
2
3
5
8
13
21
34
Structures:

Structure is a user-defined datatype in C language which allows us to combine data of


different types together. Structure helps to construct a complex data type which is more
meaningful. It is somewhat similar to an Array, but an array holds data of similar type only.
But structure on the other hand, can store data of any type, which is practically more useful.

For example: If I have to write a program to store Student information, which will have
Student's name, age, branch, permanent address, father's name etc, which included string
values, integer values etc, how can I use arrays for this problem, I will require something
which can hold data of different types together. In structure, data is stored in form of records.

Why structs in C?
Suppose, you want to store information about a person: his/her name, aadhar number, and
salary. You can create different variables name, uin and salary to store this information.

What if you need to store information of more than one person? Now, you need to create
different variables for each information per person : name1, citNo1, salary1, name2,
citNo2, salary2, etc.

A better approach would be to have a collection of all related information under a single
name Person structure and use it for every person.

Define Structures
Before you can create structure variables, you need to define its data type. To define a struct,
the struct keyword is used. struct defines a new data type which is a collection of primary and
derived data types.

Syntax

struct structureName
{
dataType member1;
dataType member2;
...
};

For example,
struct Person
{
char name[50];
int citNo;
float salary;
};

Here, a derived type struct Person is defined. Now, you can create variables of this type.
Create struct Variables
When a struct type is declared, no storage or memory is allocated. To allocate memory of a
given structure type and work with it, we need to create variables.

Here's how we create structure variables:


struct Person
{
// code
};

int main()
{
struct Person person1, person2, p[20];
return 0;
}

Another way of creating a struct variable is:


struct Person
{
// code
} person1, person2, p[20];

In both cases,
person1 and person2 are struct Person variables
p[] is a struct Person array of size 20.

Access Members of a Structure

There are two types of operators used for accessing members of a structure.
. Member operator
-> Structure pointer operator

Suppose, you want to access the salary of person2. Here's how you can do it.

person2.salary

#include <stdio.h>
#include <string.h>

// create struct with person1 variable


struct Person
{
char name[50];
int citNo;
float salary;
} person1;
int main()
{
// assign value to name of person1
strcpy(person1.name, "Amar");

// assign values to other person1 variables


person1.uin = 1947;
person1. salary = 10000;

// print struct variables


printf("Name: %s\n", person1.name);
printf("Aadhar No.: %d\n", person1.uin);
printf("Salary: %.2f", person1.salary);

return 0;
}

Output
Name: Amar
Aadhar No.: 1947
Salary: 10000.00

In this program, we have created a struct named Person. We have also created a variable
of Person named person1. In main(), we have assigned values to the variables defined
in Person for the person1 object. strcpy(person1.name, "Amar"); person1.uin = 1947;
person1. salary = 10000;

Notice that we have used strcpy() function to assign the value to person1.name. This is
because name is a char array (C-string) and we cannot use the assignment operator = with it
after we have declared the string. Finally, we printed the data of person1.

Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with
structures to simplify the syntax of declaring variables. For example, let us look at the
following code:

struct Distance
{
int feet;
float inch;
};

int main()
{
struct Distance d1, d2;
}

We can use typedef to write an equivalent code with a simplified syntax:


typedef struct Distance
{
int feet;
float inch;
} distances;

int main()
{
distances d1, d2;
}

#include <stdio.h>
#include <string.h>

// struct with typedef person


typedef struct Person
{
char name[50];
int uin;
float salary;
} person;

int main() {

// create Person variable


person p1;

// assign value to name of p1


strcpy(p1.name, "Amar");

// assign values to other p1 variables


p1.uin = 1947;
p1. salary = 10000;

// print struct variables


printf("Name: %s\n", p1.name);
printf("Aadhar No.: %d\n", p1.uin);
printf("Salary: %.2f", p1.salary);

return 0;
}

Output
Name: Amar
Aadhar No.: 1947
Salary: 10000

Here, we have used typedef with the Person structure to create an alias person.
// struct with typedef person
typedef struct Person
{
// code
} person;

Now, we can simply declare a Person variable using the person alias:
// equivalent to struct Person p1
person p1;

Nested Structures

You can create structures within a structure in C programming. For example,


struct complex
{
int imag;
float real;
};

struct number
{
struct complex comp;
int integers;
} num1, num2;

Suppose, you want to set imag of num2 variable to 11. Here's how you can do it:
num2.comp.imag = 11;

#include <stdio.h>

struct complex
{
int imag;
float real;
};

struct number
{
struct complex comp;
int integer;
} num1;

int main()
{
// initialize complex variables
num1.comp.imag = 11;
num1.comp.real = 5.25;
// initialize number variable
num1.integer = 6;

// print struct variables


printf("Imaginary Part: %d\n", num1.comp.imag);
printf("Real Part: %.2f\n", num1.comp.real);
printf("Integer: %d", num1.integer);

return 0;
}

Output
Imaginary Part: 11
Real Part: 5.25
Integer: 6

Array of Structure

We can also declare an array of structure variables, in which each element of the array will
represent a structure variable. Example : struct employee emp[5]; The below program defines
an array emp of size 5. Each element of the array emp is of type Employee.

#include<stdio.h>

void main()
{
struct Employee
{
char ename[10];
int sal;
};

struct Employee emp[5];


int i, j;

for(i = 0; i < 3; i++)


{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
Structure as Function Arguments

We can pass a structure as a function argument just like we pass any other variable or an
array as a function argument.

Example:
#include<stdio.h>

struct Student
{
char name[10];
int roll;
};

void show(struct Student st);

void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}

void show(struct Student st)


{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}

Union

Unions are conceptually similar to structures. The syntax to declare/define a union is also
similar to that of a structure. The only differences is in terms of storage. In structure each
member has its own storage location, whereas all members of union uses a single shared
memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot
handle all the members at the same time. A union is declared using the union keyword.

union item
{
int m;
float x;
char c;
}it1;

This declares a variable it1 of type union item. This union contains three members each with
a different data type. However only one of them can be used at a time. This is due to the fact
that only one location is allocated for all the union variables, irrespective of their size. The
compiler allocates the storage that is large enough to hold the largest variable type in the
union.
In the union declared above the member x requires 4 bytes which is largest amongst the
members for a 16-bit machine. Other members of union will share the same memory address.
Accessing a Union Member in C

Syntax for accessing any union member is similar to accessing structure members,

union test
{
int a;
float b;
char c;
}t;

t.a; //to access members of union t


t.b;
t.c;

#include <stdio.h>
union item
{
int a;
float b;
char ch;
};

int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';

printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);

return 0;
}

Output
-26426
20.1999
z

As you can see here, the values of a and b get corrupted and only variable c prints the
expected result. This is because in union, the memory is shared among different data types.
Hence, the only member whose value is currently stored will have the memory. In the above
example, value of the variable c was stored at last, hence the value of other variables is lost.

You might also like