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

C PGM - Unit - 3

The document provides an overview of arrays and functions in C programming, detailing how to define, initialize, and process both one-dimensional and two-dimensional arrays. It also covers sorting algorithms like bubble sort, searching algorithms such as linear and binary search, and the structure and usage of functions including their declarations and prototypes. Key examples illustrate the concepts, making it a comprehensive guide for understanding these fundamental programming constructs.

Uploaded by

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

C PGM - Unit - 3

The document provides an overview of arrays and functions in C programming, detailing how to define, initialize, and process both one-dimensional and two-dimensional arrays. It also covers sorting algorithms like bubble sort, searching algorithms such as linear and binary search, and the structure and usage of functions including their declarations and prototypes. Key examples illustrate the concepts, making it a comprehensive guide for understanding these fundamental programming constructs.

Uploaded by

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

UNIT 3

ARRAYS AND FUNCTION


DEFINITION
• Arrays a kind of data structure that can store a fixed-size sequential
collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
• In C, an array is a collection of elements of the same data type stored
in contiguous memory locations. Here's how you can define,
initialize, and process an array in C.
• All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to the
last element.
EXAMPLE
Access the element in an array:
• Sum of Elements in an Array
#include <stdio.h>
int main() { #include <stdio.h>
// Define an array of integers with a fixed size int main() {
(e.g., 5)
int numbers[5]; int arr[] = {1, 2, 3, 4, 5};
// Initialize the array elements individually int n = 5; // Explicitly define the
numbers[0] = 10; size of the array
numbers[1] = 20;
numbers[2] = 30; int sum = 0;
numbers[3] = 40; for (int i = 0; i < n; i++) {
numbers[4] = 50; sum += arr[i];
// Alternatively, initialize the array during
declaration }
// int numbers[] = {10, 20, 30, 40, 50}; printf("Sum of elements in the
// Accessing array elements
printf("Element at index 2: %d\n", numbers[2]);
array: %d\n", sum);
return 0; return 0;
}
Finding the Maximum Element
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = 5; // Explicitly define the size of the array
int max = numbers[0]; // Assume the first element is the maximum
// Loop through the array to find the maximum element
for (int i = 0; i < size; i++) {
if (numbers[i] > max) {
max = numbers[i]; // Update max if the current element is greater
}
}
printf("The maximum element in the array is: %d\n", max);
return 0;
}
MULTIDIMENSIONAL ARRAY
• C programming language allows multidimensional arrays. Here is the
general form of a multidimensional array declaration
type name[size1][size2]...[sizeN];
• A multidimensional array is an array of arrays. C supports two-
dimensional arrays.
Two-Dimensional Arrays:
• A two-dimensional array in C is a collection of elements organized in
rows and columns. It can be thought of as a table or matrix. The syntax
for declaring a two-dimensional array is as follows:
data_type array_name[rows][columns];
Example
int matrix[2][3];
Initializing Two-Dimensional Arrays:
• You can initialize a two-dimensional array using nested braces:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
• If you don't specify all the elements, the remaining elements are implicitly set
to zero:
int matrix[2][3] = {
{1, 2},
{4}
};
In this case, the elements not specified are set to zero.
An array named matrix is declared and
Example of a 2x3 array initialized as a 2x3 array with the given
#include <stdio.h> values:
int main() { 123
// Declare and initialize a 2x3 array
456
int matrix[2][3] = {
• The program then prints specific
{1, 2, 3}, elements of the array using printf:
{4, 5, 6}
• matrix[0][0]: Accesses the element at the
}; first row and first column, which is 1.
// Accessing elements in the array
• matrix[1][2]: Accesses the element at the
printf("%d\n", matrix[0][0]); // second row and third column, which is 6.
Output: 1
Now, the output:
printf("%d\n", matrix[1][2]); //
Output: 6 1
return 0; 6
}
Processing Two-Dimensional Arrays
Iterating through a two-dimensional array often involves nested loops: An array named matrix is declared and initialized as
#include <stdio.h>
a 3x3 array with the given values:
int main() {
123
// Declare and initialize a 3x3 array
int matrix[3][3] = {
456
{1, 2, 3}, 789
{4, 5, 6}, The program then enters a nested for loop structure.
{7, 8, 9} The outer loop (i) iterates over the rows, and the
inner loop (j) iterates over the columns.
};
// Print the elements of the array
Inside the nested loops, the printf statement prints
each element of the array followed by a space.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
After printing the elements of a row, the inner loop
moves to the next line using printf("\n"), creating a
printf("%d ", matrix[i][j]); new line in the output.
}
the output:
printf("\n");
123
}
return 0;
456
} 789
BUBBLE SORT
• Bubble sort is a simple sorting algorithm.
• This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements
is compared, and the elements are swapped if they are not in order.
• This algorithm is not suitable for large data sets.
ALGORITHM
Step 1: start
STEP 2: initialize the first element and declare the variable
STEP 3: compare first element with the next element in the list or array
STEP 4: swap the smaller number with larger number in the list for j0 to n-1-i
if A[j+1]<A[j], Swap A[j] and A[j+1]
STEP 5: if the numbers are sorted increment to the next element
STEP 6: repeat step 3 and step 4 until n elements in list
Step 7: stop
#include<stdio.h>
int main() { if(a[j] > a[j+1]) {
int a[10], n, i, j, temp; temp = a[j];
a[j] = a[j+1];
printf("Enter the number of elements \
n"); a[j+1] = temp;
scanf("%d", &n); }
}
printf("Enter the array elements \n"); }
for(i=0; i<n; i++)
printf("Sorted Elements are \n");
scanf("%d", &a[i]);
for(i=0; i<n; i++)
printf("%d \t", a[i]);
for(i=0; i<n-1; i++) {
for(j=0; j<n-i-1; j++) {
return 0;
}
LINEAR SEARCH
• Linear search is a type of sequential searching algorithm. In this
method, every element within the input array is traversed and
compared with the key element to be found.
• If a match is found in the array the search is said to be successful; if
there is no match found the search is said to be unsuccessful and gives
the worst-case time complexity.
input: arr[] = [1, 2, 3, 4]; x = 3
Output: 2
There is one test case with array as [1, 2, 3 4] and element to be
searched as 3. Since 3 is present at index 2, the output is 2.
Linear Search Algorithm

The algorithm for linear search is relatively simple. The procedure starts at the
very first index of the input array to be searched.
Step 1 − Start from the 0th index of the input array, compare the key value with
the value present in the 0th index.
Step 2 − If the value matches with the key, return the position at which the
value was found.
Step 3 − If the value does not match with the key, compare the next element in
the array.
Step 4 − Repeat Step 3 until there is a match found. Return the position at
which the match was found.
• Step 5 − If it is an unsuccessful search, print that the element is not present in
the array and exit the program.
#include <stdio.h> • Linear search can be used irrespective
void linear_search(int a[], int n, int key){
int i, count = 0; of whether the array is sorted or not.
for(i = 0; i < n; i++) { • It can be used on arrays of any data
if(a[i] == key) { // compares each element of the array
printf("The element is found at %d position\n", type.
i+1);
count = count + 1;
• Does not require any additional
} memory.
}
if(count == 0) // for unsuccessful search
• It is a well-suited algorithm for small
printf("The element is not present in the array\n"); datasets.
}
int main()
{
int i, n, key;
n = 6;
int a[10] = {12, 44, 32, 18, 4, 10};
key = 18;
linear_search(a, n, key);
key = 23;
linear_search(a, n, key);
return 0;
}
BINARY SEARCH
 This search algorithm works on the principle of divide and conquer.
 This algorithm to work properly, the data collection should be in the sorted
form.
 Search a sorted array by repeatedly dividing the search interval in half.
 Binary search looks for a particular item by comparing the middle most item
of the collection. If a match occurs, then the index of item is returned.
 If the middle item is greater than the item, then the item is searched in the
sub-array to the left of the middle item.
 Otherwise, the item is searched for in the sub-array to the right of the middle
item.
 This process continues on the sub-array as well until the size of the subarray
reduces to zero.
#include<stdio.h> { pos = mid;
main() c = 1;
{
break;
int a[10], n, i, key, low = 0, high, mid, pos=0, c=0;
}
printf("Enter the number of elements \n");
scanf("%d", &n); else if(a[mid] > key)
printf("Enter the array elements \n"); high = mid - 1;
for(i=0 ; i<n ; i++) else
scanf("%d", &a[i]); low = mid + 1;
printf("Enter the element to be searched \n"); }
scanf("%d", &key);
if(c == 0)
high = n-1;
printf("Element not found \n");
while(low <= high)
{
else
mid = (low + high) / 2; printf("Element found at
if(a[mid] == key)
position %d \n", pos);
return 0;
}
• A function is a self-contained block of code that
performs a specific task or set of tasks.
• Functions are used to break down a program into
smaller, manageable pieces, making the code more
modular and easier to understand.
 Defining a function:
• To define a function in C, you use the following syntax:
return_type function_name(parameter1_type
parameter1_name, parameter2_type parameter2_name, ...)
{
// Function body

Function // Statements to perform the task


return return_value; // Return statement (if applicable)
}
• return_type: The data type of the value the function
returns (use void if the function does not return any
value).
• function_name: The name of the function.
• parameters: Input values passed to the function. They
are optional.
• return_value: The value the function returns (if
applicable).
Function Declarations
• A function declaration tells the compiler about a function name and how to call
the function. The actual body of the function can be defined separately.
• A function declaration has the following parts −
return_type function_name( parameter list );
• For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
• Parameter names are not important in function declaration only their type is
required, so the following is also a valid declaration −
int max(int, int);
• Function declaration is required when you define a function in one source file
and you call that function in another file. In such case, you should declare the
function at the top of the file calling the function.
#include <stdio.h> void add(int a, int b) { // a and b
int main() { are formal parameters// Called
int x = 5, y = 10; function
add(x, y); // x and y are the actual printf("Sum = %d\n", a + b);
parameters//Calling Function }
return 0;
}

Feature Actual Parameters Formal Parameters


Values/variables passed in a function
Definition Variables in the function definition.
call.
Location In the callingfunction. In the called function.
Purpose Supplyinputs to the function. Receive and use the inputs.
Scope Limited to the callingfunction. Limited to the called function.

Lifetime Tied to the callingfunction's scope. Exists onlyduringfunction execution.


FUNCTION PROTOTYPE
• A function prototype is a declaration of a function that tells the
compiler about the function's name, return type, and the types of
its parameters.
• A function prototype is typically placed at the beginning of a
program or in a header file to inform the compiler about the
functions that will be used later in the program.
• This allows the compiler to perform type checking and generate
appropriate code for the function calls.
• The general syntax for a function prototype is:
return_type function_name(parameter_type1, parameter_type2, ...);
Function Call
• A function call is a statement that
instructs the compiler to execute the
function. We use the function name
and parameters in the function call.
• In the below example, the first sum
function is called and 10,30 are
passed to the sum function.
• After the function call sum of a and
b is returned and control is also
returned back to the main function
of the program.
Calling a Function
• While creating a C function, you give a definition of what the
function has to do. To use a function, you will have to call that
function to perform the defined task.
• When a program calls a function, the program control is transferred to
the called function. A called function performs a defined task and
when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the
main program.
• To call a function, you simply need to pass the required parameters
along with the function name, and if the function returns a value, then
you can store the returned value.
#include <stdio.h>
In this example:
// Function prototypes
int add(int a, int b); • The add and greet functions are declared
void greet(void); (prototyped) before the main function. This informs
int main() { the compiler about the existence, return types, and
int sum = add(3, 4); parameter types of these functions.
printf("Sum: %d\n", sum);
greet(); • The main function then calls these functions, and
return 0; their actual definitions are provided later in the code.
} • Using function prototypes is especially important
// Function definitions
when functions are defined in a different order than
int add(int a, int b) {
return a + b; they are called, or when functions are defined in
} separate source files.
void greet(void) { • It allows the compiler to understand the function
printf("Hello, world!\n");
signatures and generate the correct code.
}
Write a program to demonstrate the use of recursion to compute the nth Fibonacci number in C
#include <stdio.h>
// Function to calculate the nth Fibonacci number recursively
int fibonacci(int n) {
if (n <= 1) {
return n; // Base case: fib(0) = 0, fib(1) = 1
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
}
int main() {
int n;
printf("Enter the position (n) to compute the Fibonacci number: ");
scanf("%d", &n);
// Calculate and print the nth Fibonacci number
printf("Fibonacci number at position %d is %d\n", n, fibonacci(n));
return 0;
}
STRING MATCHING
String matching algorithm is also called "string searching algorithm.“
This is a vital class of string algorithm is declared as "this is the method to find a place where one
is several strings are found within the larger string."
String matching or searching algorithms try to find places where one or several strings (also
called patterns) are found within a larger string (searched text)
Pattern searching is an important problem in computer science.
When we do search for a string in notepad/word file or browser or database, pattern searching
algorithms are used to show the search results.
There are different types of method is used to finding the string
1. The Naive String Matching Algorithm
2. The Rabin-Karp-Algorithm
3. Finite Automata
4. The Knuth-Morris-Pratt Algorithm
5. The Boyer-Moore Algorithm
#include <stdio.h> 1. Declare two character arrays (str1 and
#include <string.h> str2) to store the input strings.
int main() { 2. Use printf to the user to enter the first
char str1[100], str2[100]; string.
// Input the first string 3. Use gets to read the first string from the
printf("Enter the first string: "); user and store it in the str1 array.
gets(str1); 4. Repeat the process for the second string,
// Input the second string prompting the user with printf and reading
printf("Enter the second string: "); the input with gets into the str2 array.
gets(str2); 5. Use the strcmp function to compare the
// Compare the strings
two strings (str1 and str2).
if (strcmp(str1, str2) == 0) { 6. If strcmp returns 0, it means the strings
printf("Strings are equal.\n");
are equal.
} else { 7. If the return value is not 0, the strings are
not equal.
printf("Strings are not equal.\n");
} 8. Use printf to display whether the strings
are equal or not based on the comparison
return 0;
result.
Advantage of function
• By using function large and difficult program can be divided in to sub
programs and solved.
• When we want to perform some task repeatedly or some code is to be used
more than once at different place in the program, then function avoids this
repetition or rewritten over and over.
• Due to reducing size, modular function it is easy to modify and test.
Notes:-
• C program is a collection of one or more function.
• A function is get called when function is followed by the semicolon.
• A function is defined when a function name followed by a pair of curly
braces.
Function Arguments (also known as Function
Parameters) are the data that is passed to a function.
Example:
int function_name(int var1, int var2);
Conditions of Return Types and Arguments
Function In C programming language, functions can be called
Argument either with or without arguments and might return
s values. They may or might not return values to the
calling functions.
1.Function with no arguments and no return value
2.Function with no arguments and with return value
3.Function with argument and with no return value
4.Function with arguments and with return value
• Any function can be called by another function even main() can be called by
other function.
• Every function in a program must be called directly or indirectly by the
main() function.
• A function can be called any number of times.
• A function can call itself again and again and this process is called recursion.
• A function can be called from other function but a function can’t be defined in
another function
• There are two way through which we can pass the arguments to the function
Call by value
Call by reference.
Call by value
• In the call by value copy of the actual argument is passed to the
formal argument and the operation is done on formal argument.
• When the function is called by ‘call by value’ method, it doesn’t
affect content of the actual argument.
• Changes made to formal argument are local to block of called
function.
• So when the control back to calling function the changes made is
vanish.
Call by reference
• Instead of passing the value of variable, address or reference is
passed.
• The function operate on address of the variable rather than
value.
• Here formal argument is alter to the actual argument, it means
formal arguments calls the actual arguments.
CALL BY VALUE CALL BY REFERENCE
Program to demonstrate the use of Call by Value to swap two numbers
Program to demonstrate the use of Call by Reference to swap two
#include<stdio.h> numbers
swap(int x, int y); #include<stdio.h>
main() swap(int *a, int *b);
main()
{
{
int a,b;
int a,b;
printf("Enter any two values \n"); printf("Enter any two values \n");
scanf("%d %d", &a, &b); scanf("%d %d", &a, &b);
printf("The values before function call a is %d and b is printf("The values before swapping a is %d and b is %d \n", a,
%d \n", a, b); b);
swap(a,b); swap(&a,&b);
printf("The values after function call a is %d and b is %d \ printf("The values after swapping outside the function a is %d
n", a, b); and b is %d \n", a, b);
} }
swap(int *a, int *b)
swap(int x, int y)
{
{ int t;
int t;
t = x; t = *a;
x = y; *a = *b;
y = t; *b = t;
printf("The values after swapping a is %d and b is %d printf("The values after swapping inside the function a is %d
inside the function \n", x, y); and b is %d \n", *a, *b);
}

You might also like