0% found this document useful (0 votes)
4 views130 pages

Unit 4

The document outlines the syllabus for an Introduction to C Programming course, focusing on user-defined functions, arrays, recursion, and data structures. It details the course objectives, outcomes, and the importance of functions in C programming, including their declaration, definition, and calling methods. Additionally, it discusses parameter passing techniques, function categories, and provides examples of creating and using functions in C.

Uploaded by

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

Unit 4

The document outlines the syllabus for an Introduction to C Programming course, focusing on user-defined functions, arrays, recursion, and data structures. It details the course objectives, outcomes, and the importance of functions in C programming, including their declaration, definition, and calling methods. Additionally, it discusses parameter passing techniques, function categories, and provides examples of creating and using functions in C.

Uploaded by

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

Course Name: Introduction to C Programming

Course Code: COM-201

Faculty: Dr. Mehak Mengi


Assistant Professor
Dept. of CSE, MIET

Model Institute of Engineering & Technology


Unit 4 Syllabus

Unit-IV
User-Defined Functions, Arrays, Recursion, Handling of Character Strings,
Structures, Unions, User Defined and Standard Functions, Formal and Actual
Arguments, Functions Category, Function Prototypes, Parameter Passing, Call-by-
value, Call-by-reference, Nested Functions, Recursion, One Dimensional Array,
Multidimensional Array declaration and their applications, Passing Array to a
Function, String Manipulation, Declaration of Structures, Declaration of Unions,
Pointer to Structure &Unions.
Course Outcome 1-Delivery Plan

Course Outcomes Topics Blooms Taxonomy

Decompose a problem into functions Understanding,


and synthesize a complete program Applying
using divide and conquer approach.

CO3
Debug and test programs to evaluate Understanding,
program correctness Applying
Objectives

 To introduce the concept of user-defined functions using parameter passing, recursion, and

nested function concepts.

 To apply array and string manipulation techniques, including declaration, usage, and passing to

functions.

 To demonstrate the use of structures and unions, including pointer access and differentiation for

complex data handling.


Functions in C

 A function is a block of code that performs a particular task.


 There are many situations where we might need to write same line of code for
more than once in a program.
 This may lead to unnecessary repetition of code, bugs and even becomes boring
for the programmer.
 So, C language provides an approach in which you can declare and define a
group of statements once in the form of a function and it can be called and used
whenever required.
 These functions defined by the user are also know as User-defined Functions.
 Function in C programming is a reusable block of code that makes a program
easier to understand, test and can be easily modified without changing the calling
program.
Cont…..

 When you divide a large program into various functions, it becomes easy to
manage each function individually.
 Whenever an error occurs in the program, you can easily investigate faulty
functions and correct only those errors.
 You can easily call and use functions whenever they are required which
automatically leads in saving time and space.
Why we Need Functions in C

a) To improve the readability of code. It makes the program more readable and
easy to understand.
b) Improves the reusability of the code, same function can be used in any program
rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy
to be traced.
d) In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
e) Reduces the size of the code, duplicate set of statements are replaced by
function calls.
User-defined Functions in C

 User Defined Functions are those functions which are defined and declared by the
programmer to do some specific task.
 These are designed to re-use the code.
 The functions that we create in a program are known as user defined functions.
 Benefits of designing a User-Defined Functions:
 Using functions, you can divide your large program into small pieces according to
different task which will provide you easy access to read and debug.
 Using functions, you can re-use your code. You do not need to rewrite the code,
just call the function and use it.
Parts of Functions in C

 In 'C' programming functions are divided into three activities such as:-

1) Function declaration

2) Function definition

3) Function call
 A function declaration is also called "Function prototype.
Parts of Functions in C

return-type :- It is the data type of function’s


Declaration of User-Defined Function:- return value. If function does not return
return-type functionName(type-of- value, function’s return type must be void.
local argument-list); void is a data type which represent nothing
i.e. function will not return any value.
Defining an User-Defined Function:- function name:- It is the name of those set of
return-type functionName(type-of- statements which are written in function’s
local-argument-list); body. functionName can be any valid
{ identifier’s name, do not use any reserve
Function-body/ set-of-statements; word as a function name.
} type-of-local-argument-list:- List of the data
type of those arguments (parameters) which
are used in the function definition.
Calling an User-Defined Functions:-
actual-argument-list:- List of those
functionName(actual-argument- parameters/ arguments, which are being
Function Declaration

 It is a compulsory part for using functions in code.


 In a function declaration, we just specify the name of a function that we are going to
use in our program like a variable declaration.
 We cannot use a function unless it is declared in a program.
 A function declaration is also called "Function prototype."
 For Example:- #include <stdio.h>
/*Function declaration*/
int add(int a,b);
// Here add is the name of the function
// int is the return type
// a ,b are local arguments or formal parameters
// int is type-of-local-argument-list
/*End of Function declaration*/
Function Definition

 Function definition means just writing the body of a function.


 A body of a function consists of statements which are going to perform a
specific task.
 A function body consists of a single or a block of statements.

For Example:- // Function Definition
int add(int a, int b)
//function body
{
int c;
c=a+b;
return c;
}
Function Call

 A function call means calling a function whenever it is required in a program.


 Whenever we call a function, it performs an operation for which it was designed.

For Example:- int main()// Function Call
result = add(4,5); these are the actual
arguments
Creating a void user defined function that doesn’t return anything
No Arguments passed in function

#include <stdio.h>

// Function declaration
int add(); // No parameters

// Function definition
int add() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b); // Take input from user
return a + b;
}

int main() {
int result;
result = add(); // No arguments passed
printf("Result: %d\n", result);
return 0;
}
Arguments passed in function

#include <stdio.h>

int add(int a, int b);

int add(int a, int b) {


int c;
c = a + b;
return c;
}

int main() {
int result;
result = add(4, 5); // Two integer
arguments
printf("Result: %d\n", result);
return 0;
}
Creating a User Defined Function Addition()
Creating a User Defined Function Square()
A User Defined Function to Multiply two Numbers
Passing Arguments to a Function

 Arguments are the values specified during the function call, for which the
formal parameters are declared while defining the function.
Cont…….

 While declaring the function, we


have declared two
parameters a and b of type int.
 Therefore, while calling that function,
we need to pass two arguments, else
we will get compilation error.
 And the two arguments passed should
be received in the function definition,
which means that the function header
in the function definition should have
the two parameters to hold the
argument values.
 These received arguments are also
known as formal parameters.
 The name of the variables while
declaring, calling and defining a
function can be different.
Returning a Value from Function

 A function may or may not


return a result. But if it does, we
must use the return statement
to output the result.
 return statement also ends the
function execution, hence it
must be the last statement of
any function.
 If you write any statement after
the return statement, it won't be
executed.
 The data type of the value
returned using
the return statement should be
same as the return type
mentioned at function
declaration and definition.
 If any of it mismatches, you will
get compilation error.
Poll/Quiz

 Google Form link for quiz on User defined Functions -


Practice Questions

Q1. Write an appropriate function call for each of the following functions.

a) float formula(float x) b) void display(int a, int b)


{ {
float y; int c;
y= 3*x-1; c= sqrt(a*a+b*b);
return (y); printf(“c= %i \n”, c);
} }
Summarize the Lecture

 In Today’s Lecture we discussed about :-


 Functions in C.
 Need of functions in C.
 User-defined functions in C.
 Benefits of designing a user-defined functions.
 Parts of functions in C.
 Function Declaration.
 Function Definition.
 Function Call.
 Examples based on how to create user-defined functions in C.
 Passing arguments to a function.
 Returning a value from function.
Questions- Related to Topic

Q1. What is function? Describe different styles of writing function


prototypes.

Q2. Explain about user-defined functions with syntax.


Function Arguments in C Programming

 C programming function arguments also


known as parameters are the variables that
will receive the data sent by the calling
program.
 These arguments serve as input data to the
function to carry out the specified task.
 Basically, there are two types of arguments:
 Actual arguments
 Formal arguments
 The variables declared in the function
prototype or definition are known as Formal
arguments and the values that are passed to
the called function from the main function are
known as Actual arguments.
 The actual arguments and formal arguments
must match in number, type, and order.
Formal and Actual Parameters
Formal and Actual Parameters
Parameter Passing Techniques in C

 There are different ways in which parameter data can be passed into and out of
methods and functions.
 Let us assume that a function B() is called from another function A().
 In this case A is called the “caller function” and B is called the “called function
or callee function”.
 Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
 Terminology:-
 Formal Parameter : A variable and its type as they appear in the prototype of
the function or method.
 Actual Parameter : The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling environment.
 Modes:
 IN: Passes info from caller to callee.
 OUT: Callee writes values in caller.
Methods of Parameter Passing

 Pass By Value: This method uses in-mode semantics. Changes made to formal parameter
do not get transmitted back to the caller. Any modifications to the formal parameter
variable inside the called function or method affect only the separate storage location and
will not be reflected in the actual parameter in the calling environment. This method is
also called as call by value.
C Program to Illustrate Call By Value

OUTPUT
Methods of Parameter Passing

 Pass by Reference: This technique uses in/out-mode semantics. Changes made to formal
parameter do get transmitted back to the caller through parameter passing. Any changes
to the formal parameter are reflected in the actual parameter in the calling environment
as formal parameter receives a reference to the actual data. This method is also called as
call by reference. This method is efficient in both time and space.
C Program to Illustrate Call By Reference

OUTPUT
Functions Category

 Type of functions available in C Language:-


Function with no argument and no return value
Function with no argument and with return value

Function with argument and no return value

Function with argument and return value

 Examples:-
 void add() //No return without argument
 void sub(int,int)//No return with argument

 int mul() //Return without argument

 float div(int ,int) //Return with argument


Add two numbers using function (No return without argument)

OUTPUT
Calculating the difference between two numbers using function
(No return with argument)

OUTPUT
Multiplication of two numbers using function
(Return without argument)

OUTPUT
Multiplication of two numbers using function
(Return with arguments)

OUTPUT
Create a simple calculator using functions
#include <stdio.h>
void add(int a, int b)
{ printf("Result: %d\n", a + b);
}
void subtract(int a, int b)
{ printf("Result: %d\n", a - b);
}
void multiply(int a, int b)
{ printf("Result: %d\n", a * b);
}
void divide(int a, int b) { if (b != 0)
printf("Result: %.2f\n", (float)a / b); else
printf("Division by zero error!\n");
}
int main() {
int choice, num1, num2;
printf("Enter two numbers: "); scanf("%d %d", &num1, &num2);
printf("Choose an operation:\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n"); scanf("%d", &choice);
switch (choice) { case 1:
add(num1, num2); break;
case 2:
subtract(num1, num2); break;
case 3:
multiply(num1, num2); break;
case 4:
Nested Functions

 When one or more functions are utilized under a particular function, it is known as nesting function in C
programming language. Nested functions are used when one function is a logic of another function.
 We can declare nested functions as follows:-
Program to Demonstrate Nested Functions
Program to Demonstrate Nested Functions(Need of Nested
Functions) Add two numbers and multiply the result

 #include <stdio.h>
 // Function to add two numbers
 int add(int a, int b) {
 return a + b;
 }
 // Function to call add() and then multiply the result
 void calculate(int x, int y, int z) {
 int sum = add(x, y); // Calling add() inside calculate()
 int result = sum * z;

 printf("Sum: %d\n", sum);


 printf("Final Result (sum * %d): %d\n", z, result);
 }

 int main() {
 calculate(2, 3, 4); // (2 + 3) * 4 = 20
 return 0;
 }
Program to Demonstrate Nested Functions(Need of Nested
Functions) Adding the final bill in resturant

 #include <stdio.h>
 // Function to calculate and return tax
 float calculate_tax(float subtotal) {
 return subtotal * 0.18; // 18% GST
 }

 // Function to calculate final bill — calls tax calculation


 void generate_bill(float subtotal) {
 float tax = calculate_tax(subtotal);
 float total = subtotal + tax;

 printf("Subtotal: %.2f\n", subtotal);


 printf("GST (18%%): %.2f\n", tax);
 printf("Total Bill: %.2f\n", total);
 }
 int main() {
 float subtotal;
 generate_bill(500.00); // Only one call from main
 return 0;
 }
Poll/Quiz

 Google Form link for quiz on More About Functions -


Practice Questions

Q1. What is the output of the C program?


void show();
void main()
{
printf(“PISTA”);
show();
}
void show()
{
printf(“CASHEW”);
}
Summarize the Lecture

 In Today’s Lecture we discussed about :-


 Functions arguments in C.
 Formal and actual parameters.
 Parameter passing techniques in C.
 Methods of parameter passing.
 Pass by value.
 Pass by reference.
 Examples of C program to illustrate call by value and call by reference.
 Category of functions with C program examples.
 Nested functions with C program example.
Questions- Related to Topic

Q1. Define calling a function. What is ‘Call by Value’ parameter passing in C


program? How is it differing from ‘Call by reference’? Write a program
segment to show these two types of parameter passing.

Q2. What are function prototypes? What is their purpose? Summarize the rule
associated with them different categories of function? Explain any two with
example.

Q3. Distinguish between call by value and call by reference with the help of
program.
Recursion

• Recursion is a way of solving a problem by calling a function repeatedly


until a base condition is met.
• To use recursion to solve a programming problem, we break the problem
down into smaller subproblems and use the solutions to these subproblems
to solve the original problem.
• These subproblems can then be broken down into even smaller
subproblems until we reach the base condition, at which point the recursion
stops and the final solution is returned
Recursion (Contd…)

Recursive algorithms have two main components:


1. Base case: This is the smallest version of the problem that can be

immediately solved and returned as the result. It acts as a terminating


condition for the recursive function.
2. Recursive structure: This is the idea of defining the solution to a problem

using the solutions of smaller subproblems. It involves breaking the


problem down into smaller and smaller pieces until the base case is
reached, at which point the final solution is returned.
Basic Structure of Recursive Function

return_type function_name(parameters) {

if (base_condition) {

return some_value;

} else {

// recursive call

return function_name(modified_parameters);

}
Factorial of a number using Recursive Function

#include <stdio.h>
int factorial(int n) {
if (n == 0) // Base condition
return 1;
else
return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Fibonacci series of a number using Recursive Function

#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 6;
printf("Fibonacci number at position %d is %d", n, fibonacci(n));
return 0;
}
Fibonacci series of a number using Recursive Function

#include <stdio.h>
int fibonacci(int n) {
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int main() {
int n = 6;
printf("Fibonacci number at position %d is %d", n, fibonacci(n));
return 0;
}
Sum of first natural numbers using Recursive Function

#include <stdio.h>
int sum(int n) {
if (n == 0)
return 0; // Base case
else
return n + sum(n - 1); // Recursive call
}
int main() {
int n = 5;
printf("Sum of first %d numbers is %d", n, sum(n));
return 0;
}
When to use Functions and when use Recursion?

When to use each:


•Use functions(Iterative Solutions) when you need to
perform a specific task multiple times, or when your task does
not involve solving sub-problems that can be broken down
recursively.

•Use recursion when the problem is naturally recursive, such


as problems that involve dividing a task into similar smaller
tasks, or when you’re working with structures like trees,
graphs, or mathematical sequences that fit a recursive pattern.
Arrays

 An array in C is a collection of items stored at contiguous memory locations

and elements can be accessed randomly using indices of an array.


 They are used to store similar type of elements as in the data type must be the

same for all elements.


 They can be used to store collection of primitive data types such as int, float,

double, char, etc of any particular type.


 An array is a variable that can store multiple values. For example, if you want

to store 100 integers, you can create an array for it.

int data[100];
One Dimensional Arrays

A one-dimensional array is a structured collection of array elements that can be


accessed individually by specifying the position of a component with a single index
value.

Representation of one dimensional array


Why Do We Need Arrays?

 We can use normal variables (v1, v2, v3, ..) when we have a small number of
objects.
 But if we want to store a large number of instances, it becomes difficult to
manage them with normal variables.
 The idea of an array is to represent many instances in one variable.
How to Declare an Array?

 Syntax to declare an array:


datatype array-name[array-size];
Data type: It denotes the type of the elements in the array.
Array_name: Name of the array. It must be a valid identifier.
Array_size: Number of elements an array can hold.

For example:-
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5.
Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed
once it is declared.
Some Examples of Array Declarations

 Here are some example of array declarations:

int num[100];

float temp[20];

char ch[50];
 num is an array of type int, which can only store 100 elements of type int.
 temp is an array of type float, which can only store 20 elements of type float.
 ch is an array of type char, which can only store 50 elements of type char.
Access Array Elements

You can access elements of an array by indices.


Suppose you declared an array mark as :-
float mark[5];
The first element is mark[0], the second element is mark[1] and so on.

Few keynotes:
•Arrays have 0 as the first index, not 1.
•In this example, mark[0] is the first element.
•If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
•Suppose the starting address of mark[0] is 2120d.
•Then, the address of the mark[1] will be 2124d.
•Similarly, the address of mark[2] will be 2128d and so on.
This is because the size of a float is 4 bytes.
How to Initialize an Array?

It is possible to initialize an array during declaration. For example,


int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this.
int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as
we are initializing it with 5 elements.

Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Change Value of Array Elements

Change Value of Array elements


 int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1

mark[2] = -1;

// make the value of the fifth element to 0

mark[4] = 0;
Input Array Elements

 Input Array Elements

Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element

s​canf("%d", &mark[2]);

// take input and store it in the ith element

scanf("%d", &mark[i-1]);
Output Array Elements

 Output Array Elements


 Here's how you can print an individual element of an array.
 // print the first element of the array

printf("%d", mark[0]);

// print the third element of the array

printf("%d", mark[2]);

// print ith element of the array

printf("%d", mark[i-1]);
Access Elements Out of its Bound!

Access elements out of its bound!


Suppose you declared an array of 10 elements. Let's say,
int testArray[10];
You can access the array elements from
testArray[0] to testArray[9].
Now let's say if you try to access testArray[12]. The element is not available.
This may cause unexpected output. Sometimes you might get an error and some
other time your program may run correctly.
Hence, you should never access elements of an array outside of its bound.
Program to Take Input And Print Elements of 1-d Array

OUTPUT
Program to Print the Sum of Elements of an Array

OUTPUT
Passing 1-D array elements to a function
We can pass elements of 1-D array just like any normal variables.

OUTPUT
Practice Questions

Q1. Write an appropriate array definition for each of the following problem
situations.
a) Define a one-dimensional, 12- element integer array called c. Assign the
values 1,4,7,10,…………,34 to the array elements.
b) Define a one-dimensional character array called point. Assign the string
“NORTH” to the array elements. End of the string with the null
character.
c) Define a one-dimensional, four element character array called letters.
Assign the characters ‘N’, ‘S’, ‘E’ and ‘W’ to the array elements.
d) Define a one-dimensional, six-element floating-point array called consts.
Assign the following values to the array elements:
0.005 -0.0321e-6 0.167 -0.3e8 0.015
Summarize the Lecture

 In Today’s Lecture we discussed about :-


 Representation of one-dimensional arrays.
 Why do we need arrays?
 How to declare, initialize and access array elements?
 Some examples of array declarations.
 Change the value of array elements.
 Input and output array elements.
 Access elements out of its bound!
 C programs based on one-dimensional array.
 Passing 1-d array elements to a function with C programs.
Questions- Related to Topic

Q1. What do you mean by formal and actual argument. Also show how arrays
are passed to functions. Explain with an example.

Q2. Write a program that accepts two one-dimensional arrays and find the
sum of corresponding elements and the sum is stored in the third array.
Finally it prints the resultant array.
Multidimensional Arrays in C

 In C, we can define multidimensional arrays in simple words as array of arrays.


Data in multidimensional arrays are stored in tabular form (in row major order).
 General form of declaring N-dimensional arrays:

 Examples:
Size of Multidimensional Arrays in C

 Total number of elements that can be stored in a multidimensional array can be


calculated by multiplying the size of all the dimensions.
 For example:
 The array int x[10][20] can store total (10*20) = 200 elements.
 Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
Two-dimensional Arrays in C

 Two –dimensional array is the simplest form of a multidimensional array. We


can see a two – dimensional array as an array of one – dimensional array for
easier understanding.
 The basic form of declaring a two-dimensional array of size x, y:
 Syntax:

 We can declare a two dimensional integer array say ‘x’ of size 10,20 as:

 Elements in two-dimensional arrays are commonly referred by x[i][j] where i is


the row number and ‘j’ is the column number.
Two-dimensional Array in C

 A Two-dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns
where the row number ranges from 0 to (x-1) and column number ranges from 0
to (y-1).
 A two-dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Initializing Two-dimensional Arrays in C

 There are two ways in which a Two-Dimensional array can be initialized.


 First Method:-

 The above array have 3 rows and 4 columns. The elements in the braces from
left to right are stored in the table also from left to right.
 The elements will be filled in the array in the order, first 4 elements from the left
in first row, next 4 elements in second row and so on.
 Better Method:-

 This type of initialization make use of nested braces.


 Each set of inner braces represents one row. In the above example there are total
three rows so there are three sets of inner braces.
Accessing Elements of Two-dimensional Arrays

 Elements in Two-Dimensional arrays are accessed using the row indexes and
column indexes.
 In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row
index 2 row number is 2+1 = 3.
Program to Print the Elements of a Two-dimensional Array

OUTPUT
Three-dimensional Arrays in C

 You can even create an array of 3 or more dimensions, but generally, you will never
need to do so. Therefore, we will restrict ourself to 3-D arrays only.
 Declare an array of 3 dimensions:-

 3-D array uses three indexes or subscript. This array can store 2*3*2=12 elements.
Initializing Three-dimensional Arrays in C

 Initialization in Three-Dimensional array is same as that of Two-


dimensional arrays.
 The difference is as the number of dimension increases so the
number of nested braces will also increase.
 First Method:-

 Better Method:-
Accessing Elements of Three-dimensional Arrays

 Accessing elements in Three-Dimensional Arrays is also similar to that of Two-


Dimensional Arrays.
 The difference is we have to use three loops instead of two loops for one
additional dimension in Three-dimensional Arrays.
 To output all the elements of a Two-Dimensional array we can use nested for
loops. We will require two for loops. One to traverse the rows and another to
traverse columns.
Accessing Elements of Three-dimensional Arrays

Block 0: Block 1:
[0][0][0] [1][0][0]
[0][0][1] [1][0][1]
[0][0][2] [1][0][2]
Program to Print The Elements of a Three-dimensional Array
Output of program to print the elements of a 3-dimensional array
Applications of Arrays in C

 In C programming language, arrays are used in wide range of applications:-


1. Arrays are used to Store List of values:-
 In c programming language, single dimensional arrays are used to store list of
values of same data type.
 In single dimensional arrays are used to store a row of values.
 In single dimensional array data is stored in linear form.
2. Arrays are used to Perform Matrix Operations:-
 We use two dimensional arrays to create matrix.
 We can perform various operations on matrices using two dimensional arrays.
3. Arrays are used to implement Search Algorithms:-
 We use single dimensional arrays to implement search algorithms such as:-
 Linear Search
 Binary Search
Cont…

4. Arrays are used to implement Sorting Algorithms :-


 We use single dimensional arrays to implement sorting algorithms such as :-
 Insertion Sort
 Bubble Sort
 Selection Sort
 Quick Sort
 Merge Sort, etc.
5. Arrays are used to implement Data structures :-
 We use single dimensional arrays to implement data structures such as:-
 Stack Using Arrays
 Queue Using Arrays
Passing 2-D Array Elements to a Function

OUTPUT
Poll/Quiz

 Google Form link for quiz on Two- Dimensional Arrays -


Introduction

• A string is an array of characters


• Any group of characters defined between double quotation marks is a constant
string.
– Example: “Man is obviously made to think.”
– Example: printf(“Well Done !”);
– Output: Well Done!
• To include a double quote in the string to be printed, use a back slash.
– Example: printf(“\“Well Done!\””);
– Output: “Well Done!”
Common String Operations

 Common operations performed on strings are:


– Reading and writing strings

– Combining strings together

– Copying one string to another

– Comparing strings for equality


Declaring String Variables

 A string variable is any valid C variable name and is always declared as an


array:

Syntax: char string_name[size];


 The size determines the number of characters in the string-name.

Example: char city[10];


 When the compiler assigns a character string to an character array, it
automatically supplies a null character (‘\0’) at the end of the string.
 The size should be equal to the maximum number of characters in the string plus
one.
Initializing String Variables

 Character arrays may be initialized when they are declared.


For Example:- char city[9] = “NEW YORK”;
 When we initialize a character by listing its elements, we must supply the null
terminator.
For Example :- char city[9] = {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
 We can initialize a character array without specifying the number of elements.
For Example:- char string[ ] = {'G','O','O','D','\0'};
 The size of the array will be determined automatically, based on the number of
elements initialized ie. Size of array= 5 elements
 We can also declare the size much larger than the string size.
For Example:- char str[10] = “GOOD”;
 Following will result in a compile time error.
char str[3] = “GOOD”;
Reading String From Terminal

 Reading words:-
 The input function scanf can be used with %s format specification to read in a
string of character.
For example:- char address[15];
scanf(“%s”, address);
 The problem with the scanf function is that it terminates its input on the first
white space it finds.
 A white space include blanks, tabs, new lines, etc.
For example:- INPUT: NEW YORK
 Only the string “NEW” will be read into the array address.
Reading String From Terminal

 If we want to read the entire line “NEW YORK”, then we may use two character
arrays of appropriate sizes.

For example:- scanf(“%s %s”, adr1, adr2);


 NEW YORK will assign the string “NEW” to adr 1 and “YORK” to adr2.
 In the case of character arrays, the ampersand (&) is not required before the
variable name.
 The scanf function automatically terminates the string with a null character.

For example:- char address[15];

scanf(“%s”, address);
Reading String From Terminal

 Reading a Line of Text:-


 In many text processing applications, we need to read in an entire line of text
from the terminal.
 It is not possible to use scanf function to read a line containing more than one
word.
 This is because the scanf terminates reading as soon as a space is encountered in
input.
 getchar function is used repeatedly to read successive single characters from the
input and place them into a character array.
 Thus an entire line of text can be read and stored in an array.
 The reading is terminated when the newline character (‘\n’) is entered and the
null character is then inserted at the end of the string.
Writing Strings To Screen

 The printf function with %s format is used to print strings to the screen.
 The format %s can be used to display an array of characters that is terminated by
the null character.
 For example:- printf(“%s”, name);
 This statement can be used to display the entire content of the array name.
Program to Read String from the User using Scanf() Function
Program to Read a Line of Text using fgets() and puts()
Program to read & write strings using printf() and scanf() functions
String Handling Functions

String Manipulation Functions:-


• C library supports a number of string handling functions that can be used to
carry out many of the string manipulations.
• Following are the most common used string-handling functions:-
strcat() FUNCTION

 The strcat function joins two strings together.


 Syntax: strcat(string1, string2);
 string1 and string2 are character arrays.
 When the function strcat is executed, string2 is appended to string1.
 It does so by removing the null character at the end of string1 and placing string2
from there.
 The string at string 2 remains unchanged.
 We make sure that the size of string1 (to which string2 is appended) is large
enough to accommodate the final string.
 C permits nesting of strcat functions.
 For example:- strcat(strcat(string1, string2), string3);
 This statement is allowed and concatenates all the three strings together. The
resultant string is stored in string1.
Program to Implement strcat() Function
strcmp() FUNCTION

•The strcmp function compares two strings.


• Syntax:- strcmp(string1, string2);
•Here, string1 and string2 may be string variables or string constants.
•It compares strings string1 and string2.
•Returns 0 if the two strings are identical.
•Otherwise returns a nonzero integer.
•The magnitude of the output value depends on the compiler that you use.
•This value can differ in simulation and generated code.
•Strings are considered identical when they have the same size and content.
Program to Implement strcmp() Function
strcpy() FUNCTION

 The strcpy function works almost like a string-assignment operator.


 Syntax: strcpy(string1, string2);
 It assigns the content of string2 to string1. It is used to copy one string to another.
 String2 may be a character variable or a string constant.
 Example: strcpy(city, “DELHI”);
 It assign the string “DELHI” to the string variable city.
 Similarly, the statement strcpy(city1, city2);
 It assigns the contents of the string variable city2 to the string variable city1.
 When you use strcpy(), the size of the destination string should be large enough to
store the copied string. Otherwise, it may result in undefined behavior.
Program to Implement strcpy() Function
strlen() FUNCTION

 This function counts and return the number of characters in a string.


 Syntax:
n = strlen(string);
 Where n is an integer variable which receives the value of the length of the string.
 The argument may be a string constant.
 The counting ends at the first null character.
Program to Implement strlen() Function
Poll/Quiz

 Google Form link for quiz on Handling of Character Strings -


Summarize the Lecture

 In Today’s Lecture we discussed about :-


 Handling of character strings.
 Common string operations.
 Declaring and initializing string variables.
 Reading string from terminal.
 Writing strings to screen.
 C programs to read and write strings.
 String handling functions using C programs.
Questions- Related to Topic

Q1. How a string is stored in C? List the important library functions for string
manipulations with example for each.

Q2. Write a program to perform the string comparison.

Q3. How a string is stored in C? Also write a program to concatenate two


strings?

Q4. How string is similar to an array. Write a program to perform string copy
using C.
Outcomes of Today’s Lecture

 What are structures and unions?


 How to define a structure and union, create and using structure and union
variables?
 Examples of creating a structure and a union.
 Difference between structure and unions in terms of memory allocation,
memory location and size of union and structure variables.
 Which one is better structure or union and why?
Union

 Structure:-  Union:-
 Structure is a collection of data items.  Union is similar to a structure data
The data item can be different type, type but can store different values in a
some can be int, float, char and so on.
single location.
 The data item of structure is called  Union will contain many different
member of the structure.
type of values but only one is stored
 In other words, we can say that
at a time.
heterogeneous data types can be
 If a new assignment is made, the
grouped to form a structure.
previous value is automatically
erased.
How to Define a Structure and Union

 How to create structure?  How to create union?


 To create structure in c, we use the
 To create union in c, we use the
keyword called "union".
keyword called "struct".
 We use the following syntax to create
 We use the following syntax to create union in c language.
structures in c language.  union <union_name>
 struct <structure_name> {
{ data_type member1;
data_type member1; data_type member2;
data_type member2; data type member3;
.
data type member3; .
. };
.
};
Example of Creating a Structure and a Union

 Following is the example of creating  Following is the example of creating


a structure called Student which is
a union called Student which is used
used to hold student record.
to hold student record.
 Creating structure in C
 struct Student {
 Creating union in C
 char stud_name[30];  union Student {
 int roll_number;  char stud_name[30];
 float percentage;  int roll_number;
 };  float percentage;
 };
Important Points to be Remembered about Structure and Union

 Important Points to be  Important Points to be


Remembered Remembered
 Every structure must terminated  Every union must terminated
with semicolon symbol (;). with semicolon symbol (;).
 "struct" is a keyword, it must be  "union" is a keyword, it must

used in lowercase letters only. be used in lowercase letters


only.
Create Structure and Union Variables

 Creating and Using structure


 Creating and Using union
variables variables
 In a c programming language, there
 In a c programming language, there
are two ways to create union
are two ways to create structure variables.
variables.  We can create union variable while
 We can create structure variable the union is defined.
while defining the structure.  We can also create after terminating
 We can also create after terminating union using union keyword.
structure using struct keyword.  To access members of a union using
 To access members of a structure union variable, we use dot (.)
operator.
using structure variable, we use dot
(.) operator.
Creating and Using Structure Variables

In this program, the stucture variable "stud_1 is created while defining the structure
and the variable "stud_2 is created using struct keyword. Whenever we access the
members of a structure we use the dot (.) operator.
Creating and using Union Variables
In this program, the union variable "stud_1 is created while defining the union and
the variable "stud_2 is created using union keyword. Whenever we access the
members of a union we use the dot (.) operator.
Difference Between Structure and Union

 Declaration and Initialization of structure starts with struct keyword.

Declaration and Initialization of union starts with union keyword.

 Structure allocates different memory locations for all its members while

union allocates common memory location for all its members. The memory

occupied by a union will be large enough to hold the largest member of the

union.
Difference between structures and unions in terms of Memory
Allocation

 Memory allocation of Structure  Memory allocation of Union


 When the structures are used in the C  When the unions are used in the C
programming language, the memory programming language, the memory
does not allocate on defining a does not allocate on defining union.
structure.  The memory is allocated when we
 The memory is allocated when we create the variable of a particular
create the variable of a particular union.
structure.  As long as the variable of a union is
 As long as the variable of a structure is
created no memory is allocated.
created no memory is allocated.  The size of memory allocated is equal
 The size of memory allocated is equal
to the maximum memory required by
to the sum of memory required by
an individual member among all
individual members of that structure.
members of that union.
Only One Union Member can be Accessed at a Time

 Only one union member can be accessed at a time


 You can access all members of a structure at once as sufficient memory is
allocated for all members.
 However, it's not the case in unions.
 You can only access a single member of a union at one time.
Which one is better structure or union and why?

 Structure:
 Union:
1. It allocates piece of memory that is
1. It allocates memory equal to
large enough to hold the largest
sum of memory allocated to its variable of type in union.
each individual member. 2. One block is used by all the
2. Each member have their own members of union.
memory space. 3. As memory is shared, Ambiguity is
3. Structure can not be more in union.
implemented in shared memory. 4. Only one member is accessed at a
time.
4. It has less Ambiguity.
5. A union is a type that lets you store
5. All members can be accessed at different data types in the same
a time. memory space (but not
6. Structure is a type in which each simultaneously).
defined data type will have its
own memory.
Poll/Quiz

 Google Form link for quiz on Structures and Unions in C -


Practice Questions

Q1. Define a structure consisting of two floating point members, called real
and imaginary. Include the tag complex within the definition.

Q2. Describe the variables x1, x2 and x3 to be structures of type complex, as


described in the preceding problem.

Q3. Combine the structure definition and the variable declarations described
in Probs. 1 and 2 into one declaration.
Summarize the Lecture

 In Today’s Lecture we discussed about :-


 What are structures and unions?
 How to define a structure and union?
 Example of creating a structure and a union.
 Important points to be remembered about structure and union.
 Create and using structure and union variables.
 Differentiate between structure and union in terms of memory allocation
and memory location.
 Why there is difference in the size of union and structure variables?
 Which one is better structure or union and why?
Questions- Related to Topic

Q1. What is structure? Write a program to illustrate the concept of structure


and how member variables are accessed.

Q2. What is the difference between structure and union? Write a program by
using structure that will accept information for 5 employees as name,
address, contact no. and display it.

Q3. Highlight the differences between union and structure data structures
with suitable example.

You might also like