0% found this document useful (0 votes)
6 views

PCDS Mod-2 Notes

Programing using C and DS mod 2

Uploaded by

monalishadash43
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)
6 views

PCDS Mod-2 Notes

Programing using C and DS mod 2

Uploaded by

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

MODULE-2

C Library Functions

The Standard Function Library in C is a huge library of sub-libraries, each of which


contains the code for several functions. In order to make use of these libraries, link each
library in the broader library through the use of header files.

In order to use these functions, we have to include the header file in the program. Below are
some header files with descriptions:

C Standard library functions or simply C Library functions are inbuilt functions in C


programming.

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

It checks the value of an expression that we expect to be true under


1 <assert.h> normal circumstances.
S Header
No. Files Description

If the expression is a nonzero value, the assert macro does nothing.

2 <complex.h> A set of functions for manipulating complex numbers.

Defines macro constants specifying the implementation-specific


properties of the
3 <float.h> floating-point library.

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.

The math.h header defines various mathematical functions and one


macro. All the Functions
in this library take double as an argument and return double as the
5 <math.h> result.

The stdio.h header defines three variable types, several macros,


and various
6 <stdio.h> function for performing input and output.

7 <time.h> Defines date and time handling functions.

Strings are defined as an array of characters. The difference


between a character array
and a string is that a string is terminated with a special character
8 <string.h> ‘\0’.

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

// the above approach


#include <stdio.h>

int main()

printf(" C PROGRAMMING");

return 0;

Output

C PROGRAMMING

2. math.h– To perform any operation related to mathematics, it is necessary to include


math.h header file.

Example 1: sqrt()

Syntax-
double sqrt(double x)

Below is the C program to calculate the square root of any number:

#include <math.h>

#include <stdio.h>

int main()

double number, squareRoot;

number = 12.5;
squareRoot = sqrt(number);

printf("Square root of %.2lf = %.2lf", number, squareRoot);

return 0;

Output

Square root of 12.50 = 3.54

Example 2- pow():

Syntax:

double pow(double x, double y)

Below is the C program to calculate the power of any number:

#include <math.h>

#include <stdio.h>

int main()

double base, power, result;

base = 10.0;

power = 2.0;

result = pow(base, power);


printf("%.1lf^%.1lf = %.2lf", base, power, result);

return 0;

Output

10.0^2.0 = 100.00
Example 3- sin():

Syntax:

double sin(double x)

Below is the C program to calculate the sin of an argument:

#include <math.h>

#include <stdio.h>

int main()

double x;

double result;

x = 2.3;

result = sin(x);

printf("sin(%.2lf) = %.2lf\n", x, result);

x = -2.3;
result = sin(x);

printf("sin(%.2lf) = %.2lf\n", x, result);

x = 0;

result = sin(x);

printf("sin(%.2lf) = %.2lf\n", x, result);

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

double arg = 30, result;


arg = (arg * PI) / 180;

result = cos(arg);

printf("cos of %.2lf radian = %.2lf", arg, result);

return 0;

Output

cos of 0.52 radian = 0.87


Example 5- tan():

Syntax:
double tan(double x);

Below is the C program to calculate the tangent of the argument:

#include <math.h>

#include <stdio.h>

int main()

double x;

double result;

x = 2.3;

result = tan(x);

printf("tan(%.2lf) = %.2lf\n", x, result);


x = -2.3;

result = tan(x);

printf("tan(%.2lf) = %.2lf\n", x, result);

return 0;

Output

tan(2.30) = -1.12
tan(-2.30) = 1.12

Example 6- log():

Syntax-

double log( double arg );

Below is the C program to calculate the natural logarithm of an argument-

#include <math.h>

#include <stdio.h>

int main()

double num = 5.6, result;

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.

Below is the C program to implement the above approach-

#include <float.h>

#include <stdio.h>

int main()

printf("Maximum value of float = %.10e\n",

FLT_MAX);

printf("Minimum value of float = %.10e\n",

FLT_MIN);

Output

Maximum value of float = 3.4028234664e+38


Minimum value of float = 1.1754943508e-38
4. limits.h: The limits.h header determines various properties of the various variable types.
The macros defined in this header limits the values of various variable types like char, int,
and long.

Below is the C program to implement the above approach-

#include <limits.h>

#include <stdio.h>

int main()

printf("Number of bits in a byte %d\n",

CHAR_BIT);

printf("Minimum value of SIGNED CHAR = %d\n",

SCHAR_MIN);

printf("Maximum value of SIGNED CHAR = %d\n",

SCHAR_MAX);

printf("Maximum value of UNSIGNED CHAR = %d\n",

UCHAR_MAX);

printf("Minimum value of SHORT INT = %d\n",

SHRT_MIN);

printf("Maximum value of SHORT INT = %d\n",

SHRT_MAX);
printf("Minimum value of INT = %d\n",

INT_MIN);

printf("Maximum value of INT = %d\n",

INT_MAX);

printf("Minimum value of CHAR = %d\n",

CHAR_MIN);

printf("Maximum value of CHAR = %d\n",

CHAR_MAX);

printf("Minimum value of LONG = %ld\n",

LONG_MIN);

printf("Maximum value of LONG = %ld\n",

LONG_MAX);

return (0);

Output

Number of bits in a byte 8


Minimum value of SIGNED CHAR = -128
Maximum value of SIGNED CHAR = 127
Maximum value of UNSIGNED CHAR = 255
Minimum value of SHORT INT = -32768
Maximum value of SHORT INT = 32767
Minimum value of INT = -2147483648
Maximum value of INT = 2147483647
Minimum value of CHAR = -128
Maximum value of CHAR = 127
Minimum value of LONG = -9223372036854775808
Maximum value of LONG = 9223372036854775807

5. time.h: This header file defines the date and time functions.

Below is the C program to implement time() and localtime() functions-

#include <stdio.h>

#include <time.h>

#define SIZE 256

int main(void)

char buffer[SIZE];

time_t curtime;

struct tm* loctime;

curtime = time(NULL);

loctime = localtime(&curtime);

fputs(asctime(loctime), stdout);

strftime(buffer, SIZE, "Today is %A, %B %d.\n", loctime);

fputs(buffer, stdout);
strftime(buffer, SIZE, "The time is %I:%M %p.\n", loctime);

fputs(buffer, stdout);

return 0;

Output

Sun Sep 26 17:27:47 2022


Today is Monday, Sep 26.
The time is 05:27 PM.

6. string.h: For using string functions, it is necessary to include string.h header file in the
program.

Example 1: strcat(): In C programming, the strcat() functions are used to concatenate(join)


two strings. This function concatenates the destination string and the source string, and the
result is stored in the destination string.

Syntax-

char *strcat(char *destination, const char *source)


Below is the C program to implement strcat():

#include <stdio.h>

#include <string.h>

int main()

char str1[100] = "BCE ",

str2[100] = " BBSR";


// Concatenates str1 and str2

strcat(str1, str2);

// Resultant string is stored

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

int strcmp (const char* str1, const char* str2);

Below is the C program to implement strcmp():

#include <stdio.h>

#include <string.h>

int main()

char str1[] = "Bce",

str2[] = "bCe",
str3[] = "Bce";

int result;

result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result);

result = strcmp(str1, str3);

printf("strcmp(str1, str3) = %d\n", result);

return 0;

Output

strcmp(str1, str2) = -32


strcmp(str1, str3) = 0

Example 3 – strcpy(): The strcpy() function copies the string pointed by the source to the
destination.

Syntax:
char* strcpy(char* destination, const char* source);

Below is the C program to implement the strcpy():

#include <stdio.h>

#include <string.h>

int main()
{

char str1[20] = " BCE BBSR";

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:

int strlen(char a[]);

Below is the C program to implement strlen():

#include <stdio.h>

#include <string.h>

int main()

char a[20] = "Program";

char b[20] = { "BCE" };


printf("Length of string a = %zu \n",

strlen(a));

printf("Length of string b = %zu \n",

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.

Below is the C program to implement conjugate of a complex number-

#include <complex.h>

#include <stdio.h>

int main(void)

double real = 1.3,

imag = 4.9;

double complex z = real+imag*I;

double complex conj_f = conjf(z);


printf("z = %.1f + %.1fi\n",

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.

Advantages of Using C library functions

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.

2. The functions are optimized for performance.

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.

3. It saves considerable development time

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.

4. The functions are portable

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.

User defined function in C


User-defined functions are a powerful feature of C programming language that allows users
to define their own functions to perform specific tasks. Functions are a set of statements that
are combined to perform a specific task. These functions can be called anywhere in the
program, making the code more modular and easier to read.

Syntax

The syntax of a user-defined function in C is as follows:

return_type function_name( parameter list) {


body of the function
}

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 add(int a, int b) {


int sum = a + b;
return sum;
}

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:

The sum of 5 and 10 is 15

Types of User-Defined Functions

There are two types of user-defined functions in C:

1. Function with return value

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 max(int num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}

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:

The maximum of 10 and 20 is 20

2. Function without return value

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!

Benefits of User-Defined Functions

There are several benefits to using user-defined functions in C programming, including:

Reusability: One of the main benefits of user-defined functions is that they can be reused in
different parts of a program.

Modularity: User-defined functions promote modularity in a program by breaking it down


into smaller, manageable parts.

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.

Improved collaboration: User-defined functions can improve collaboration by making it


easier for multiple developers to work on different parts of a program simultaneously.

Examples of User-Defined Functions

Here are a few examples of user-defined functions in C programming:

Example 1: Function to calculate the factorial of a number.


#include <stdio.h>

int factorial(int num) {


int fact = 1;
for (int i = 1; i<= num; i++) {
fact = fact * i;
}
return fact;
}
int main() {
int num = 5;
int result = factorial(num);
printf("The factorial of %d is %d\n", num, result);
return 0;
}

Output:

The factorial of 5 is 120

Example 2: Function to check if a number is even or odd.


#include <stdio.h>

int is_even(int num) {


if (num % 2 == 0) {
return 1;
} else {
return 0;
}
}

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>

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

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:

Before swapping: num1 = 5, num2 = 10


After swapping: num1 = 10, num2 = 5

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.

Recursion involves several numbers of recursive calls.


Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.

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.

How recursion works?

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

}
Working of Recursion

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>

int sum(int n);

int main() {

int number, result;

printf("Enter a positive integer: ");

scanf("%d", &number);

result = sum(number);

printf("sum = %d", result);

return 0;
}

int sum(int n) {

if (n != 0)

// sum() function calls itself

return n + sum(n-1);

else

return n;

Output

Enter a positive integer:3

sum = 6

Advantages and Disadvantages of Recursion

Recursion makes program elegant. However, if performance is vital, use loops instead as
recursion is usually much slower.

Advantages of recursion

1. The code may be easier to write.

2. To solve such problems which are naturally recursive such as tower of Hanoi.

3. Reduce unnecessary calling of function.

4. Extremely useful when applying the same solution.


5. Recursion reduce the length of code.

6. It is very useful in solving the data structure problem.

Disadvantages of recursion

1. Recursive functions are generally slower than non-recursive function.

2. It may require a lot of memory space to hold intermediate results on the system stacks.

3. Hard to analyze or understand the code.

4. It is not more efficient in terms of space and time complexity.

In the following example, recursion is used to calculate the factorial of a number.

#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

Enter the number whose factorial you want to calculate?5

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;

printf("Enter the value of 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;

return fib(n-1)+fib(n-2); // Recursive function

Output

Enter the value of n 12

The 12 term in the fibnoci series is: 144

Fibonacci Series using recursion in C

Let's see the fibonacci series program in c using recursion.


#include<stdio.h>
void printFibonacci(int n){
static int n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
printFibonacci(n-2);
return 0;
}

Output:

Enter the number of elements:15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Ackermann Function

In computability theory, the Ackermann function, named after Wilhelm Ackermann, is


one of the simplest and earliest-discovered examples of a total computable function that is
not primitive recursive.
All primitive recursive functions are total and computable, but the Ackermann function
illustrates that not all total computable functions are primitive recursive.

It’s a function with two arguments each of which can be assigned any non-negative integer.

Ackermann function is defined as:

Solve A(1, 2)?


Answer:
Given problem is A(1, 2)
Here m = 1, n = 2 e.g m > 0 and n > 0
Hence applying third condition of Ackermann function
A(1, 2) = A(0, A(1, 1)) ———- (1)
Now, Let’s find A(1, 1) by applying third condition of Ackermann function
A(1, 1) = A(0, A(1, 0)) ———- (2)
Now, Let’s find A(1, 0) by applying second condition of Ackermann function
A(1, 0) = A(0, 1) ———- (3)
Now, Let’s find A(0, 1) by applying first condition of Ackermann function
A(0, 1) = 1 + 1 = 2
Now put this value in equation 3
Hence A(1, 0) = 2
Now put this value in equation 2
A(1, 1) = A(0, 2) ———- (4)
Now, Let’s find A(0, 2) by applying first condition of Ackermann function
A(0, 2) = 2 + 1 = 3
Now put this value in equation 4
Hence A(1, 1) = 3
Now put this value in equation 1
A(1, 2) = A(0, 3) ———- (5)
Now, Let’s find A(0, 3) by applying first condition of Ackermann function
A(0, 3) = 3 + 1 = 4
Now put this value in equation 5
Hence A(1, 2) = 4
So, A (1, 2) = 4

// C program to illustrate Ackermann function

#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.

C array is beneficial if you have to store similar elements.

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.

By using the array, we can access the elements easily.

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

To declare the array.

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

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration.

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

Let's see the C program to declare and initialize the array in C.

#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

C Array Example: Sorting an array

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

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.

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.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Consider the following example.

int twodimen[4][3];

Here, 4 is the number of rows, and 3 is the number of columns.

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

2D array example: Storing elements in a matrix and printing it.

#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

printing the elements ....

56 10 30

34 21 34

45 56 78

Difference Between One-Dimensional and Two-Dimensional Array

Parameters One-Dimensional Array Two-Dimensional Array

Basics A one-dimensional array stores a A two-dimensional array stores an array of


single list of various elements various arrays, or a list of various lists, or
having a similar data type. an array of various one-dimensional arrays.

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.

Dimensions It has only one dimension. It has a total of two dimensions.

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:

 2D Arrays are used to implement matrices.


 Arrays can be used to implement various data structures like
a heap, stack, queue, etc.
 They allow random access.
 They are cache-friendly.

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

Algorithm to perform matrix addition, matrix subtraction, matrix multiplication

Matrix addition:

1. Input the order of the matrix.


2. Input the matrix 1 elements.
3. Input the matrix 2 elements.
4. Repeat from i = 0 to m
5. Repeat from j = 0 to n
6. mat3[i][j] = mat1[i][j] + mat2[i][j]
7. Print mat3.

Matrix subtraction:

1. Input the order of the matrix.


2. Input the matrix 1 elements.
3. Input the matrix 2 elements.
4. Repeat from i = 0 to m
5. Repeat from j = 0 to n
6. mat3[i][j] = mat1[i][j] - mat2[i][j]
7. Print mat3.

Matrix multiplication:

1. Input the order of the matrix1 ( m * n).


2. Input the order of matrix2 (p * q).
3. Input the matrix 1 elements.
4. Input the matrix 2 elements.
5. Repeat from i = 0 to m
6. Repeat from j = 0 to q
7. repeat from k = 0 to p
8. sum=sum+ mat1[c][k] * mat2[k][d];
9. mat3[c][d]=sum
10. Print mat3.
Program to add two matrices

#include <stdio.h>

int main() {

int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter the number of rows (between 1 and 100): ");

scanf("%d", &r);

printf("Enter the number of columns (between 1 and 100): ");

scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("Enter elements of 2nd matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element b%d%d: ", i + 1, j + 1);


scanf("%d", &b[i][j]);

// adding two matrices

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

sum[i][j] = a[i][j] + b[i][j];

// printing the result

printf("\nSum of two matrices: \n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("%d ", sum[i][j]);

if (j == c - 1) {

printf("\n\n");

}
return 0;
}

Output:
Enter the number of rows (between 1 and 100): 2

Enter the number of columns (between 1 and 100): 3

Enter elements of 1st matrix:

Enter element a11: 2

Enter element a12: 3

Enter element a13: 4

Enter element a21: 5

Enter element a22: 2

Enter element a23: 3

Enter elements of 2nd matrix:

Enter element b11: -4

Enter element b12: 5

Enter element b13: 3

Enter element b21: 5

Enter element b22: 6

Enter element b23: 3

Sum of two matrices:

-2 8 7

10 8 6
Program to substract two matrices
#include <stdio.h>

int main() {

int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter the number of rows (between 1 and 100): ");

scanf("%d", &r);

printf("Enter the number of columns (between 1 and 100): ");

scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("Enter elements of 2nd matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("Enter element b%d%d: ", i + 1, j + 1);

scanf("%d", &b[i][j]);

// adding two matrices

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

sum[i][j] = a[i][j] - b[i][j];


}

// printing the result

printf("\nSubstraction of two matrices: \n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j) {

printf("%d ", sum[i][j]);

if (j == c - 1) {

printf("\n\n");

return 0;

Output:

Enter the number of rows (between 1 and 100): 2

Enter the number of columns (between 1 and 100): 2

Enter elements of 1st matrix:

Enter element a11: 23

Enter element a12: 45

Enter element a21: 67

Enter element a22: 38

Enter elements of 2nd matrix:

Enter element b11: 12

Enter element b12: 23

Enter element b21: 22

Enter element b22: 18

Substraction of two matrices:


11 22

45 20

Program on multiply two matrices

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

printf("enter the number of row=");

scanf("%d",&r);

printf("enter the number of column=");

scanf("%d",&c);

printf("enter the first matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

printf("enter the second matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

{
scanf("%d",&b[i][j]);

printf("multiply of the matrix=\n");

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 printing result

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("%d\t",mul[i][j]);

printf("\n");

return 0;

}
Output:

enter the number of row=3


enter the number of column=3
enter the first matrix element=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18

C program to transpose of a matrix


#include <stdio.h>

int main() {

int a[10][10], transpose[10][10], r, c;

printf("Enter rows and columns: ");

scanf("%d %d", &r, &c);

printf("\nEnter matrix elements:\n");

for (int i = 0; i < r; ++i)

for (int j = 0; j < c; ++j) {

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("\nEntered matrix: \n");

for (int i = 0; i < r; ++i)

for (int j = 0; j < c; ++j) {

printf("%d ", a[i][j]);

if (j == c - 1)
printf("\n");

// computing the transpose

for (int i = 0; i < r; ++i)

for (int j = 0; j < c; ++j) {

transpose[j][i] = a[i][j];

// printing the transpose

printf("\nTranspose of the matrix:\n");

for (int i = 0; i < c; ++i)

for (int j = 0; j < r; ++j) {

printf("%d ", transpose[i][j]);

if (j == r - 1)

printf("\n");

return 0;

Output:

Enter rows and columns: 2

Enter matrix elements:

Enter element a11: 1

Enter element a12: 4

Enter element a13: 0


Enter element a21: -5

Enter element a22: 2

Enter element a23: 7

Entered matrix:

1 4 0

-5 2 7

Transpose of the matrix:

1 -5

4 2

0 7

String and Character Array


String is a sequence of characters that are treated as a single data item and
terminated by a null character '\0'. C language does not support strings as a
data type.

A string is actually a one-dimensional array of characters in C language.


These are often used to create meaningful and readable programs.

Importance of Char Array

 Character Array is used to display the sequence of characters or numbers.


 Using char array we can store the variable in a memory to corresponding memory address.
 Various application such as Word processors, text editors, dictionaries all use strings or
character arrays.
 Char array is also used in Pattern Matching like DNA matching and genome matching.
 Char array is also used in Language processing software such as Text-to-speech software.
 Modern databases like mongoDB and JSON also used Char Array for data manipulation.

Use of Char Array in C

Char array in C programming is used to store and manipulate the strings.

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”.

4 Ways to Initialize a String in C

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

4. Assigning character by character without size: We can assign character by


character without size with the NULL character at the end. The size of the string is
determined by the compiler automatically.
char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'

Declaring and Initializing a string variables:

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

// Illegal

char ch[3] = "hello";

char str[4];

str = "hello";

String Input and Output:

 %s format specifier to read a string input from the terminal.


 But scanf() function, terminates its input on the first white space it encounters.
 edit set conversion code %[..] that can be used to read a line containing a variety of
characters, including white spaces.
 The gets() function can also be used to read character string with white spaces

char str[20];

printf("Enter a string");

scanf("%[^\n]", &str);

printf("%s", str);
char text[20];

gets(text);

printf("%s", text);

String Handling Functions:

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() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string


The following are the most commonly used string handling functions.

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

strcpy(src, "This is source");


strcpy(dest, "This is destination");

strcat(dest, src);

printf("Final destination string : |%s|", dest);

return(0);
}

Output:
Final destination string : |This is destinationThis is source|

strlen() and strcmp() function:

strlen() will return the length of the string passed to it and

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

int i=strcmp("study ", "tonight");

printf("%d %d",j,i);

return 0;

Output:

12 -1

strcpy() function:

It copies the second string argument to the first string argument .


Example of 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:

It is used to reverse the given string expression.


Code snippet for strrev():

#include <stdio.h>

int main()

char s1[50];

printf("Enter your string: ");

gets(s1);

printf("\nYour reverse string is: %s",strrev(s1));

return(0);

Output:

Enter your string: studytonight

Your reverse string is: thginotyduts

// C program to illustrate strings

#include <stdio.h>

#include <string.h>

int main()

// declare and initialize string

char str[] = "Bce";


// print string

printf("%s\n", str);

int length = 0;

length = strlen(str);

// displaying the length of string

printf("Length of string str is %d", length);

return 0;

Output
Bce
Length of string str is 3

How to Read a Line of Text in C?

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

// MAX Size if 50 defined

fgets(str, MAX, stdin);


printf("String is: \n");

// Displaying Strings using Puts

puts(str);

return 0;

Input:
Bce

Output:
String is:
Bce

Passing Array to Function in C

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.

Consider the following syntax to pass an array to the function.

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:

return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

return_type function(type *arrayname)

You can also use the concept of a pointer.

C language passing an array to function example

#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

Example 2: Pass Arrays to Functions

// Program to calculate the sum of array elements by passing to a function

#include <stdio.h>

float calculateSum(float num[ ]);

int main() {

float result, num[ ] = {23.4, 55, 22.6, 3, 40.5, 18};


// num array is passed to calculateSum()

result = calculateSum(num);

printf("Result = %.2f", result);

return 0;

float calculateSum(float num[ ]) {

float sum = 0.0;

for (int i = 0; i < 6; ++i) {

sum += num[i];

return sum;

Output

Result = 162.50

Pass Multidimensional Arrays to a Function

To pass multidimensional arrays to a function, only the name of the array is passed to the
function (similar to one-dimensional arrays).

Example 3: Pass two-dimensional arrays

#include <stdio.h>
void displayNumbers(int num[2][2]);

int main() {

int num[2][2];

printf("Enter 4 numbers:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

scanf("%d", &num[i][j]);

// pass multi-dimensional array to a function

displayNumbers(num);

return 0;

void displayNumbers(int num[2][2]) {

printf("Displaying:\n");

for (int i = 0; i < 2; ++i) {

for (int j = 0; j < 2; ++j) {

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.

How to create a structure?

‘struct’ keyword is used to create a structure. Following is an example.


struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

How to declare structure variables?

A structure variable can either be declared with structure declaration or as a separate


declaration like basic types.

struct Point

int x, y;

} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types

struct Point

int x, y;

};
int main()

struct Point p1; // The variable p1 is declared like a normal variable

How to initialize structure members?

Structure members cannot be initialized with declaration. For example the following C
program fails in compilation.

struct Point

int x = 0; // COMPILER ERROR: cannot initialize members here

int y = 0; // COMPILER ERROR: cannot initialize members here

};

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

// A valid initialization. member x gets value 0 and y

// gets value 1. The order of declaration is followed.

struct Point p1 = {0, 1};

How to access structure elements?

Structure members are accessed using dot (.) operator.

#include<stdio.h>

struct Point
{

int x, y;

};

int main()

struct Point p1 = {0, 1};

// Accessing members of point p1

p1.x = 20;

printf ("x = %d, y = %d", p1.x, p1.y);

return 0;

Output:

x = 20, y = 1

What is designated Initialization?

Designated Initialization allows structure members to be initialized in any order.


#include<stdio.h>

struct Point

int x, y, z;

};

int main()

// Examples of initialization using designated initialization

struct Point p1 = {.y = 0, .z = 1, .x = 2};

struct Point p2 = {.x = 20};

printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);

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

return 0;

Output:

x = 2, y = 0, z = 1

x = 20
What is an array of structures?

Like other primitive data types, we can create an array of structures.

#include<stdio.h>

struct Point

int x, y;

};

int main()

// Create an array of structures

struct Point arr[10];

// Access array members

arr[0].x = 10;

arr[0].y = 20;

printf("%d %d", arr[0].x, arr[0].y);


return 0;

Output:

10 20

What is a structure pointer?

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

struct Point p1 = {1, 2};

// p2 is a pointer to structure p1

struct Point *p2 = &p1;


// Accessing structure members using structure pointer

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

return 0;

Output:

12

Limitations of C Structures

C structures have some limitations.

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

struct number n1,n2,n3;

n1.x=4;

n2.x=3;

n3=n1+n2;

return 0;

/*

Output:

prog.c: In function 'main':

prog.c:10:7: error:

invalid operands to binary + (have 'struct number' and 'struct number')

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.

 Functions inside Structure: C structures do not permit functions inside Structure

 Static Members: C Structures cannot have static members inside their body

 Access Modifiers: C Programming language do not support access modifiers. So they


cannot be used in C Structures.

 Construction creation in Structure: Structures in C cannot have constructor inside


Structures.

Structure vs Union

Structures in C is a user-defined data type available in C that allows to combining of data


items of different kinds. Structures are used to represent a record.

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)

struct [structure name]

member definition;

member definition;

...

member definition;

}structure variable declaration;

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:

union [union name]

member definition;

member definition;

...
member definition;

};

(OR)

union [union name]

member definition;

member definition;

...

member definition;

}union variable declaration;

Similarities between Structure and Union

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

// between structure and Union

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

// creating variable for structure

// and initializing values difference

struct struct_example s={18,38,"bce"};

// creating variable for union

// and initializing values

union union_example u={18,38,"bce"};


printf("structure data:\n integer: %d\n"

"decimal: %.2f\n name: %s\n",

s.integer, s.decimal, s.name);

printf("\nunion data:\n integer: %d\n"

"decimal: %.2f\n name: %s\n",

u.integer, u.decimal, u.name);

// difference two and three

printf("\nsizeof structure : %d\n", sizeof(s));

printf("sizeof union : %d\n", sizeof(u));

// difference five

printf("\n Accessing all members at a time:");

s.integer = 183;

s.decimal = 90;

strcpy(s.name, "bce");

printf("structure data:\n integer: %d\n "


"decimal: %.2f\n name: %s\n",

s.integer, s.decimal, s.name);

u.integer = 183;

u.decimal = 90;

strcpy(u.name, "bce");

printf("\nunion data:\n integer: %d\n "

"decimal: %.2f\n name: %s\n",

u.integer, u.decimal, u.name);

printf("\n Accessing one member at time:");

printf("\nstructure data:");

s.integer = 240;

printf("\ninteger: %d", s.integer);


s.decimal = 120;

printf("\ndecimal: %f", s.decimal);

strcpy(s.name, "C programming");

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

printf("\n union data:");

u.integer = 240;

printf("\ninteger: %d", u.integer);

u.decimal = 120;

printf("\ndecimal: %f", u.decimal);

strcpy(u.name, "C programming");

printf("\nname: %s\n", u.name);

//difference four
printf("\nAltering a member value:\n");

s.integer = 1218;

printf("structure data:\n integer: %d\n "

" decimal: %.2f\n name: %s\n",

s.integer, s.decimal, s.name);

u.integer = 1218;

printf("union data:\n integer: %d\n"

" decimal: %.2f\n name: %s\n",

u.integer, u.decimal, u.name);

Output:
structure data:

integer: 18

decimal: 38.00

name: bce

union data:

integer: 18

decimal: 0.00
name: ?

sizeof structure: 28

sizeof union: 20

Accessing all members at a time: structure data:

integer: 183

decimal: 90.00

name: bce

union data:

integer: 1801807207

decimal: 277322871721159510000000000.00

name: bce

Accessing one member at a time:

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.

You might also like