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

Unit 3

notes
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 views36 pages

Unit 3

notes
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/ 36

lOMoARcPSD|36483038

222CPI06-UNIT 3- Notes

C programmng (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

UNIT-III FUNCTIONS , STRUCTURES & UNIONS 9


Functions: Definition of function – Declaration of function – Pass by value - Pass by reference –
Recursion - Binary Search using recursive functions.
Structures and Unions: Introduction - Need for structure data type - Structure definition – Structure
declaration - Structure within a structure - Union - Programs using Structures and Unions.
----------------------------------------------------------------------------------------------------------------------------
C Functions

••
A function in C is a set of statements that when called perform some specific task. 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.
In this article, we will learn about functions, function definition. declaration, arguments and
parameters, return values, and many more.
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.IP

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


int sum(int , int);

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Function Declaration

Note: A function in C must always be declared globally before calling it.

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
}

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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.

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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


return 0;
}

Output
Sum is: 40
As we noticed, we have not used explicit function declaration. We simply defined and called the
function.

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

Output
The Square root of 49.00 = 7.00

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

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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


return 0;
}

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.

Passing Parameters to Functions

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
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

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

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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.

Basic Structure of Recursive Functions

The basic syntax structure of the recursive functions is:


type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Basic Structure of Recursive Function in C

Example: C Program to Implement Recursion


In the below C program, recursion is used to calculate the sum of the first N natural numbers.
C
// C Program to calculate the sum of first N natural numbers
// using recursion
#include <stdio.h>

int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}

// recursive case / recursive call


int res = n + nSum(n - 1);

return res;
}

int main()
{
int n = 5;

// calling the function


int sum = nSum(n);

printf("Sum of First %d Natural Numbers: %d", n, sum);


return 0;
}
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

// C program to implement binary search using recursion


#include <stdio.h>

// A recursive binary search function. It returns location


// of x in given array arr[l..r] if present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
// checking if there are elements in the subarray
if (r >= l) {

// calculating mid point


int mid = l + (r - l) / 2;

// If the element is present at the middle itself


if (arr[mid] == x)
return mid;

// If element is smaller than mid, then it can only


// be present in left subarray
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}

// Else the element can only be present in right


// subarray
return binarySearch(arr, mid + 1, r, x);
}

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

// We reach here when element is not present in array


return -1;
}

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

Learn Data Structures & Algorithms with Programming in C

Output
Element is present at index 3

Complexity Analysis of Binary Search(Recursive)


Time Complexity: O(log n)
Auxiliary Space: O(log n), where n is the number of elements in the array.

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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand


struct structure_name variable1, variable2, .......;

Access Structure Members


We can access structure members by using the ( . ) dot operator.

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.

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

We can initialize structure members in 3 ways which are as follows:


1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.

1. Initialization using Assignment Operator

struct structure_name str;


str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };


In this type of initialization, the values are assigned in sequential order as they are declared in the
structure template.

3. Initialization using Designated Initializer List

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

// C program to illustrate the use of structures


#include <stdio.h>

// declaring structure with name str1


struct str1 {
int i;
char c;
float f;
char s[30];
};

// declaring structure with name str2


struct str2 {
int ii;
char cc;
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

// copying structure using assignment operator


var2 = var1;

printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",


var1.i, var1.c, var1.f, var1.s);
printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",
var2.i, var2.c, var2.f, var2.s);
printf("Struct 3\n\ti = %d, c = %c, f = %f\n", var3.ii,
var3.cc, var3.ff);

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

// C Program to illustrate the use of typedef with

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

// structures
#include <stdio.h>

// defining structure
struct str1 {
int a;
};

// defining new name for str1


typedef struct str1 str1;

// another way of using typedef with structures


typedef struct str2 {
int x;
} str2;

int main()
{
// creating structure variables using new names
str1 var1 = { 20 };
str2 var2 = { 314 };

printf("var1.a = %d\n", var1.a);


printf("var2.x = %d", var2.x);

return 0;
}

Output
var1.a = 20
var2.x = 314

Structure within Structure/Nested Structures


C language allows us to insert one structure into another as a member. This process is called nesting
and such structures are called nested structures. There are two ways in which we can nest one
structure into another:

1. Embedded Structure Nesting

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

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

char member_str2;
...
}
...
}

2. Separate Structure Nesting

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

Accessing Nested Members

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

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Example of Structure Nesting

// C Program to illustrate structure nesting along with


// forward declaration
#include <stdio.h>

// child structure declaration


struct child {
int x;
char c;
};

// parent structure declaration


struct parent {
int a;
struct child b;
};

// driver code
int main()
{
struct parent var1 = { 25, 195, 'A' };

// accessing and printing nested members


printf("var1.a = %d\n", var1.a);
printf("var1.b.x = %d\n", var1.b.x);
printf("var1.b.c = %c", var1.b.c);

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.

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Example of Structure Pointer

// C program to illustrate the structure pointer


#include <stdio.h>

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

// Accessing structure members using structure pointer


printf("%d %d", ptr->x, ptr->y);

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.

Example of Self-Referential Structures

struct structure_name {
data_type member1;
data_type member2;
struct structure_name* str;
}
C

// C program to illustrate the self referential structures


#include <stdio.h>

// structure template
typedef struct str {
int mem1;
int mem2;

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

struct str* next;


}str;

// driver code
int main()
{
str var1 = { 1, 2, NULL };
str var2 = { 10, 20, NULL };

// assigning the address of var2 to var1.next


var1.next = &var2;

// pointer to var1
str *ptr1 = &var1;

// accessing var2 members using var1


printf("var2.mem1: %d\nvar2.mem2: %d", ptr1->next->mem1,
ptr1->next->mem2);

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

Example of Structure Padding and Packing

// C program to illustrate structure padding and packing


#include <stdio.h>

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

// structure with padding


struct str1 {
char c;
int i;
};

struct str2 {
char c;
int i;
} __attribute((packed)) __; // using structure packing

// driver code
int main()
{

printf("Size of str1: %d\n", sizeof(struct str1));


printf("Size of str2: %d\n", sizeof(struct str2));
return 0;
}

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.

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

Different Ways to Define a Union Variable

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.

Access Union Members

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

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

// C Program to demonstrate how to use union


#include <stdio.h>

// union template or declaration


union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{

// defining a union variable


union un var1;

// initializing the union member


var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

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.

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Memory Allocation in C Union

Example 1: C program to find the size of the union

• C

// C Program to find the size of the union


#include <stdio.h>

// declaring multiple unions


union test1 {
int x;
int y;
} Test1;

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

printf("Sizeof test1: %d\n", size1);


printf("Sizeof test2: %d\n", size2);
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

printf("Sizeof test3: %d", size3);


return 0;
}

Output
Sizeof test1: 4
Sizeof test2: 4
Sizeof test3: 40

Difference between C Structure and C Union


The following table lists the key difference between the structure and union in C:

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

C program to create, declare and initialize


structure
#include <stdio.h>

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

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


Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

printf("\n Id: %d", emp.empId);


printf("\n Salary: %f\n", emp.salary);

return 0;
}

Output
Name: Mike
Id: 1120
Salary: 76909.000000

C program to read and print an employee's


detail using structure
/*C program to read and print employee's record using structure*/

#include <stdio.h>

/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};

int main()
{
/*declare structure variable*/
struct employee emp;

/*read employee details*/


printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/


printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}

Output
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543

Entered detail is:


Name: Mike
Id: 1120
Salary: 76543.000000

C program to demonstrate example of


structure of array
/*C program to demonstrate example of structure of array.*/

#include <stdio.h>

struct student {
char name[30];
int marks[5];
int total;
float perc;
};

int main()
{
struct student std;
int i;

printf("Enter name: ");


gets(std.name);

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;

printf("\nName: %s \nTotal: %d \nPercentage: %.2f", std.name, std.total, std.perc);

return 0;
}

Output
Enter name: Mike
Enter marks:
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

C program to demonstrate example of


structure pointer (structure with pointer)
/* C program to demonstrate example of structure pointer
(structure with pointer)*/

#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*/

pItem = &itm; /*pointer assignment - assigning address of itm to pItem*/

/*read values using pointer*/


printf("Enter product name: ");
gets(pItem->itemName);
printf("Enter price:");
scanf("%f", &pItem->price);
printf("Enter quantity: ");
scanf("%d", &pItem->qty);

/*calculate total amount of all quantity*/


pItem->amount = (float)pItem->qty * pItem->price;

/*print item details*/


printf("\nName: %s", pItem->itemName);
printf("\nPrice: %f", pItem->price);
printf("\nQuantity: %d", pItem->qty);
printf("\nTotal Amount: %f", pItem->amount);

return 0;
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Output
Enter product name: Pen
Enter price:5.50
Enter quantity: 15

Name: Pen
Price: 5.500000
Quantity: 15
Total Amount: 82.500000

C program to add two distances in feet and


inches using structure
#include <stdio.h>

struct distance {
int feet;
int inch;
};

void addDistance(struct distance d1, struct distance d2)


{
struct distance d3;
d3.feet = d1.feet + d2.feet;
d3.inch = d1.inch + d2.inch;

d3.feet = d3.feet + d3.inch / 12; //1 feet has 12 inches


d3.inch = d3.inch % 12;

printf("\nTotal distance- Feet: %d, Inches: %d", d3.feet, d3.inch);


}

int main()
{
struct distance d1, d2;

printf("Enter first distance in feet & inches:");


scanf("%d%d", &d1.feet, &d1.inch);

printf("Enter second distance in feet & inches:");


scanf("%d%d", &d2.feet, &d2.inch);

/*add two distances*/


addDistance(d1, d2);

return 0;
}

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

Output
Enter first distance in feet & inches: 10 8
Enter second distance in feet & inches: 5 7
Total distance- Feet: 16, Inches: 3

C program for passing structures as function


arguments and returning a structure from a
function
#include <stdio.h>

// Lets create a structure first


struct FirstStruct {
int Num1;
int Num2;
} FirstStruct_IP;

// function declarations
struct FirstStruct TakeUserInput(void);
void DisplayOutput(struct FirstStruct Input);

// structure object declaration


struct FirstStruct inputStruct;

int main()
{
// create a structure to get a return from TakeUserInput function
// Now use the DisplayOutput to print the input
DisplayOutput(TakeUserInput());

return 0;
}

// This function returns a structure after storing


// the user input into it
struct FirstStruct TakeUserInput(void)
{
printf("Enter a number: ");
scanf("%d", &inputStruct.Num1);
printf("Enter a number again: ");
scanf("%d", &inputStruct.Num2);

return inputStruct;
}

// Function taking Structure as argument


void DisplayOutput(struct FirstStruct Input)
{
Downloaded by abdulla syed (abdullasyed252000@gmail.com)
lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

printf("%d\n", ((Input.Num1) + (Input.Num2)));


}

Output
Enter a number: 10
Enter a number again: 20
30

C program to declare, initialize an union,


example of union
/*C program to declare, initialize a UNION,
example of UNION*/

#include <stdio.h>

// union declaration
union pack {
char a;
int b;
double c;
};

int main()
{
pack p; //union object/variable declaration

printf("\nOccupied size by union pack: %d", sizeof(pack));

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

// see, what will happen? if u will assign values together


p.a = 'A';
p.b = 10;
p.c = 12345.6790;

// here the last value of p.c will be accessed by all members


printf("\nValue of a:%c, b:%d, c:%f", p.a, p.b, p.c);

return 0;
}

Downloaded by abdulla syed (abdullasyed252000@gmail.com)


lOMoARcPSD|36483038

222CPI06 – PROGRAMMING IN C SAKTHIDEVI.I

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

C program to find the size of the union


// C program to find the size of union

#include <stdio.h>

union MyUnion {
int num1;
float num2;
};

int main()
{
union MyUnion UN;

printf("Size of union: %ld", sizeof(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

Downloaded by abdulla syed (abdullasyed252000@gmail.com)

You might also like