Unit 3
Unit 3
222CPI06-UNIT 3- Notes
Syntax
The parameter name is not mandatory while declaring functions. We can also declare the function
without using the name of the data variables.
Example
Function Declaration
Function Definition
The function definition consists of actual statements which are executed when the function is called
(i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition always
starts with the function declaration so we do not need to declare it explicitly. The below example serves
as both a function definition and a declaration.
return_type function_name (para1_type para1_name, para2_type para2_name)
{
   // body of the function
}
Function Definition in C
Function Call
A function call is a statement that instructs the compiler to execute the function. We use the function
name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum function. After
the function call sum of a and b is returned and control is also returned back to the main function of the
program.
Working of function in C
Note: Function call is neccessary to bring the program control to the function definition. If not called,
the function statements will not be executed.
Example of C Function
    •   C
// Driver code
int main()
{
  // Calling sum function and
  // storing its value in add variable
  int add = sum(10, 30);
Output
Sum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and called the
function.
Function return type tells what type of value is returned after all function is executed. When we don’t
want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Note: Only one value can be returned from a C function. To return multiple values, we have to use
pointers or structures.
Function Arguments
Function Arguments (also known as Function Parameters) are the data that is passed to a function.
Example:
int function_name(int var1, int var2);
Conditions of Return Types and Arguments
In C programming language, functions can be called either with or without arguments and might return
values. They may or might not return values to the calling functions.
      1. Function with no arguments and no return value
      2. Function with no arguments and with return value
      3. Function with argument and with no return value
      4. Function with arguments and with return value
To know more about function Arguments and Return values refer to the article – Function Arguments
& Return Values in C.
How Does C Function Work?
Working of the C function can be broken into the following steps as mentioned below:
          1. Declaring a function: Declaring a function is a step where we declare a function. Here we
             define the return types and parameters of the function.
          2. Defining a function:
          3. Calling the function: Calling the function is a step where we call the function by passing
             the arguments in the function.
          4. Executing the function: Executing the function is a step where we can run all the
             statements inside the function to get the final result.
       5. Returning a value: Returning a value is the step where the calculated value after the
          execution of the function is returned. Exiting the function is the final step where all the
          allocated memory to the variables, functions, etc is destroyed before giving full control to
          the main function.
Types of Functions
There are two types of functions in C:
       1. Library Functions
       2. User Defined Functions
Types of Functions in C
1. Library Function
A library function is also referred to as a “built-in function”. A compiler package already exists that
contains these functions, each of which has a specific meaning and is included in the package. Built-in
functions have the advantage of being directly usable without being defined, whereas user-defined
functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
      • C Library functions are easy to use and optimized for better performance.
      • C library functions save a lot of time i.e, function development time.
      • C library functions are convenient as they always work.
Example:
   •   C
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
    double Number;
    Number = 49;
Output
The Square root of 49.00 = 7.00
Functions that the programmer creates are known as User-Defined functions or “tailor-made
functions”. User-defined functions can be improved and modified according to the need of the
programmer. Whenever we write a function that is case-specific and is not defined in any header file,
we need to declare and define our own functions according to the syntax.
Advantages of User-Defined Functions
       • Changeable functions can be modified as per need.
       • The Code of these functions is reusable in other programs.
       • These functions are easy to understand, debug and maintain.
Example:
      •   C
// C program to show
// user-defined functions
#include <stdio.h>
// Driver code
int main()
{
  int a = 30, b = 40;
    // function call
    int res = sum(a, b);
Output
Sum is: 70
Passing Parameters to Functions
The data passed when the function is being invoked is known as the Actual parameters. In the below
program, 10 and 30 are known as actual parameters. Formal Parameters are the variable and the data
type as mentioned in the function declaration. In the below program, a and b are known as formal
parameters.
// Driver code
int main()
{
  int var1 = 3, var2 = 2;
  printf("Before swap Value of var1 and var2 is: %d, %d\n",
       var1, var2);
  swap(var1, var2);
  printf("After swap Value of var1 and var2 is: %d, %d",
       var1, var2);
  return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 3, 2
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer to the same locations, so any
changes made inside the function are reflected in the caller’s actual parameters.
Example:
   •   C
// Driver code
int main()
{
  int var1 = 3, var2 = 2;
  printf("Before swap Value of var1 and var2 is: %d, %d\n",
       var1, var2);
  swap(&var1, &var2);
  printf("After swap Value of var1 and var2 is: %d, %d",
       var1, var2);
  return 0;
}
Output
Before swap Value of var1 and var2 is: 3, 2
After swap Value of var1 and var2 is: 2, 3
Advantages of Functions in C
Functions in C is a highly useful feature of C with many advantages as mentioned below:
       1.   The function can reduce the repetition of the same statements in the program.
       2.   The function makes code readable by providing modularity to our program.
       3.   There is no fixed number of calling functions it can be called as many times as you want.
       4.   The function reduces the size of the program.
       5.   Once the function is declared you can just use it without thinking about the internal working
            of the function.
Disadvantages of Functions in C
The following are the major disadvantages of functions in C:
       1. Cannot return multiple values.
       2. Memory and time overhead due to stack frame allocation and transfer of program control.
SUMMARY:
       1. The function is the block of code that can be reused as many times as we want inside a
          program.
       2. To use a function we need to call a function.
       3. Function declaration includes function_name, return type, and parameters.
       4. Function definition includes the body of the function.
       5. The function is of two types user-defined function and library function.
       6. In function, we can according to two types call by value and call by reference according to
          the values passed.
Questions on Functions in C
Q1. Define functions.
Answer:
Functions are the block of code that is executed every time they are called during an execution of a
program.
Q2. What is a forward declaration?
Answer:
Sometimes we define the function after its call to provide better readibliy. In such cases, we declare
function before the their defiinition and call. Such declaration are called Forward Declaration.
Q3. What is the difference between function declaration and definition?
Answer:
                               Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                           lOMoARcPSD|36483038
The data like function name, return type, and the parameter is included in the function declaration
whereas the definition is the body of the function. All these data are shared with the compiler
according to their corresponding steps.
Q4. What is the difference between function arguments and parameters?
Answer:
Function parameters are the values declared in a function declaration. Whereas, function arguments
are the values that are passed in the function during the function call.
Example:
int func(int x,int y);
func(10,20);
Here, int x and int y are parameters while, 10 and 20 are the arguments passed to the function.
To know more about it, refer to this article – Difference between Arguments and Parameters in C.
Q5. Can we return multiple values from a C Function?
Answer:
No, it is generally not possible to return multiple values from a function. But we can either
use pointers to static or heap memory locations to return multiple values or we can put data in
the structure and then return the structure.
To know more about it, refer to this article – How to return multiple values from a function in C or
C++?
Q6. What is the actual and formal parameter?
Answer:
Formal parameter: The variables declared in the function prototype is known as Formal arguments or
parameters.
Actual parameter: The values that are passed in the function are known as actual arguments or
parameters.
--------------------------------------------------------------------------------------------------------------------
Recursion
Recursion is the process of a function calling itself repeatedly till the given condition is satisfied. A
function that calls itself directly or indirectly is called a recursive function and such kind of function
calls are called recursive calls.
In C, recursion is used to solve complex problems by breaking them down into simpler sub-problems.
We can solve large numbers of problems using recursion in C. For example, factorial of a number,
generating Fibonacci series, generating subsets, etc.
int nSum(int n)
{
   // base condition to terminate the recursion when N = 0
   if (n == 0) {
      return 0;
   }
    return res;
}
int main()
{
   int n = 5;
Output
Sum of First 5 Natural Numbers: 15
Binary Search:
Binary Search is an interval searching algorithm used to search for an item in the sorted list. It works
by repeatedly dividing the list into two equal parts and then searching for the item that is the part
where it can possibly exist.
Unlike linear search, there are a few conditions for applying binary search:
       1. The list must be sorted.
       2. Random access to the list member.
It means that we cannot apply the binary search in unsorted or liked data structures.
Binary Search Program in C (Recursive)
The following C program implements the binary search algorithm using recursion:
      •     C
// driver code
int main(void)
{
   // taking a sorted array
   int arr[] = { 2, 3, 4, 10, 40 };
   int size = sizeof(arr) / sizeof(arr[0]);
   // element to be searched
   int x = 10;
   // calling binary search
   int index = binarySearch(arr, 0, size - 1, x);
    if (index == -1) {
       printf("Element is not present in array");
    }
    else {
       printf("Element is present at index %d", index);
    }
    return 0;
}
Output
Element is present at index 3
Applications of Recursion in C
Recursion is widely used to solve different kinds of problems from simple ones like printing linked
lists to being extensively used in AI. Some of the common uses of recursion are:
         • Tree-Graph Algorithms
         • Mathematical Problems
         • Divide and Conquer
         • Dynamic Programming
         • In Postfix to Infix Conversion
         • Searching and Sorting Algorithms
Advantages of C Recursion
The advantages of using recursive methods over other methods are:
      1. Recursion can effectively reduce the length of the code.
      2. Some problems are easily solved by using recursion like the tower of Hanoi and tree
          traversals.
      3. Data structures like linked lists, trees, etc. are recursive by nature so recursive methods are
          easier to implement for these data structures.
Disadvantages of C Recursion
As with almost anything in the world, recursion also comes with certain limitations some of which
are:
       1. Recursive functions make our program a bit slower due to function call overhead.
       2. Recursion functions always take extra space in the function call stack due to separate
          stack frames.
       3. Recursion methods are difficult to understand and implement.
       C Structures
   •
The••structure in C is a user-defined data type that can be used to group items of possibly different types
into a single type. The struct keyword is used to define the structure in the C programming language.
The items in the structure are called its member and they can be of any valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure declaration, we specify its
member variables along with their datatype. We can use the struct keyword to declare the structure in C
using the following syntax:
Syntax
struct structure_name {
   data_type member_name1;
   data_type member_name1;
   ....
   ....
                               Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                         lOMoARcPSD|36483038
};
The above syntax is also called a structure template or structure prototype and no memory is allocated
to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that by creating variables of
the structure type. We can define structure variables using two methods:SKIP
struct structure_name {
   data_type member_name1;
   data_type member_name1;
   ....
   ....
}variable1, varaible2, ...;
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow operator to access the
members.
Initialize Structure Members
Structure members cannot be initialized with the declaration. For example, the following C program
fails in the compilation.
struct Point
{
    int x = 0; // COMPILER ERROR: cannot initialize members here
    int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for the above error is simple. When a datatype is declared, no memory is allocated for it.
Memory is allocated only when variables are created.
Designated Initialization allows structure members to be initialized in any order. This feature has been
added in the C99 standard.
struct structure_name str = { .member1 = value1, .member2 = value2, .member3 = value3 };
The Designated Initialization is only supported in C but not in C++.
Example of Structure in C
The following C program shows how to use structures
C
   float ff;
} var; // variable declaration with structure template
// Driver code
int main()
{
   // variable declaration after structure template
   // initialization with initializer list and designated
   // initializer list
   struct str1 var1 = { 1, 'A', 1.00, "Programming in C" },
            var2;
   struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };
    return 0;
}
Output
Struct 1:
    i = 1, c = A, f = 1.000000, s = Programming in C
Struct 2:
    i = 1, c = A, f = 1.000000, s = Programming in C
Struct 3
    i = 5, c = a, f = 5.000000
typedef for Structures
The typedef keyword is used to define an alias for the already existing datatype. In structures, we have
to use the struct keyword along with the structure name to define the variables. Sometimes, this
increases the length and complexity of the code. We can use the typedef to define some new shorter
name for the structure.
Example
// structures
#include <stdio.h>
// defining structure
struct str1 {
   int a;
};
int main()
{
  // creating structure variables using new names
  str1 var1 = { 20 };
  str2 var2 = { 314 };
    return 0;
}
Output
var1.a = 20
var2.x = 314
In this method, the structure being nested is also declared inside the parent structure.
Example
struct parent {
    int member1;
    struct member_str member2 {
      int member_str1;
                                Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                         lOMoARcPSD|36483038
           char member_str2;
           ...
     }
     ...
}
In this method, two structures are declared separately and then the member structure is nested inside the
parent structure.
Example
struct member_str {
     int member_str1;
     char member_str2;
     ...
}
struct parent {
     int member1;
     struct member_str member2;
     ...
}
One thing to note here is that the declaration of the structure should always be present before its
definition as a structure member. For example, the declaration below is invalid as the struct mem is
not defined when it is declared inside the parent structure.
struct parent {
     struct mem a;
};
struct mem {
     int var;
};
We can access nested Members by using the same ( . ) dot operator two times as shown:
str_parent.str_child.member;
                               Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                            lOMoARcPSD|36483038
// driver code
int main()
{
   struct parent var1 = { 25, 195, 'A' };
    return 0;
}
Output
var1.a = 25
var1.b.x = 195
var1.b.c = A
Structure Pointer in C
We can define a pointer that points to the structure like any other variable. Such pointers are generally
called Structure Pointers. We can access the members of the structure pointed by the structure pointer
using the ( -> ) arrow operator.
// structure declaration
struct Point {
   int x, y;
};
int main()
{
  struct Point str = { 1, 2 };
    // p2 is a pointer to structure p1
    struct Point* ptr = &str;
    return 0;
}
Output
12
Self-Referential Structures
The self-referential structures in C are those structures that contain references to the same type as
themselves i.e. they contain a member of the type pointer pointing to the same structure type.
struct structure_name {
   data_type member1;
   data_type member2;
   struct structure_name* str;
}
C
// structure template
typedef struct str {
   int mem1;
   int mem2;
// driver code
int main()
{
   str var1 = { 1, 2, NULL };
   str var2 = { 10, 20, NULL };
    // pointer to var1
    str *ptr1 = &var1;
    return 0;
}
Output
var2.mem1: 10
var2.mem2: 20
Such kinds of structures are used in different data structures such as to define the nodes of linked lists,
trees, etc.
C Structure Padding and Packing
Technically, the size of the structure in C should be the sum of the sizes of its members. But it may not
be true for most cases. The reason for this is Structure Padding.
Structure padding is the concept of adding multiple empty bytes in the structure to naturally align the
data members in the memory. It is done to minimize the CPU read cycles to retrieve different data
members in the structure.
There are some situations where we need to pack the structure tightly by removing the empty bytes. In
such cases, we use Structure Packing. C language provides two ways for structure packing:
       1. Using #pragma pack(1)
       2. Using __attribute((packed))__
struct str2 {
   char c;
   int i;
} __attribute((packed)) __; // using structure packing
// driver code
int main()
{
Output
Size of str1: 8
Size of str2: 5
         C Unions
     •
The••Union is a user-defined data type in C language that can contain elements of the different data
types just like structure. But unlike structures, all the members in the C union are stored in the same
memory location. Due to this, only one member can store data at the given instance.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’ names and
data types along with the name of the union. No memory is allocated to the union in the declaration.
union union_name {
   datatype member1;
   datatype member2;
   ...
};
Keep in mind that we have to always end the union declaration with a semi-colon.P
We need to define a variable of the union type to start using union members. There are two methods
using which we can define a union variable.
        1. With Union Declaration
        2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
   datatype member1;
   datatype member2;
   ...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.
We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the nested unions.
var1.member1.memberA;
Here,
       •   var1 is a union variable.
       •   member1 is a member of the union.
       •   memberA is a member of member1.
Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning the value to it.
                               Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                             lOMoARcPSD|36483038
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.
Example of Union
     •   C
// driver code
int main()
{
    return 0;
}
Output
The value stored in member1 = 15
Size of Union
The size of the union will always be equal to the size of the largest member of the array. All the less-
sized elements can store the data in the same space without any overflow.
• C
union test2 {
  int x;
  char y;
} Test2;
union test3 {
  int arr[10];
  char y;
} Test3;
// driver code
int main()
{
   // finding size using sizeof() operator
   int size1 = sizeof(Test1);
   int size2 = sizeof(Test2);
   int size3 = sizeof(Test3);
Output
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40
Structure Union
    The size of the structure is equal to or greater than the total               The size of the union is the size of its
                     size of all of its members.                                            largest member.
    The structure can contain data in multiple members at the                     Only one member can contain data at
                           same time.                                                       the same time.
It is declared using the struct keyword. It is declared using the union keyword.
PROGRAMS
/*structure declaration*/
struct employee {
   char name[30];
   int empId;
   float salary;
};
int main()
{
   /*declare and initialization of
   structure variable*/
   struct employee emp = { "Mike", 1120, 76909.00f };
    return 0;
}
Output
Name: Mike
Id: 1120
Salary: 76909.000000
#include <stdio.h>
/*structure declaration*/
struct employee{
   char name[30];
   int empId;
   float salary;
};
int main()
{
   /*declare structure variable*/
   struct employee emp;
Output
                                Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                            lOMoARcPSD|36483038
Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543
#include <stdio.h>
struct student {
   char name[30];
   int marks[5];
   int total;
   float perc;
};
int main()
{
   struct student std;
   int i;
    printf("Enter marks:\n");
    std.total = 0;
    for (i = 0; i < 5; i++) {
       printf("Marks in subject %d ?: ", i + 1);
       scanf("%d", &std.marks[i]);
       std.total += std.marks[i];
    }
    std.perc = (float)((float)std.total / (float)500) * 100;
    return 0;
}
Output
Enter name: Mike
Enter marks:
                                  Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                            lOMoARcPSD|36483038
Marks   in    subject    1?   :    88
Marks   in    subject    2?   :    98
Marks   in    subject    3?   :    98
Marks   in    subject    4?   :    78
Marks   in    subject    5?   :    99
Name: Mike
Total: 461
Percentage: 92.20
#include <stdio.h>
struct item {
   char itemName[30];
   int qty;
   float price;
   float amount;
};
int main()
{
   struct item itm; /*declare variable of structure item*/
   struct item* pItem; /*declare pointer of structure item*/
  return 0;
                                  Downloaded by abdulla syed (abdullasyed252000@gmail.com)
                                                           lOMoARcPSD|36483038
Output
Enter product name: Pen
Enter price:5.50
Enter quantity: 15
Name: Pen
Price: 5.500000
Quantity: 15
Total Amount: 82.500000
struct distance {
   int feet;
   int inch;
};
int main()
{
   struct distance d1, d2;
    return 0;
}
Output
Enter first distance in feet & inches: 10 8
Enter second distance in feet & inches: 5 7
Total distance- Feet: 16, Inches: 3
// function declarations
struct FirstStruct TakeUserInput(void);
void DisplayOutput(struct FirstStruct Input);
int main()
{
   // create a structure to get a return from TakeUserInput function
   // Now use the DisplayOutput to print the input
   DisplayOutput(TakeUserInput());
    return 0;
}
    return inputStruct;
}
Output
Enter a number: 10
Enter a number again: 20
30
#include <stdio.h>
// union declaration
union pack {
   char a;
   int b;
   double c;
};
int main()
{
   pack p; //union object/variable declaration
    // assign value to each member one by one other it will replace last value
    p.a = 'A';
    printf("\nValue of a:%c", p.a);
    p.b = 10;
    printf("\nValue of b:%d", p.b);
    p.c = 12345.6790;
    printf("\nValue of c:%f", p.c);
    return 0;
}
Output
Occupied        size by union pack: 8
Value of        a:A
Value of        b:10
Value of        c:12345.679000
Value of        a:�, b:-377957122, c:12345.679000
#include <stdio.h>
union MyUnion {
   int num1;
   float num2;
};
int main()
{
   union MyUnion UN;
    UN.num1 = 10;
    printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);
    UN.num2 = 10.34F;
    printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);
    return 0;
}
Output
Size of union: 4
Num1: 10, Num2: 0.000000
Num1: 1092972708, Num2: 10.340000