0% found this document useful (0 votes)
10 views33 pages

Psc-Unit 3

The document covers arrays and functions, detailing one-dimensional (1D) and two-dimensional (2D) arrays, including their definitions, representations, and examples in C programming. It also discusses static and dynamic memory allocation for arrays, highlighting their differences and applications. Additionally, it touches on character arrays, strings, and searching algorithms in arrays.

Uploaded by

drarunshalinlv
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)
10 views33 pages

Psc-Unit 3

The document covers arrays and functions, detailing one-dimensional (1D) and two-dimensional (2D) arrays, including their definitions, representations, and examples in C programming. It also discusses static and dynamic memory allocation for arrays, highlighting their differences and applications. Additionally, it touches on character arrays, strings, and searching algorithms in arrays.

Uploaded by

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

UNIT 3 ARRAYS AND FUNCTIONS

3.1 Arrays (1-D, 2-D)

Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache
friendliness. There are mainly three types of the array:

 One Dimensional (1D) Array


 Two Dimension (2D) Array
 Multidimensional Array
3.1.1 One Dimensional Array:
 It is a list of the variable of similar data types.

 It allows random access and all the elements can be accessed with the help of their
index.

 The size of the array is fixed.


 For a dynamically sized array, vector can be used in C++.
 Representation of 1D array:

EXAMPLE:

// C program to illustrate how to create an array,


// initialize it, update and access elements
#include <stdio.h>
int main()
{
// declaring and initializing array
int arr[5] = { 1, 2, 4, 8, 16 };
// printing it
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// updating elements
arr[3] = 9721;
// printing again
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
OutPut:
1 2 4 8 16
1 2 4 9721 16

3.1.2 Two Dimensional Array:


 It is a list of lists of the variable of the same data type.
 It also allows random access and all the elements can be accessed with the help of
their index.
 It can also be seen as a collection of 1D arrays. It is also known as the Matrix.

 Its dimension can be increased from 2 to 3 and 4 so on.


 They all are referred to as a multi-dimension array.
 The most common multidimensional array is a 2D array.
Representation of 2 D array:
Example:

#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;
}
Run Code
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

Matrix Multiplication:
Input:
mat1[][] = {{1, 2},{3, 4}}
mat2[][] = {{5, 6},{7, 8}}
Multiplication of two matrices:

{{1*5 + 2*7 1*6 + 2*8},


{3*5 + 4*7 3*6 + 4*8}}
Output:
{{19, 22},
{43, 50}}
// C program to multiply two matrices
#include <stdio.h>
#include <stdlib.h>
// matrix dimensions so that we dont have to pass them as
// parametersmat1[R1][C1] and mat2[R2][C2]
#define R1 2 // number of rows in Matrix-1
#define C1 2 // number of columns in Matrix-1
#define R2 2 // number of rows in Matrix-2
#define C2 3 // number of columns in Matrix-2
void multiplyMatrix(int m1[][C1], int m2[][C2])
{
int result[R1][C2];
printf("Resultant Matrix is:\n");
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
result[i][j] = 0;
for (int k = 0; k < R2; k++) {
result[i][j] += m1[i][k] * m2[k][j];
}
printf("%d\t", result[i][j]);
}
printf("\n");
}
}
// Driver code
int main()
{
// R1 = 4, C1 = 4 and R2 = 4, C2 = 4 (Update these
// values in MACROs)
int m1[R1][C1] = { { 1, 1 }, { 2, 2 } };
int m2[R2][C2] = { { 1, 1, 1 }, { 2, 2, 2 } };

// if coloumn of m1 not equal to rows of m2


if (C1 != R2) {
printf("The number of columns in Matrix-1 must be "
"equal to the number of rows in "
"Matrix-2\n");
printf("Please update MACROs value according to "
"your array dimension in "
"#define section\n");
exit(EXIT_FAILURE);
}
// Function call
multiplyMatrix(m1, m2);
return 0;
}

Output

Resultant Matrix is:


3 3 3
6 6 6

Difference Table:

One Dimension
Basis Two Dimension Array
Array

Store a single list Store a ‘list of lists’ of the


Definition of the element of element of a similar data
a similar data type. type.
One Dimension
Basis Two Dimension Array
Array

Represent multiple data


Represent multiple
Representation items as a table consisting of
data items as a list.
rows and columns.

The declaration
varies for different The declaration varies for
programming different programming
language: language:
1. For C++, 1. For C++,
datatype datatype
Declaration variable_name[ro variable_name[row][column
w] ]

2. For Java, 2. For Java,


datatype [] datatype [][]
variable_name= variable_name= new
new datatype[row][column]
datatype[row]

Dimension One Two

size of(datatype of the


size of(datatype of the variable of the array)*
Size(bytes) variable of the array) * size
the number of rows* the number of columns.
of the array

Address of a[i][j] can be calculated in two


ways row-major and column-major
Address of a[index] is equal 1. Column Major: Base Address + Size of
Address to (base Address+ Size of each element (number of rows(j-lower
calculation. each element of array * bound of the column)+(i-lower bound
index). of the rows))
2. Row Major: Base Address + Size of
each element (number of columns(i-
lower bound of the row)+(j-lower
bound of the column))

int arr[5]; //an array with int arr[2][5]; //an array with two rows and
one row and five columns five columns will be created.
Example will be created. a b c d e
{a , b , c , d , e} f g h i j

3.1.3 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.
3.2 Static and Dynamic Array Allocation
According to the concept of array, an array can be defined in two ways as per the memory
allocation concept.
Types of Arrays:
There are basically two types of arrays: Static Array & Dynamic Array

3.2.1 Static Array: In this type of array, memory is allocated at compile time having a fixed
size of it. We cannot alter or update the size of this array.
Example:
Let us take an example, int a[5] creates an array of size 5 which means that we can insert only
5 elements; we will not be able to add 6th element because the size of the array is fixed
above.

int a[5] = {1, 2, 3, 4, 5}; //Static Integer Array


int *a = new int[5]; //Dynamic Integer Array

Example of Static Array: int a[5] = {1, 2, 3, 4, 5};


 A static integer array named a and initializes with the values 1, 2, 3, 4, and 5.
 The size of this array is determined automatically based on the number of values
provided in the initialization list.
 Thus the array a is allocated on the stack, and its size cannot be changed once defined.
3.2.2 Dynamic Array: Dynamic arrays in C are arrays that can change size during runtime,
unlike static arrays whose size is fixed at compile time. In this type of array, memory is
allocated at run time but not having a fixed size. Suppose, a user wants to declare any
random size of an array, then we will not use a static array, instead of that a dynamic
array is used in hand. It is used to specify the size of it during the run time of any
program.
Creating a Dynamic Array
1. Using malloc() Function:
int *array;
int size = 10;

array = (int *)malloc(size * sizeof(int));


2. Using calloc() Function:
int *array;
int size = 10;
array = (int *)calloc(size, sizeof(int));

3. Resizing with realloc() Function:


int newSize = 20;
array = (int *)realloc(array, newSize * sizeof(int));

3.2.3 The differences between static and dynamic arrays

S.No Static Memory Allocation Dynamic Memory Allocation

In the Dynamic memory


In the static memory allocation, the memory is
allocation, variables get controlled by the programmer. It
1 allocated permanently, till gets allocated whenever a
the program executes or malloc() is executed gets
function call finishes. deallocated wherever the free() is
executed.

Static Memory Allocation Dynamic Memory Allocation is


2
is done before program done during program execution.
execution.

It uses heap (not heap data


It uses stack for managing
structure) of memory for
3 the static allocation of
managing the dynamic allocation
memory
of memory

4 It is less efficient It is more efficient

In Dynamic Memory Allocation,


In Static Memory
there is memory re-usability and
5 Allocation, there is no
memory can be freed when not
memory re-usability
required

In static memory
allocation, once the In dynamic memory allocation,
6 memory is allocated, the when memory is allocated the
memory size can not memory size can be changed.
change.

This allows reusing the memory.


In this memory allocation The user can allocate more
7 scheme, we cannot reuse memory when required. Also, the
the unused memory. user can release the memory
when the user needs it.

In this memory allocation


In this memory allocation
scheme, execution is
8 scheme, execution is slower than
faster than dynamic
static memory allocation.
memory allocation.

In this memory is In this memory is allocated at run


9
allocated at compile time. time.

10 In this allocated memory In this allocated memory can be


remains from start to end released at any time during the
of the program. program.

Example: This static Example: This dynamic memory


11 memory allocation is allocation is generally used
generally used for array. for linked list.

Example:
// C program to create dynamic array using malloc() function

#include <stdio.h>
#include <stdlib.h>
int main()
{

// address of the block created hold by this pointer


int* ptr;
int size;

// Size of the array


printf("Enter size of elements:");
scanf("%d", &size);

// Memory allocates dynamically using malloc()


ptr = (int*)malloc(size * sizeof(int));

// Checking for memory allocation


if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {

// Memory allocated
printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
}
}

return 0;
}

Output:
Enter size of elements:5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

3.3 Character arrays and Strings


An array of strings in C is a two-dimensional array of character types. Each String is
terminated with a null character (\0). It is an application of a 2d array.
Syntax:
char variable_name[r][m] = {list of string};
Here,
 var_name is the name of the variable in C.

 r is the maximum number of string values that can be stored in a string array.
 m is the maximum number of character values that can be stored in each string array.
Example:
// C Program to print Array
// of strings
#include <stdio.h>
// Driver code
int main()
{
char arr[3][10] = {"GURU",
"JEEVITH", "GURUJEEVI"};
printf("String array Elements are:\n");

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


{
printf("%s\n", arr[i]);
}
return 0;
}
Output:
String array Elements are:
GURU
JEEVITH
GURUJEEVI

3.4 Searching Algorithms


Searching is one of the most common operations performed in an array. Array searching can
be defined as the operation of finding a particular element or a group of elements in the
array.
There are several searching algorithms. The most commonly used among them are:
 Linear Search
 Binary Search
 Ternary Search

3.4.1 Linear Search:


Linear Search is defined as a sequential search algorithm that starts at one end and goes
through each element of a list until the desired element or group of elements is found.
Otherwise, the search continues till the end of the data set. This has a time complexity
of O(N) where ‘N’ is the length of the array.

Ex:
#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
Output:
Enter number of elements in array
3
Enter 3 integer(s)
4
5
2
Enter a number to search
5
5 is present at location 2.
3.4.2 Binary Search:
Binary Search is a searching algorithm used in a sorted array. In this algorithm, the
element is found by repeatedly dividing the search interval in half and deciding the next
interval to find the element. This searching algorithm has a time complexity
of O(log 2 N) where ‘N’ is the length of the array. The only thing to note is that the array must
be sorted in increasing or decreasing order.
Ex:
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
Output:
Enter number of elements
3
Enter 3 integers
4
2
5
Enter value to find
2
2 found at location 2.

3.4.3 Ternary Search:


Ternary search is a divide and conquer algorithm that can be used to find an element in an
array. It is similar to binary search where we divide the array into two parts but in this
algorithm, we divide the given array into three parts and determine which has the key
(searched element). This algorithm also has the constraint that the array must be sorted. The
time complexity for this algorithm is O(log 3 N) where ‘N’ is the size of the array.

3.5 Sorting Algorithm


A Sorting Algorithm is used to rearrange a given array or list of elements according to a
comparison operator on the elements. The comparison operator is used to decide the new
order of elements in the respective data structure.
For Example: The below list of characters is sorted in increasing order of their ASCII values.
That is, the character with a lesser ASCII value will be placed first than the character with a
higher ASCII value.

Ex:
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
Output:
0 2 6 11 12 18 34 45 55 99

3.6 Built in functions (Predefined standard library functions)


Standard library functions are also known as built-in functions. Functions such
as puts(), gets(), printf(), scanf() etc are standard library functions. These functions are already
defined in header files (files with .h extensions are called header files such as stdio.h), so we
just call them whenever there is a need to use them.
For example, printf() function is defined in <stdio.h> header file so in order to use
the printf() function, we need to include the <stdio.h> header file in our program
using #include <stdio.h>.
3.7 User Defined functions
The functions that we create in a program are known as user defined functions or in other
words you can say that a function created by user is known as user defined function.
Now we will learn how to create user defined functions and how to use them in C
Programming.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls

Syntax of a function

return_type function_name (argument list)


{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double, char, void, short etc.
Don’t worry you will understand these terms better once you go through the examples below.
function_name: It can be anything, however it is advised to have a meaningful name for the
functions so that it would be easy to understand the purpose of function just by seeing it’s
name.
argument list: Argument list contains variables names along with their data types. These
arguments are kind of inputs for the function. For example – A function which is used to add
two integer variables, will be having two integer argument.
Block of code: Set of C statements, which will be executed whenever a call will be made to the
function.
3.7.1 Function Declarations

In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function
with the given name defined somewhere else in the program.

Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Declaration
Note: A function in C must always be declared globally before calling it.
3.7.2 Function Definition

The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).

A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The
below example serves as both a function definition and a declaration.

return_type function_name (para1_type para1_name, para2_type para2_name)


{
// body of the function
}

3.7.3 FUNCTION PROTOTYPES WITH DIFFERENT RETURN VALUES AND TYPES


• A function may or may not accept any argument. • It may or may not return any value.
• Based on these facts, there are four different aspects of function calls:
1.FUNCTION WITHOUT ARGUMENTS AND WITHOUT RETURN VALUE

2.FUNCTION WITHOUT ARGUMENTS AND WITH RETURN VALUE


3.FUNCTION WITH ARGUMENTS AND WITH RETURN VALUE
4.FUNCTION WITH ARGUMENTS AND WITHOUT RETURN VALUE

Type 1.FUNCTION WITHOUT ARGUMENTS AND WITHOUT RETURN VALUE


Example :
#include<stdio.h>
void sum();
void main()
{
sum();
}
void sum() {
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output: Enter two numbers 10 25
The sum is 35
Type 2: FUNCTION WITHOUT ARGUMENTS AND WITH RETURN VALUE

Example:Function without argument and with return value


#include<stdio.h>
int sum();
void main() {
int result;
result = sum();
printf("%d",result);
}
int sum() {
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output:
Enter two numbers 10 25
The sum is 35

Type 3: FUNCTION WITHOUT ARGUMENTS AND WITH RETURN VALUEFunction with


arguments and return values

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b) {
return a+b; }
Output:
Enter two numbers 10 25
The sum is 35
Type 4: Function with argument and no return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b) {
printf("\nThe sum is %d",a+b); }

Output: Enter two numbers 10 24 The sum is 34

3.7.4 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.
Working of function in C
Note: Function call is neccessary to bring the program control to the function definition. If not
called, the function statements will not be executed.
Example of C Function
// C program to show function
// call and definition
#include <stdio.h>
// Function that takes two parameters
// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}
// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
Output: Sum is: 40

3.7.5 TYPES OF FUNCTION


There are two types of functions in C programming:
i. Library Functions:
• The functions which are declared in the C header files such as scanf(), printf(), gets(),
puts(), etc.
ii. User-defined functions:
• The functions which are created by the C programmer, so that he/she can use it many
times.
• It reduces the complexity of a big program and optimizes the code.

3.8 Scope of a Function:


In C, the scope of a variable refers to the region in the program where it is declared, defined,
and used. Here are the key points:

3.8.1 Global Scope:


Variables declared outside any block or function have global scope. They are visible
throughout the entire program. Global variables are also called file scope.
Example:
#include <stdio.h>
int global = 5; // Global variable
void display() {
printf("%d\n", global);
}
int main() {
printf("Before change within main: ");
display();
global = 10;
printf("After change within main: ");
display();
return 0;
}
Output:
Before change within main: 5
After change within main: 10

3.8.2 Local Scope:


Variables declared inside a block or function have local scope. They are visible only within that
block or function. Local variables are also called block scope.
Example:
#include <stdio.h>
int main() {
{
int x = 10, y = 20;
{
printf("x = %d, y = %d\n", x, y); // 10 and 20
{
int y = 40;
x++;
y++;
printf("x = %d, y = %d\n", x, y); // 11 and 41
}
printf("x = %d, y = %d\n", x, y); // 11 and 20
}
}
return 0;
}
Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20

3.8.3 Visibility of variables in function:


A function parameter’s scope is the entire function body. It can be shadowed by a local
variable with the same name.
Example:
int x = 42;
void foo(int x) {
printf("%d\n", x); // Prints the function parameter value
}

Remember that global variables have external linkage by default, but you can restrict access to
the current file by marking them as static. Local variables have internal linkage within their
block or function.

3.9 Parameter passing in functions


3.9.1 Call by Value:
Call by Value
Call by value in C is where in the arguments we pass value and that value can be used in
function for performing the operation. Values passed in the function are stored in temporary
memory so the changes performed in the function don’t affect the actual value of the variable
passed.
Ex:
// Call by value
#include <stdio.h>
// Call by value
int sum(int x, int y)
{
int c;
c = x + y;
// Integer value retured
return c;
}
// Driver Code
int main()
{
// Integer Declared
int a = 3, b = 2;
// Function Called
int c = sum(a, b);
printf("Sum of %d and %d : %d", a, b, c);
return 0;
}
Output: Sum of 3 and 2 : 5

3.9.2 Call by Reference

Call by reference is the method in C where we call the function with the passing address as
arguments. We pass the address of the memory blocks which can be further stored in a
pointer variable that can be used in the function. Now, changes performed in the values inside
the function can be directly reflected in the main memory.

Ex:
// C Program to implement
// Call by reference
#include <stdio.h>
// Call by reference
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
// Driver Code
int main()
{
// Declaring Integer
int x = 1, y = 5;
printf("Before Swapping: x:%d , y:%d\n", x, y);
// Calling the function
swap(&x, &y);
printf("After Swapping: x:%d , y:%d\n", x, y);
return 0;
}
Output:
Before Swapping: x:1 , y:5
After Swapping: x:5 , y:1

3.9.3 Passing Arrays to function in C:

In C, when passing an array to a function, you have a few options:

Passing by Pointer (Preferred):


You can pass a pointer to the first element of the array. The function receives the address of
the array, allowing it to access the entire array.
Example:
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[8] = {12, 4, 5, 3, 7, 8, 11, 45};
int size = sizeof(arr) / sizeof(arr[0]);
printArray(arr, size);
return 0;
}
Output: 12 4 5 3 7 8 11 45
Passing by Value:
You can declare the array in the function parameter list. The function receives a copy of the
array, which is less efficient.

Example:
#include <stdio.h>
void func(int arr[8]) {
// Size information is lost; arr behaves like a pointer
printf("Size of arr[] in func(): %d bytes\n", sizeof(arr));
}
int main() {
int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
printf("Size of arr[] in main(): %d bytes\n", sizeof(arr));
func(arr);
return 0;
}
Output:
Size of arr[] in main(): 32 bytes
Size of arr[] in func(): 8 bytes

Remember that passing an array to a function results in array decay, where the array loses
information about its size. One way to handle this is by passing the size of the array as an
additional parameter to the function.

3.10 STRING HANDLING OR MANIPULATION FUNCTIONS

Strings handling functions are defined under "string.h" header file. #include<string.h>
Few Predefined String Function and its Purpose:
• strlen() String length computes string's length strcpy() String Copy copies a string to
another
• strcat() String Concatenation concatenates(joins) two strings strcmp() String
Comparison compares two strings
• strlwr() String Lower converts string to lowercase strupr() String Upper converts string
to uppercase strrev() String Reverse reverses the given string
• strncat(), strncmp(), strncpy() n -> denotes number of strings

Syntax:
char var_name[size]=“String”;
Example program for Handling of Character Strings:
#include<stdio.h>
#include<conio.h>
{ char a[6]=“Cse”;
clrscr();
printf(“Enter a string : “);
scanf(“%s”,a);
printf(“Your String is : %s”,a);
getch();
}

Output:
Your String is : cse

3.10.1 List of String Functions

• strlen() - It is used to find the length of the string.


• strcpy() - It is used to copy one string to another.
• strcat() - It is used to combine two strings.
• strcmp()-It is used to compare two strings. Returns 0 if two strings are equal.
• strrev()-It used to reverse a string.
 strlwr(), strupr()- It used to change the case of a string.

3.10.2 strlen( ) Function :


• The strlen() function calculates the length of a given string.
• The strlen() function is defined in string.h header file.
• It doesn’t count null character ‘\0’.
Syntax:
int strlen(const char *str);
syntax:
strlen(string)
Example:
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
char a[]="college"; int b;
clrscr(); b=strlen(a);
printf("\nThe length of the string is %d",b);
getch();
}
Output:
The length of the string is 7
3.10.3 strcpy( ) Function :
• It copies the string str2 into string str1, including the end character (terminator char ‘\0’).
Syntax:
char *strcpy( char *str1, char *str2); strncpy() Function:
char *strncpy( char *str1, char *str2, size_t n); strncpy(s1,s2, 3);
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = “Welcome";
char s2[30] = “TAMIL NADU";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: TAMILNADU

Example 2:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]=“Cse";
char b[]="Dept";
clrscr();
strcpy(a,b);
printf("\nThe string is %s",a);
getch();
}
Output:
The string is Dept
3.10.4 strcat( ) Function :
• It concatenates two strings and returns the concatenated string.
Syntax:
strcat(string1,string2);
Example:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]=“Cse";
char b[]="Dept";
clrscr();
strcat(a,b);
printf("\nThe string is %s",a);
getch();
}
Output:
The string is CseDept
3.10.5 strcmp( ) Function :
• It compares the two strings and returns an integer value.
• If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
• If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.
• If string1 > string2 then it would return positive value.
• If string1 == string2 then you would get 0(zero) when you use this function for compare
strings.
Syntax: int strcmp(const char *str1, const char *str2);
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = “ProblemSolving";
char s2[20] = “ProblemSolvingusingC";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}

else {
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string 1 and 2 are different
Example 2:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[10]=“csedept";
char b[10]=“cse";
int i;
clrscr();
i=strcmp(a,b);
if(i==0)
printf(“Strings are equal”);
else
printf("Strings are not equal”);
getch();
}
Output:
Strings are not equal
3.10.6 strrev()
It used to reverse a string.
syntax: strrev(string);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[]="Dept";
clrscr();
printf("\nThe reversed string is %s",strrev(a));
getch();
}

Output:
The string is tpeD

Example 2: String Palindrome


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s1[15], s2[15];
printf("\nenter the string:");
scanf("%s",s1);
strcpy(s2,s1);
strrev(s1);
if(strcmp(s1,s2)==0)
printf("\n The string is palindrome");
else
printf("\n The string is not a palindrome");
getch();
}
Output:
enter the string: aba
The string is palindrome

3.10.7 strlwr(), strupr()


It used to change the case of a string.
syntax:
strlwr(string);
strupr(string);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[20]=“csedept";
clrscr();
printf("\nThe string is :%s",a);
strupr(a);
printf("\nThe string after conversion to uppercase :%s",a);
strlwr(a);
printf("\nThe string after conversion to lowercase :%s",a);
getch();
}
Output
The string is :csedept
The string after conversion to uppercase :CSEDEPT
The string after conversion to lowercase :csedept

3.11 Recursion Function:

In C programming, recursion is a powerful concept where a function calls itself repeatedly until
a certain condition is met. Let’s explore the basics of recursion, recursive functions, and how
they differ from iteration.

Definition:
A function that calls itself is called a recursive function. Recursive functions can contain
multiple recursive calls. So Recursion is the process of a function calling itself directly or
indirectly. They are used to solve complex problems by breaking them down into simpler sub-
problems.
Basic Structure of Recursive Functions:
type function_name(args) {
// Base condition
// Recursion case (recursive call)
}

Example: Sum of First N Natural Numbers


Let’s calculate the sum of the first N natural numbers using recursion:

#include <stdio.h>

int nSum(int n) {
// Base condition to terminate recursion when N = 0
if (n == 0) {
return 0;
}
// Recursive case (recursive call)
int res = n + nSum(n - 1);
return res;
}

int main() {
int n = 5;
int sum = nSum(n);
printf("Sum of First %d Natural Numbers: %d", n, sum);
return 0;
}

Output:
Sum of First 5 Natural Numbers: 15

In this example, the nSum function calculates the sum of the first N natural numbers. It
demonstrates the fundamental concepts of recursion: the base condition (when to stop) and
the recursion case (how to break down the problem).

You might also like