Professional Documents
Culture Documents
ICP Ref Material
ICP Ref Material
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.
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 main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
return 0;
}
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.
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.
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.
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.
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;
result = sum(number);
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.
#include <stdio.h>
int main()
{
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
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;
When the above code is compiled and executed, it produces the following result
0
1
1
2
3
5
8
13
21
34
Structures:
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.
int main()
{
struct Person person1, person2, p[20];
return 0;
}
In both cases,
person1 and person2 are struct Person variables
p[] is a struct Person array of size 20.
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>
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;
}
int main()
{
distances d1, d2;
}
#include <stdio.h>
#include <string.h>
int main() {
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
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;
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;
};
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 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);
}
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;
#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.