PCDS Mod-2 Notes
PCDS Mod-2 Notes
C Library Functions
In order to use these functions, we have to include the header file in the program. Below are
some header files with descriptions:
The prototype and data definitions of these functions are present in their respective header
files. To use these functions we need to include the header file in our program.
For example,
If you want to use the printf() function, the header file <stdio.h> should be included.
S Header
No. Files Description
These limits specify that a variable cannot store any value beyond
these limits, for example-
4 <limits.h> An unsigned character can store up to a maximum value of 255.
1. stdio.h: This library is use to use the printf() function, the header file <stdio.h>
should be included in the program.
Implementation
// C program to implement
int main()
printf(" C PROGRAMMING");
return 0;
Output
C PROGRAMMING
Example 1: sqrt()
Syntax-
double sqrt(double x)
#include <math.h>
#include <stdio.h>
int main()
number = 12.5;
squareRoot = sqrt(number);
return 0;
Output
Example 2- pow():
Syntax:
#include <math.h>
#include <stdio.h>
int main()
base = 10.0;
power = 2.0;
return 0;
Output
10.0^2.0 = 100.00
Example 3- sin():
Syntax:
double sin(double x)
#include <math.h>
#include <stdio.h>
int main()
double x;
double result;
x = 2.3;
result = sin(x);
x = -2.3;
result = sin(x);
x = 0;
result = sin(x);
return 0;
Output
sin(2.30) = 0.75
sin(-2.30) = -0.75
sin(0.00) = 0.00
Example 4- cos():
Syntax:
double cos(double x);
Below is the C program to calculate the cosine of an argument:
#include <math.h>
#include <stdio.h>
#define PI 3.141592654
int main()
result = cos(arg);
return 0;
Output
Syntax:
double tan(double x);
#include <math.h>
#include <stdio.h>
int main()
double x;
double result;
x = 2.3;
result = tan(x);
result = tan(x);
return 0;
Output
tan(2.30) = -1.12
tan(-2.30) = 1.12
Example 6- log():
Syntax-
#include <math.h>
#include <stdio.h>
int main()
result = log(num);
printf("log(%.1f) = %.2f",
num, result);
return 0;
Output
log(5.6) = 1.72
3. float.h: The float.h header file of the C Standard Library contains a set of various
platform-dependent constants related to floating-point values.
#include <float.h>
#include <stdio.h>
int main()
FLT_MAX);
FLT_MIN);
Output
#include <limits.h>
#include <stdio.h>
int main()
CHAR_BIT);
SCHAR_MIN);
SCHAR_MAX);
UCHAR_MAX);
SHRT_MIN);
SHRT_MAX);
printf("Minimum value of INT = %d\n",
INT_MIN);
INT_MAX);
CHAR_MIN);
CHAR_MAX);
LONG_MIN);
LONG_MAX);
return (0);
Output
5. time.h: This header file defines the date and time functions.
#include <stdio.h>
#include <time.h>
int main(void)
char buffer[SIZE];
time_t curtime;
curtime = time(NULL);
loctime = localtime(&curtime);
fputs(asctime(loctime), stdout);
fputs(buffer, stdout);
strftime(buffer, SIZE, "The time is %I:%M %p.\n", loctime);
fputs(buffer, stdout);
return 0;
Output
6. string.h: For using string functions, it is necessary to include string.h header file in the
program.
Syntax-
#include <stdio.h>
#include <string.h>
int main()
strcat(str1, str2);
// in str1
puts(str1);
return 0;
Output
BCE BBSR
Example 2- strcmp(): It compares two strings. If the return value is 0 then the strings are
equal or if the return value is non-zero then the strings are not equal.
Syntax:
#include <stdio.h>
#include <string.h>
int main()
str2[] = "bCe",
str3[] = "Bce";
int result;
return 0;
Output
Example 3 – strcpy(): The strcpy() function copies the string pointed by the source to the
destination.
Syntax:
char* strcpy(char* destination, const char* source);
#include <stdio.h>
#include <string.h>
int main()
{
char str2[20];
strcpy(str2, str1);
puts(str2);
return 0;
Output
BCE BBSR
Example 4 – strlen(): This function calculates the length of the given string.
Syntax:
#include <stdio.h>
#include <string.h>
int main()
strlen(a));
strlen(b));
return 0;
Output
Length of string a = 7
Length of string b = 3
7. complex.h: Functions in this header file are used to perform various operations
on complex numbers.
Complex numbers are the ones with the real and imaginary parts.
#include <complex.h>
#include <stdio.h>
int main(void)
imag = 4.9;
creal(conj_f),
cimag(conj_f));
Output:
z = 1.3 - 4.9i
8. assert.h: Assertions are statements used to test assumptions made by programmers.
For example, we may use an assertion to check if the pointer returned by malloc() is NULL
or not.
Syntax-
void assert(int expression);
#include <assert.h>
#include <stdio.h>
int main()
int x = 7;
x = 9;
assert(x == 7);
return 0;
Output
c:7: main: Assertion `x == 7' failed.
1. One of the most important reasons you should use library functions is simply because they
work. These functions have gone through multiple rigorous testing and are easy to use.
Since, the functions are "standard library" functions, a dedicated group of developers
constantly make them better. In the process, they are able to create the most efficient code
optimized for maximum performance.
Since the general functions like printing to a screen, calculating the square root, and many
more are already written. You shouldn't worry about creating them once again.
With ever-changing real-world needs, your application is expected to work every time,
everywhere. And, these library functions help you in that they do the same thing on every
computer.
Syntax
The return_type can be any valid C data type, and the function_name can be any valid
identifier. The parameter list specifies the arguments that the function takes as input, and the
body of the function contains the statements that are executed when the function is called.
Example:
Here is an example of a user-defined function that takes two integers as input and returns
their sum:
#include <stdio.h>
int main() {
int num1 = 5, num2 = 10, result;
result = add(num1, num2);
printf("The sum of %d and %d is %d\n", num1, num2, result);
return 0;
}
Output:
This type of function returns a value to the calling function. The return statement is used to
return a value from the function. Here is an example of a function with return value:
#include <stdio.h>
int main() {
int a = 10, b = 20, c;
c = max(a, b);
printf("The maximum of %d and %d is %d\n", a, b, c);
return 0;
}
Output:
This type of function does not return any value to the calling function. The return statement
is not used in this type of function. Here is an example of a function without return value:
#include <stdio.h>
void greet() {
printf("Hello World!\n");
}
int main() {
greet();
return 0;
}
Output:
Hello World!
Reusability: One of the main benefits of user-defined functions is that they can be reused in
different parts of a program.
Simplified code: User-defined functions can simplify the code by abstracting away complex
logic into a single function
Better testing: By breaking down a program into smaller functions, it becomes easier to test
each function individually.
Output:
int main() {
int num = 5;
if (is_even(num)) {
printf("%d is even\n", num);
} else {
printf("%d is odd\n", num);
}
return 0;
}
Output:
5 is odd
Example 3: Function to swap two integers.
#include <stdio.h>
int main() {
int num1 = 5, num2 = 10;
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping: num1 = %d,
num2 = %d\n", num1, num2);
return 0;
}
Output:
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example, tower of
Hanoi, Fibonacci series, factorial finding, etc.
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void recurse()
... .. ...
recurse();
... .. ...
int main()
... .. ...
recurse();
... .. ...
}
Working of Recursion
#include <stdio.h>
int main() {
scanf("%d", &number);
result = sum(number);
return 0;
}
int sum(int n) {
if (n != 0)
return n + sum(n-1);
else
return n;
Output
sum = 6
Recursion makes program elegant. However, if performance is vital, use loops instead as
recursion is usually much slower.
Advantages of recursion
2. To solve such problems which are naturally recursive such as tower of Hanoi.
Disadvantages of recursion
2. It may require a lot of memory space to hold intermediate results on the system stacks.
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
factorial = 120
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
#include<stdio.h>
int fib(int);
int main()
int n;
scanf("%d",&n);
printf("The %d term in the fibonacci series is: %d ",n,fib(n));
return 0;
int fib(int n)
if(n==0)
return 0;
if(n==1||n==2)
return 1;
Output
Output:
Ackermann Function
It’s a function with two arguments each of which can be assigned any non-negative integer.
#include <stdio.h>
int ack(int m, int n)
{
if (m == 0){
return n+1;
}
else if((m > 0) && (n == 0)){
return ack(m-1, 1);
}
else if((m > 0) && (n > 0)){
return ack(m-1, ack(m, n-1));
}
}
int main(){
int A;
A = ack(1, 2);
printf("%d", A);
return 0;
}
Output:
4
Arrays in C
C Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types, such as pointers,
structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
For example, if we want to store the marks of a student in 6 subjects, then we don't need to
define different variables for the marks in the different subject. Instead of that, we can define
an array which can store the marks in each subject at the contiguous memory locations.
Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is
stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn
later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output
80
60
70
85
75
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
int marks[]={20,30,40,50,60};
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output
20
30
40
50
60
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
Program to print the largest and second largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);
However, 2D arrays are created to implement a relational database lookalike data structure. It
provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.
data_type array_name[rows][columns];
int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays.
We will have to define at least the second dimension of the array. The two-dimensional array
can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Representation It represents multiple data items in It represents multiple data items in the form of
the form of a list. a table that contains columns and rows.
Parameters of One can easily receive it in a The parameters that receive it must define an
Receiving pointer, an unsized array, or a sized array’s rightmost dimension.
array.
Total Size (in Total number of Bytes = The size of Total number of Bytes = The size of array
terms of Bytes) array x the size of array variable or visible or datatype x the size of second index x
datatype. the size of the first index.
Applications of Arrays:
Matrix Operations
Program to perform matrix addition, matrix subtraction, matrix multiplication
Matrix Addition
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 + mat2 = {{2, 4}, {6, 8}}
Matrix Subtraction
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 - mat2 = {{0, 0}, {0, 0}}
Matrix Multiplication
mat1 = {{1, 2}, {3, 4}}mat2 = {{1, 2}, {3, 4}}mat1 * mat2 = {{7, 10}, {15, 22}}
Matrix addition:
Matrix subtraction:
Matrix multiplication:
#include <stdio.h>
int main() {
scanf("%d", &r);
scanf("%d", &c);
scanf("%d", &a[i][j]);
if (j == c - 1) {
printf("\n\n");
}
return 0;
}
Output:
Enter the number of rows (between 1 and 100): 2
-2 8 7
10 8 6
Program to substract two matrices
#include <stdio.h>
int main() {
scanf("%d", &r);
scanf("%d", &c);
scanf("%d", &a[i][j]);
scanf("%d", &b[i][j]);
if (j == c - 1) {
printf("\n\n");
return 0;
Output:
45 20
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
scanf("%d",&r);
scanf("%d",&c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mul[i][j]=0;
for(k=0;k<c;k++)
mul[i][j]+=a[i][k]*b[k][j];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
printf("%d\t",mul[i][j]);
printf("\n");
return 0;
}
Output:
int main() {
scanf("%d", &a[i][j]);
if (j == c - 1)
printf("\n");
transpose[j][i] = a[i][j];
if (j == r - 1)
printf("\n");
return 0;
Output:
Entered matrix:
1 4 0
-5 2 7
1 -5
4 2
0 7
For example: The string "home" contains 5 characters including the '\0' character which is
automatically added by the compiler at the end of the string.
Initializing a String
A string can be initialized in different ways. Below are the examples to declare a
string with the name str and initialize it with “Bce”.
1. Assigning a string literal without size: String literals can be assigned without
size. Here, the name of the string str acts as a pointer because it is an array.
char str[] = "Bce";
2. Assigning a string literal with a predefined size: String literals can be assigned
with a predefined size. But we should always account for one extra space which will
be assigned to the null character. If we want to store a string of size n then we should
always declare a string with a size equal to or greater than n+1.
char str[50] = "Bce";
3. Assigning character by character with size: We can also assign a string
character by character. But we should remember to set the end character as ‘\0’
which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
// Illegal
char str[4];
str = "hello";
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
char text[20];
gets(text);
printf("%s", text);
C language supports a large snumber of string handling functions that can be used to carry
out many of the string manipulations. These functions are packaged in the string.h library.
Hence, you must include string.h header file in your programs to use these functions.
Method Description
strcat() function in C:
Syntax:
strcat(str1,str2);
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
Example:
#include <stdio.h>
#include <string.h>
int main () {
char src[50], dest[50];
strcat(dest, src);
return(0);
}
Output:
Final destination string : |This is destinationThis is source|
strcmp() will return the ASCII difference between first unmatching character of two strings.
#include<stdio.h>
#include<string.h>
int main()
int j = strlen("studytonight");
printf("%d %d",j,i);
return 0;
Output:
12 -1
strcpy() function:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50], s2[50];
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
Output:
StudyTonight
strrev() function:
#include <stdio.h>
int main()
char s1[50];
gets(s1);
return(0);
Output:
#include <stdio.h>
#include <string.h>
int main()
printf("%s\n", str);
int length = 0;
length = strlen(str);
return 0;
Output
Bce
Length of string str is 3
We can use the fgets() function to read a line of string and gets() to read characters from the
standard input (stdin) and store them as a C string until a newline character or the End-of-
file (EOF) is reached.
#include <stdio.h>
#define MAX 50
int main()
char str[MAX];
puts(str);
return 0;
Input:
Bce
Output:
String is:
Bce
In C, there are various general problems which requires passing more than one variable of the
same type to a function. For example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be passed as the actual parameters
from the main function. Here, instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that into the function. This will
resolve all the complexity since the function will now work for any number of values.
As we know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual parameter.
functionname(arrayname);//passing array
Methods to declare a function that receives an array as an argument
There are 3 ways to declare the function which is intended to receive an array as an argument.
First way:
Second way:
Third way:
#include<stdio.h>
int minarray(int arr[ ],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}
return min;
}
int main()
{
int i=0,min=0;
int numbers[ ]={4,5,7,3,8,9};
min=minarray(numbers,6);
printf("minimum number is %d \n",min);
return 0;
}
Output
minimum number is 3
#include <stdio.h>
int main() {
result = calculateSum(num);
return 0;
sum += num[i];
return sum;
Output
Result = 162.50
To pass multidimensional arrays to a function, only the name of the array is passed to the
function (similar to one-dimensional arrays).
#include <stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;
printf("Displaying:\n");
printf("%d\n", num[i][j]);
Output
Enter 4 numbers:
2
Displaying:
Structures in C
What is a structure?
A structure is a key word that create user defined data type in C. A structure creates a data
type that can be used to group items of possibly different types into a single type.
struct Point
int x, y;
struct Point
int x, y;
};
int main()
Structure members cannot be initialized with declaration. For example the following C
program fails in compilation.
struct Point
};
The reason for above error is simple, when a datatype is declared, no memory is allocated
for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces ‘{}’. For example, following is a
valid initialization.
struct Point
int x, y;
};
int main()
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
p1.x = 20;
return 0;
Output:
x = 20, y = 1
struct Point
int x, y, z;
};
int main()
return 0;
Output:
x = 2, y = 0, z = 1
x = 20
What is an array of structures?
#include<stdio.h>
struct Point
int x, y;
};
int main()
arr[0].x = 10;
arr[0].y = 20;
Output:
10 20
Like primitive types, we can have pointer to a structure. If we have a pointer to structure,
members are accessed using arrow ( -> ) operator.
#include<stdio.h>
struct Point
int x, y;
};
int main()
// p2 is a pointer to structure p1
return 0;
Output:
12
Limitations of C Structures
The C structure does not allow the struct data type to be treated like built-in data types:
We cannot use operators like +,- etc. on Structure variables. For example, consider the
following code:
struct number
float x;
};
int main()
n1.x=4;
n2.x=3;
n3=n1+n2;
return 0;
/*
Output:
prog.c:10:7: error:
n3=n1+n2;
*/
No Data Hiding: C Structures do not permit data hiding. Structure members can be
accessed by any function, anywhere in the scope of the Structure.
Static Members: C Structures cannot have static members inside their body
Structure vs Union
Defining a structure: To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than or equal to one member. The format of
the struct statement is as follows:
struct [structure name]
member definition;
member definition;
...
member definition;
};
(OR)
member definition;
member definition;
...
member definition;
Union in C is a special data type available in C that allows storing different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of using the
same memory location for multiple purposes.
Defining a Union:
To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one
member for your program. The format of the union statement is as follows:
member definition;
member definition;
...
member definition;
};
(OR)
member definition;
member definition;
...
member definition;
1. Both are user-defined data types used to store data of different types as a single unit.
2. Their members can be objects of any type, including other structures and unions or
arrays. A member can also consist of a bit field.
3. 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.
4. 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.
5. ‘.’ operator or selection operator, which has one of the highest precedences, is used for
accessing member variables inside both the user-defined datatypes.
Differences between Structure and Union are as shown below in tabular format as shown
below as follows:
// C program to illustrate differences
#include <stdio.h>
#include <string.h>
// declaring structure
struct struct_example
int integer;
float decimal;
char name[20];
};
// declaring union
union union_example
int integer;
float decimal;
char name[20];
};
void main()
// difference five
s.integer = 183;
s.decimal = 90;
strcpy(s.name, "bce");
u.integer = 183;
u.decimal = 90;
strcpy(u.name, "bce");
printf("\nstructure data:");
s.integer = 240;
u.integer = 240;
u.decimal = 120;
//difference four
printf("\nAltering a member value:\n");
s.integer = 1218;
u.integer = 1218;
Output:
structure data:
integer: 18
decimal: 38.00
name: bce
union data:
integer: 18
decimal: 0.00
name: ?
sizeof structure: 28
sizeof union: 20
integer: 183
decimal: 90.00
name: bce
union data:
integer: 1801807207
decimal: 277322871721159510000000000.00
name: bce
structure data:
integer: 240
decimal: 120.000000
name: C programming
union data:
integer: 240
decimal: 120.000000
name: C programming
Altering a member value:
structure data:
integer: 1218
decimal: 120.00
name: C programming
union data:
integer: 1218
decimal: 0.00
name: ?
structures are better than unions since memory is shared in a union which results in a bit of
ambiguity. But technically speaking, unions are better in that they help save a lot of
memory, resulting in the overall advantage over structures in the long run.