0% found this document useful (0 votes)
11 views17 pages

HW1248

Unit 5 covers functions in C programming, detailing their syntax, types, and advantages such as modularity and code reusability. It explains function declarations, definitions, calls, and the differences between library and user-defined functions. Additionally, it introduces structures and unions, highlighting their definitions, memory allocation, and usage in grouping different data types.

Uploaded by

ap2.brothers3151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views17 pages

HW1248

Unit 5 covers functions in C programming, detailing their syntax, types, and advantages such as modularity and code reusability. It explains function declarations, definitions, calls, and the differences between library and user-defined functions. Additionally, it introduces structures and unions, highlighting their definitions, memory allocation, and usage in grouping different data types.

Uploaded by

ap2.brothers3151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit – 5

Working with Functions in C Programming

Functions in C are reusable blocks of code that perform specific tasks. They help organize
code, improve readability, and facilitate debugging.

A function in C is a set of statements that when called perform some specific tasks. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain
meanings and performing certain operations. They are also called subroutines or procedures
in other languages.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls

Function Declarations
In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function
with the given name defined somewhere else in the program.

Syntax
return_type name_of_the_function (parameter_1, parameter_2);

The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.

Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
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 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.
// C program to show function call and definition

#include <stdio.h>

// Function that takes two parameters a and b as inputs and returns their sum

int sum(int a, int b)

return a + b;

// Driver code

int main()

// Calling sum function and

// storing its value in add variable

int add = sum(10, 30);

printf("Sum is: %d", add);

return 0;

Function Return Type


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);

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

Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions

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 program to implement

// the above approach

#include <math.h>

#include <stdio.h>

// Driver code

int main()

double Number;
Number = 49;

// Computing the square root with

// the help of predefined C

// library function

double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",

Number, squareRoot);

return 0;

2. User Defined Function


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 program to show

// user-defined functions

#include <stdio.h>

int sum(int a, int b)

return a + b;

// Driver code

int main()

{
int a = 30, b = 40;

// function call

int res = sum(a, b);

printf("Sum is: %d", res);

return 0;

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.

We can pass arguments to the C function in two ways:


1. Pass by Value
2. Pass by Reference

1. Pass by Value
Parameter passing in this method copies values from actual parameters into formal function
parameters. As a result, any changes made inside the functions do not reflect in the caller’s
parameters.
Example:
// C program to show use
// of call by value
#include <stdio.h>

void swap(int var1, int var2)


{
int temp = var1;
var1 = var2;
var2 = temp;
}

// 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;
}

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 program to show use of

// call by Reference

#include <stdio.h>

void swap(int *var1, int *var2)

int temp = *var1;

*var1 = *var2;

*var2 = temp;

// 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;

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.

1. Utility of Functions

 Modularity: Functions break the program into smaller, manageable, and reusable
modules.
 Code Reusability: Once written, a function can be reused multiple times.
 Improved Debugging: Errors can be isolated to specific functions, making
debugging easier.
 Code Readability: By breaking down the logic into functions, the overall structure of
the code becomes cleaner and easier to understand.

Example:

int add(int a, int b) {


return a + b;
}
int main() {
int sum = add(5, 10);
printf("Sum: %d\n", sum);
return 0;
}

2. Return Values and Their Types

 A function in C can return a value to the caller using the return keyword.
 The return type is specified in the function declaration and definition.
Example:

int multiply(int a, int b) {


return a * b; // Returns an integer
}

int main() {
int result = multiply(3, 4);
printf("Result: %d\n", result); // Output: 12
return 0;
}

 Functions can also return other data types like float, char, void (no return value),
and even pointers.

3. Differentiating Between Declaration and Definition of Function


Arguments/Parameters

 Function Declaration (Prototype):


o Specifies the function's name, return type, and parameters without the body.
o Declared before the main() function or in a header file.
o Example:

int add(int, int); // Function declaration

Function Definition:

 Provides the implementation of the function.


 Includes the function body where the actual logic resides.
 Example:

int add(int a, int b) { // Function definition


return a + b;
}
Function Call:

 Executes the function by passing the required arguments.


 Example:

int result = add(5, 10); // Function call

4. Recursion

 Definition: Recursion occurs when a function calls itself directly or indirectly.


 Uses: Useful for solving problems like factorial, Fibonacci sequence, and tree
traversal.
 Base Case: To prevent infinite recursion, a base case must be defined.

Example:

int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}

int main() {
int result = factorial(5); // 5! = 5 * 4 * 3 * 2 * 1
printf("Factorial: %d\n", result); // Output: 120
return 0;
}

 Key Notes:
o Recursive functions can be memory-intensive due to multiple function calls on
the stack.
o Iterative solutions are often preferred for performance-critical applications.

Summary

 Functions are essential for structuring code efficiently.


 Call by Value passes a copy of the variable, while Call by Reference passes the
address.
 Library Functions provide built-in functionality, while User-Defined Functions are
custom-made.
 Differentiating declaration and definition is critical for understanding program
structure.
 Recursion is a powerful but resource-intensive tool that simplifies complex problems.

Structures and Unions in C Programming


In C, structures and unions allow you to group different types of data under one entity.
While structures are used to group related variables of different data types, unions provide a
way to store different types of data in the same memory location.

Parameter Structure Union

A structure is a user-defined A union is a user-defined data


data type that groups type that allows storing
different data types into a different data types at the
Definition single entity. same memory location.

The keyword struct is used The keyword union is used to


Keyword to define a structure define a union

The size is the sum of the The size is equal to the size of
sizes of all members, with the largest member, with
Size padding if necessary. possible padding.

Each member within a


Memory Memory allocated is shared by
structure is allocated unique
individual members of union.
Allocation storage area of location.

Data No data overlap as members Full data overlap as members


Overlap are independent. shares the same memory.

Accessing Individual member can be Only one member can be


Members accessed at a time. accessed at a time.

Structures in C

1. Structure Definition

A structure is a user-defined data type that groups variables of different types under one name.
A structure in C is a collection of variables, possibly of different types, under a single name.
Each member of the structure is allocated its own memory space, and the size of the structure
is the sum of the sizes of all its members.

Syntax
struct name {
member1 definition;
member2 definition;

memberN definition;
};
Example:
#include <stdio.h>

struct Student {
char name[50];
int age;
float grade;
};

int main() {

// Create a structure variable


struct Student s1 = {"Geek", 20, 85.5};

// Access structure members


printf("%s\n", s1.name);
printf("%d\n", s1.age);
printf("%.2f\n", s1.grade);
printf("Size: %d bytes", sizeof(s1));

return 0;
}

2. Declaring and Initializing Structure Variables

 Declaring Structure Variables:


After defining a structure, you can declare variables of that type. Example:

struct Student s1, s2;

 Initializing Structure Variables:


You can initialize structure variables at the time of declaration or later.
Example:
struct Student s1 = {101, "Alice", 95.5}; // Initialization at declaration
struct Student s2;
s2.id = 102; // Initialization later
strcpy(s2.name, "Bob");
s2.marks = 89.0;
3. Accessing Structure Members

 The dot operator (.) is used to access structure members.

Example:

printf("ID: %d\n", s1.id);

printf("Name: %s\n", s1.name);

printf("Marks: %.2f\n", s1.marks);

4. Example Program: Using Structures

#include <stdio.h>

#include <string.h>

struct Student {

int id;

char name[50];

float marks;

};

int main() {

struct Student s1 = {101, "Alice", 95.5};

struct Student s2;

// Initialize s2

s2.id = 102;

strcpy(s2.name, "Bob");

s2.marks = 89.0;

// Print details

printf("Student 1: ID=%d, Name=%s, Marks=%.2f\n", s1.id, s1.name, s1.marks);


printf("Student 2: ID=%d, Name=%s, Marks=%.2f\n", s2.id, s2.name, s2.marks);

return 0;

Unions in C

1. Union Definition

A union is a user-defined data type where all members share the same memory location. This
means only one member can hold a value at any time.
A union in C is similar to a structure, but with a key difference: all members of a union share
the same memory location. This means only one member of the union can store a value at
any given time. The size of a union is determined by the size of its largest member.
Syntax:
union name {
member1 definition;
member2 definition;

memberN definition;
};
Example:

 Example:

#include <stdio.h>

union Data {
int i;
double d;
char c;
};

int main() {

// Create a union variable


union Data data;

// Store an integer in the union


data.i = 100;
printf("%d
", data.i);

// Store a double in the union (this will


// overwrite the integer value)
data.d = 99.99;
printf("%.2f
", data.d);

// Store a character in the union (this will


// overwrite the double value)
data.c = 'A';
printf("%c
", data.c);

printf("Size: %d", sizeof(data));

return 0;
}

2. Initializing and Using Unions

 Initializing Union Variables: You can initialize only one member of a union at a time.

Example:

union Data d1;

d1.i = 10; // Assigns value to `i`

Accessing Union Members:

 Similar to structures, use the dot operator (.) to access union members.
 Since all members share the same memory, modifying one member affects others.

Example:

union Data d1;

d1.i = 10;

printf("i: %d\n", d1.i);

d1.f = 3.14;

printf("f: %.2f\n", d1.f);

3. Example Program: Using Unions

#include <stdio.h>

#include <string.h>

union Data {
int i;

float f;

char str[20];

};

int main() {

union Data d1;

// Assign integer value

d1.i = 10;

printf("Integer: %d\n", d1.i);

// Assign float value

d1.f = 3.14;

printf("Float: %.2f\n", d1.f);

// Assign string value

strcpy(d1.str, "Hello");

printf("String: %s\n", d1.str);

// Observe memory sharing

printf("After modifying str, i: %d, f: %.2f\n", d1.i, d1.f);

return 0;

Similarities Between Structure and Union


Structures and unions are also similar in some aspects listed below:
 Both are user-defined data types used to store data of different types as a single unit.
 Their members can be objects of any type, including other structures and unions or arrays.
A member can also consist of a bit field.
 Both structures and unions support only assignment = and sizeof operators. The two
structures or unions in the assignment must have the same members and member types.
 A structure or a union can be passed by value to functions and returned by value by
functions. The argument must have the same type as the function parameter. A structure
or union is passed by value just like a scalar variable as a corresponding parameter.
 ‘.’ operator or selection operator, which has one of the highest precedences, is used for
accessing member variables inside both the user-defined datatypes.

Applications of Structures and Unions

 Structures:
o Used for creating data models like student records, employee details, or custom
data types.
 Unions:
o Useful in situations where memory usage is critical, such as in embedded
systems.
o Example: Creating data structures for protocols (e.g., interpreting network
packets).

---------------------------------------------xxxx-------------------------------------------------

You might also like