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

PC Unit 3

Uploaded by

elitetube1
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)
66 views

PC Unit 3

Uploaded by

elitetube1
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/ 74

UNIT-III ARRAYS AND FUNCTIONS Periods: 09

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations- Function – definition of
function – Declaration of function – Pass by value – Pass by reference –
Recursion
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
Arrays

An array is a group of related data items that share a common name. The value is indicated bywriting a number
called index number or subscript in brackets after the array name.

Syntax:
type variable-name[size];

Examples :
int salary[10];
float height[50];
int group[10];
char name[10];
PROPERTIES OF AN ARRAY
 All the elements of an array share the same name and they are
distinguished from one another with the help of an element number.
 The element number in an array plays major role for calling each
element.
 The type of an array is the data type of its elements.
 The array elements are stored in continuous memory locations.
 The location of an array is the location of its first element.
 The length of an array is the no. of data elements in the array.
 The size of an array is the length of the array times the size of an
elements.
TYPES OF ARRAY
(i) One dimensional array
(ii) Two dimensional array
(iii) Multi dimensional array

(i) One dimensional array

An array with a single subscript is known as one dimensional array.


It is otherwise known as single-subscribed (or) linear (or) one-dimensional arrays.

Example
int number[5];
The memory representation of above example is given below in pictorial form.

Array name number[0] number[1] number[2] number[3] number[4]

Value stored 12 15 6 17 25

Address 1024 1026 1028 1030 1032


A two-dimensional array or 2D array in C is the simplest form of the multidimensional array. We can visualize a
two-dimensional array as an array of one-dimensional arrays arranged one over another forming a table with ‘x’ rows
and ‘y’ columns where the row number ranges from 0 to (x-1) and the column number ranges from 0 to (y-1).
Syntax:
datatype array-name[row_size][column_size];
Example
int a[3][3];

column 0 column 1 column 2

row 0 a[0][0] a[0][1] a[0][2]

row 1 a[1][0] a[1][1] a[1][2]

row 2 a[2][0] a[2][1] a[2][2]


Three-Dimensional Array in C
A Three Dimensional Array or 3D array in C is a collection of two-dimensional arrays. It can be visualized as
multiple 2D arrays stacked on top of each other.
C Array Initialization – one dimension array

Array Initialization with Declaration


In this method, we initialize the array along with its declaration. We use an initializer list to initialize multiple elements
of the array. An initializer list is the list of values enclosed within braces { } separated b a comma.

data_type array_name [size] = {value1, value2, ... valueN};

Array Initialization with Declaration without Size


The size of the array in these cases is equal to the number of
elements present in the initializer list as the compiler can
automatically deduce the size of the array.

data_type array_name[] = {1,2,3,4,5};

Array Initialization after Declaration (Using Loops)

We initialize the array after the declaration by assigning the initial value to each element individually. We can use for
loop, while loop, or do-while loop to assign the value to each element of the array.

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


{
array_name[i] = valuei;
}
Initialization of Two-Dimensional Arrays in C
The various ways in which a 2D array can be initialized are as follows:

1.Using Initializer List


2.Using Loops

Initialization of 2D array using Initializer List


First Method:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

Second Method (better):

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};


Initialization of 2D array using Loops
int x[3][4];

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


{
for(int j = 0; j < 4; j++)
{
scanf(“%d”,&x[i][j]);
}
}
Declaration of Three-Dimensional Array in C
We can declare a 3D array with x 2D arrays each having y rows and z columns using the syntax shown below.

data_type array_name[x][y][z]; int array[3][3][3];

•data_type: Type of data to be stored in each element.


•array_name: name of the array
•x: Number of 2D arrays.
•y: Number of rows in each 2D array.
•z: Number of columns in each 2D array.

Initialization of Three-Dimensional Array in C


Initialization of 3D Array using Initializer List
1.Initializer List
Method 1:
2.Loops
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23};

Method 2(Better):
int x[2][3][4] =
{ { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }};
//Program to display character array with address
//one dimensional array
#include<stdio.h>
#include<conio.h>
void main() Output
{ Character memory location
char name[10] ={‘A’,’B’,’C’,’D’,’E’}; [A] 3001
int i=0; [B] 3002
clrscr(); [C] 3003
printf(“\n Character memory location \n”); [D] 3004
while(name[i]!=‘\0’) [E] 3005
{
printf(“\n [%c] \t \t [%u]”,name[i],&name[i]);
i++;
getch();
}
}
// C Program to print the elements of a
// Two-Dimensional array

#include <stdio.h>
int main(void)
{
// an array with 3 rows and 2 columns. OUTPUT
int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
Element at x[0][0]: 0
// output each array element's value Element at x[0][1]: 1
for (int i = 0; i < 3; i++) { Element at x[1][0]: 2
for (int j = 0; j < 2; j++) { Element at x[1][1]: 3
printf("Element at x[%i][%i]: ", i, j); Element at x[2][0]: 4
printf("%d\n", x[i][j]); Element at x[2][1]: 5
}
}

return (0);
}
// C Program to store and print 12 values entered by the user Output
#include <stdio.h> COLUMN 0 COLUMN 1 Enter 12 values:
int main() 1
{ test[0][0][0] test[0][0][1] 2
int test[2][3][2]; ROW 0 1 2 3
printf("Enter 12 values: \n"); 4
for (int i = 0; i < 2; ++i) test[0][1][0] test[0][1][1] 5
{ ROW 1 3 4 ARRAY 0 6
for (int j = 0; j < 3; ++j) 7
{ 8
ROW 2 test[0][2][0] test[0][2][1]
for (int k = 0; k < 2; ++k) 9
{ 5 6 10
scanf("%d", &test[i][j][k]); 11
} 12
} Displaying Values:
} COLUMN 0 COLUMN 1 test[0][0][0] = 1
// Printing values with proper index. test[0][0][1] = 2
printf("\nDisplaying values:\n"); test[1][0][0] test[1][0][1] test[0][1][0] = 3
for (int i = 0; i < 2; ++i) 7 8 ROW 0 test[0][1][1] = 4
{ test[0][2][0] = 5
for (int j = 0; j < 3; ++j) test[0][2][1] = 6
test[1][1][0] test[1][1][1]
{ for (int k = 0; k < 2; ++k) ARRAY 1 ROW 1 test[1][0][0] = 7
{ printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]); 9 10
test[1][0][1] = 8
}
test[1][1][0] = 9
} test[1][2][0] test[1][2][1] ROW 2
test[1][1][1] = 10
} 11 12 test[1][2][0] = 11
return 0;
} test[1][2][1] = 12
INITIALIZATION OF ARRAYS
We can also initialize the elements of arrays like an ordinary variable initialization.
An array can be initialized in two way, they are
 Compile time initialization.
 Run time initialization.

Compile time Initialization


Initialization in made at the time of declaration (in the declaration part) is known as compile time initialization. The
general form of initialization of arrays is:
Syntax
datatype array-name[size] = {list of values};
Examples
int rollno[3] = {26,32,12};
Example:
 The value of array are enclosed in braces and separated by commas. static int counter[] = {1,1,1};
 The values are assigned to the array by assignment operator (=).
 If the number of values in the list is less than the number of elements, then only that many elements will be initialized.
 The remaining elements will be set to zero automatically.
 We can use the word ‘static’ before type declaration. This declares the variable as a staticvariable.
Run time Initialization

When the users have to initialize more number of elements means it is difficult to use compile time initialization. To
avoid this situation the user can initialize elements in run time.

/*Program showing one-dimensional array*/


#include<stdio.h>
#include<conio.h> void main()
{
int a[100],sum=0,i,n;clrscr();
printf(“Enter no. of terms:”);
scanf(“%d”,&n);
printf("Enter %d integer numbers\n",n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of given numbers is : %d\n",sum);
getch();
}
UNIT-III ARRAYS AND FUNCTIONS Periods: 09

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations- Function – definition of
function – Declaration of function – Pass by value – Pass by reference –
Recursion
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
Strings in C
A String in C programming is a sequence of characters terminated with a null character ‘\0’. The C String is stored as
an array of characters. The difference between a character array and a C string is that the string in C is terminated
with a unique character ‘\0’.

C String Declaration Syntax


Declaring a string in C is as simple as declaring a one-dimensional array.
Below is the basic syntax for declaring a string.
char string_name[size];
String
Introduction
The character string is one of the most useful and important data types.
The C string library provides a wide range of functions for strings like reading,writing, copying,
comparing,combining,searching,etc.
A string literals constant is a sequence of characters treated as a single data item enclosed within
double quotes.
(or)
In C program language the group of characters, digits and symbols enclosed within quotation marks
are called as string.
Syntax
data_type string_name[size]=“string”;
The size determines the number of characters in a string.For example,
char name[30];
Declaration and Initialization of a string
example 1
char name[]=“CHENNAI”;
The C compiler inserts the NULL(\0) character automatically at the end of the string. Hence the
initialization of the NULL character is not essential. Even if null is added at the end of the
string,compiler does not throw any error. Other format are
Example:
char name[8]=“CHENNAI”;
or
char name[8]={‘C’,’H’,’E’,’N’,’N’,’A’,’I’,\0};
C permits the storage of string to any length.However, if a string exceeds the limit a character array will
overwrite the data beyond the array.
//Program to print ‘WELCOME’ by using different syntax of initialization of array
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{

char array1[9]={‘W’,’E’,’L’,’C’,’O’,’M’,’E’,’\0’};
char array2[9]=“WELCOME”;
char array3[9]={{‘W’},{‘E’}, {‘L’},{‘C’} {‘O’},{‘M’},{‘E’}};
clrscr();
printf(“\n first output=%s”,array1);
printf(“\n second output=%s”,array2);
printf(“\n third output=%s”,array3);
getch();
}
Output
first output =WELCOME
second output =WELCOME
third output =WELCOME
Reading strings
There are three functions to read strings as shown in table with the syntax
Sno Function Syntax //Program to read a string using gets function
#include<stdio.h>
1. scanf scanf(“%s”,variablename); int main(void)
2. getchar variablename=getchar(); {
char name[30];
3. gets gets(str); printf(“what’s your name?\n”);
gets(name);
#include <stdio.h> printf(“Name is:%s\n”,name);
#include <conio.h> return 0;
void main() }
{ Output
char c; what’s your name?
printf ("\n Enter a character \n"); mohan
c = getchar(); // get a single character Name is mohan
printf(" You have passed ");
putchar(c); // print a single character using putchar
getch();
} OUTPUT
Enter a character
A
You have passed A
Writing Strings
Strings can be displayed using three function as shown in the table
Sno Function Syntax
1. printf printf(“%s”,variable name);
2. putchar putchar(char_var);
3. puts puts(string);

//Program to convert the given character to uppercase using putchar() and getchar() function
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char c;
clrscr();
c=getchar();
putchar(toupper(c));
getch();
}
Output
sairam
SAIRAM
//program using puts() function in printing the string
#include<stdio.h>
int main()
{
char s[100];
printf(“enter the text:”);
gets(s);
printf(“\n entered text:”);
puts(s);
return 0;
}

Output
Enter the text: Welcome to Chennai
entered text: Welcome to Chennai
String Library Functions
The C string library provides a large number of functions that can be used for string manipulation.
The header file string.h is to be initialized whenever standard library function is used.C string library
functions names are
Function name Description
strlen Returns the length of the string
strlwr Returns upper case letter to lower case
strupr Returns lower case letter to upper case letter
strcat concatenate two string
strcmp compare two string
strrev reverse the contents of a string
strcpy copies a string from source to destination
i)strlen function
The strlen function is used to find the length of the string.
Syntax
n=strlen(string);
where ‘n’ is an integer variable, which receives the value of length of the string. The counting ends at the
first null character \0 null character is not taken into consideration.

//Program for the function strlen()


#include<stdio.h>
#include <string.h>
int main()
{
char ch[]={'g', 'e', 'e', 'k', 's', '\0'};
printf("Length of string is: %d", strlen(ch));
return 0;
}

Output
Length of string is: 5
ii)strcyp function
The strcpy function copies the source string to the destination string.
Syntax
strcpy(string1,string2);
here,string 1 is the destination and string 2 is the source string.
//Program to copy the contents of one string to another string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() Output
Source string is Hello
{
Destination string is Hello
char scr[50]=“Hello”;
char dest[50];
puts(“source string is”);
puts(scr);
strcpy(dest,src);
puts(“Destination string is”);
puts(dest);
getch();
}
iii)strcat function
The strcat function concatenates one string with another
syntax
strcat(string1,string2);
string 1 and string2 are character arrays or string constants.When the function strcat is executed, string2 is appended
to string1 by removing the null character at the end of string1 and string2.
//Program to concate the second string at the end of the first string
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() Output
{ The strings are:
char dest[50]=“Hello”; Hello
char scr[50]=“Readers”; Readers
puts(“The strings are:”); After concatenation
puts(dest); HelloReaders
puts(src);
strcat(dest,src);
puts(“Afterc concatenation”);
puts(dest);
getch();
}
iv)strrev function
The strrev function reverses all the characters of string except
the terminating null characters.
Syntax
strrev(string);
//Program to display a reverse of the given string
#include<stdio.h>
#include<conio.h>
#include<string.h> Output
void main() Enter the String:
Computer
char str[20];
Afterreversal,the string is,
puts(“enter the string:”); retupmoc
gets(str);
strrev(str);
puts(“After reversal,the string is:”);
puts(str);
getch();
}
v)strcmp function
The strcmp function compares the two strings character by character using their ASCII values,and returns
any one of the following integer values.
We can use strcmp() instead of stricmp().The only difference is that the former function discrimates
between small and capital letters whereas does not.
Syntax
strcmp(string1,string2);
Return value Implication Example
ASCII value of the character of the
first string is less then the ASCII
Less than 0 i=strcmp(“XYZ”,”xyz”)
value of the corresponding character
of the second string
ASCII value of the character of the
first string is greater than the ASCII i=strcmp(“xyz”,”XYZ”)
Greater than 0
value of the corresponding character
of the second string.
i=strcmp(“XYZ”,”XYZ”)
Equal to 0 If the strings are identical
//Program for strcmp()
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[20];
char str2[20];
int result;
strcpy(str1, "hello");
strcpy(str2, "hEllo");
result = strcmp(str1, str2);
if(result > 0)
{
printf("ASCII value of first unmatched character of str1 is greater than str2");
}
else if(result < 0)
{
printf("ASCII value of first unmatched character of str1 is less than str2");
}
else
{
printf("Both the strings str1 and str2 are equal");
}
return 0;
}
Output
ASCII value of first unmatched character of str1 is greater than str2
vi)strlwr function
The strlwr function converts all the letters in a string to lowercase.When we are passing any upper case
string to this function it converts it into lowercase.
Syntax
strlwr(string);
#include<stdio.h>
#include<conio.h>
#include<string.h> Output
void main() Enter the string
HELLO
{
Lowercase string is
char str[20]; hello
puts(“enter the string”);
gets(str);
strlwr(str);
puts(“lower case string is”);
puts(str);
getch();
}
vii)strupr function
The strupr function converts all the letters in a string to uppercase.
Syntax
strupr(string);

#include<stdio.h>
#include<conio.h>
#include<string.h>
Output
void main() Enter the string
{ water
charstr[20]; Upper case string
puts(“Enter the string”); WATER
gets(str);
strupr(str);
puts(“Upper case sting”);
puts(str);
getch();
}
UNIT-III ARRAYS AND FUNCTIONS Periods: 09

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations- Function – definition
of function – Declaration of function – Pass by value – Pass by reference
– Recursion
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
Sorting
Sorting is the process of arranging elements in the list according to their values, in
ascending or descending order.
(or)
Sorting refers to ordering data in an ascending or descending fashion according to
some linear relationship among the data items. Sorting can be done on names,
numbers and records.
A sorted list is called an ordered list. Sorted list is important in list searching
because it facilitates rapid search operations.
Bubble sort - What is Bubble Sort?
Bubble sort is a simple sorting algorithm that works by comparing the adjacent elements in the list and swapping them if the
elements are not in the specified order. It is an in-place and stable sorting algorithm that can sort items in data structures such
as arrays and linked lists.
Bubble sort requires n-1 passes, where n is the number of input items. The bubble sort gets its name because elements tends to
move up to the correct order like bubbles rising to the surface. The diagrammatic representation is as follows.

How does Bubble Sort Work? Input: arr[] = {6, 3, 0, 5}


Insertion sort is an algorithm used to sort a collection of
elements in ascending or descending order. The basic
idea behind the algorithm is to divide the list into two
parts: a sorted part and an unsorted part.

Initially, the sorted part contains only the first element of


the list, while the rest of the list is in the unsorted part.
The algorithm then iterates through each element in the
unsorted part, picking one at a time, and inserts it into its
correct position in the sorted part.

To do this, the algorithm compares the current element


with each element in the sorted part, starting from the
rightmost element. It continues to move to the left until it
finds an element that is smaller (if sorting in ascending
order) or larger (if sorting in descending order) than the
current element.

Once the correct position has been found, the algorithm


shifts all the elements to the right of that position to make
room for the current element, and then inserts the current
element into its correct position.
Insertion Sort Algorithm

we can derive simple steps by which we can achieve insertion sort.

Step 1 − If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater
than the value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to
the selection sort where we first find the minimum element and place the minimum element at the beginning.
Repeat the same process for the remaining elements.
SEARCHING :
It check for an element or retrieve an element from any data structure where the data is stored. Based on the type of search
operation, there are generally two algorithms defined in C:
 Linear Search or Sequential Search
 Binary Search
Linear Search or Sequential Search - Find whether a value is exist in a given array. If it is exist then return the current
position. In this algorithm we check the value one by one in given list.
Binary Search - Search in the given sorted elements. In this algorithm we divide sorted elements frommiddle and check
the lie between which part. Same process we try until the all element not read.

How Does Linear Search Algorithm Work?

In Linear Search Algorithm,

•Every element is considered as a potential match for the key and checked for the same.

•If any element is found equal to the key, the search is successful and the index of that element is returned.

•If no element is found equal to the key, the search yields “No match found”.
Linear search Algorithm For example: Consider the array arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30

Step 1: Start from the first element (index 0) and compare key with each element (arr[i]).
•Comparing key with first element arr[0]. SInce not equal, the iterator moves to the next element as a potential
match.

Step 2: Now when comparing arr[2] with key, the value


matches. So the Linear Search Algorithm will yield a successful
message and return the index of the element when key is found
(here 2).
Binary Search is defined as
a searching algorithm used in a
sorted array by repeatedly dividing
the search interval in half. The idea
of binary search is to use the
information that the array is sorted
and reduce the time complexity to
O(log N).

•Divide the search space into two halves by finding the middle index “mid”.
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.

First Step: Calculate the mid and compare the mid element with the key. If the key is less than mid element,
move to left and if it is greater than the mid then move search space to the right.
•Key (i.e., 23) is greater than current mid element (i.e., 16). The search space moves to the right.

•Key is less than the current mid 56. The search space moves to the left.
Second Step: If the key matches the value of the mid element, the element is found and stop search.
// below we have a simple C program for bubble sort
int main()
#include <stdio.h>
{
void bubbleSort(int arr[], int n)
int arr[100], i, n, step, temp;
{
// ask user for number of elements to be sorted
int i, j, temp;
printf("Enter the number of elements to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &n);
{
// input elements if the array
for(j = 0; j < n-i-1; j++)
for(i = 0; i < n; i++)
{
{
if( arr[j] > arr[j+1])
printf("Enter element no. %d: ", i+1);
{
scanf("%d", &arr[i]);
// swap the elements
}
temp = arr[j];
// call the function bubbleSort
arr[j] = arr[j+1];
bubbleSort(arr, n);
arr[j+1] = temp;
return 0;
} }}
}
// print the sorted array
printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}}
// C program for insertion sort
#include <math.h> // A utility function to print
#include <stdio.h> // an array of size n
/* Function to sort an array using insertion sort*/ void printArray(int arr[], int n)
void insertionSort(int arr[], int n) {
{ int i;
int i, key, j; for (i = 0; i < n; i++)
for (i = 1; i < n; i++) printf("%d ", arr[i]);
{ printf("\n");
key = arr[i]; }
j = i - 1; // Driver code
/* Move elements of arr[0..i-1], that are int main()
greater than key, to one position ahead of their {
current position */ int arr[] = {12, 11, 13, 5, 6};
while (j >= 0 && arr[j] > key) int n = sizeof(arr) / sizeof(arr[0]);
{ insertionSort(arr, n);
arr[j + 1] = arr[j]; printArray(arr, n);
j = j - 1; return 0;
} }
arr[j + 1] = key;
}
}
// C Program for HeapSort
#include <stdio.h> // HeapSorting function // Driver code
void heapsort(int arr[], int n) int main()
// Heapify function {
{
void heapify(int arr[], int n, int i)
{ int i, temp; // initializing the array
int temp, maximum, left_index, right_index; int arr[] = { 20, 18, 5, 15, 3, 2 };
// performing heapify on the non leaf nodes so n/2 - 1 int n = 6;
// currently assuming i postion to // to 0 are the non leaf nodes
// be holding the largest value for (i = n / 2 - 1; i >= 0; i--) {
maximum = i;
heapify(arr, n, i); // Displaying original array
} printf("Original Array : ");
// right child index
right_index = 2 * i + 2; // the current array is changed to max heap for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
// left child index for (i = n - 1; i > 0; i--) { }
left_index = 2 * i + 1; temp = arr[0];
arr[0] = arr[i];
// if left index value is grater than the current index printf("\n");
// value arr[i] = temp;
heapify(arr, i, 0); heapsort(arr, n);
if (left_index < n && arr[left_index] > arr[maximum])
maximum = left_index; }
} // Displaying sorted array
// if right index value is grater than the current index printf("Array after performing heap sort: ");
// value
if (right_index < n && arr[right_index] > arr[maximum]) for (int i = 0; i < n; i++) {
maximum = right_index; printf("%d ", arr[i]);
}
// checking if we needed swaping the elements or not
if (maximum != i) { return 0;
temp = arr[i]; }
arr[i] = arr[maximum];
arr[maximum] = temp;
heapify(arr, n, maximum);
}
}
// C code to linearly search x in arr[].
#include <stdio.h>
int search(int arr[], int N, int x)
{
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);

// Function call
int result = search(arr, N, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
// C program to implement recursive Binary Search
#include <stdio.h>
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
// Driver code
int main()
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
UNIT-III ARRAYS AND FUNCTIONS Periods: 09

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations- Function – definition
of function – Declaration of function – Pass by value – Pass by reference
– Recursion
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
Different Operations on Matrices
The addition of two matrices A m*n and Bm*n gives a matrix Cm*n. The elements of C are the sum of corresponding
elements in A and B which can be shown as:

Key points:
•The addition of matrices is commutative, which means A+B =
B+A
• The addition of matrices is associative, which
means A+(B+C) = (A+B)+C
•The order of matrices A, B, and A+B is always the same
•If the order of A and B are different, A+B can’t be computed
•The complexity of the addition operation
is O(M*N) where M*N is the order of matrices
Matrices Subtraction:
The subtraction of two matrices Am*n and Bm*n give a matrix Cm*n. The elements of C are difference of corresponding
elements in A and B which can be represented as:

Key points:
•Subtraction of matrices is non-commutative which means A-B ≠ B-A
•Subtraction of matrices is non-associative which means A-(B-C) ≠ (A-B)-C
•The order of matrices A, B, and A – B is always the same
•If the order of A and B are different, A – B can’t be computed
•The complexity of subtraction operation is O(M*N) where M*N is the order of
matrices
Matrices Multiplication:
The multiplication of two matrices Am*n and Bn*p give a matrix Cm*p. It means a number of columns in A must be equal to the
number of rows in B to calculate C=A*B. To calculate element c11, multiply elements of 1st row of A with 1st column of B and
add them (5*1+6*4) which can be shown as:

Key points:
•Multiplication of matrices is non-commutative which means A*B ≠ B*A
•Multiplication of matrices is associative which means A*(B*C) = (A*B)*C
•For computing A*B, the number of columns in A must be equal to the number of rows in B
•The existence of A*B does not imply the existence of B*A
•The complexity of multiplication operation (A*B) is O(m*n*p) where m*n and n*p are the order
of A and B respectively
•The order of matrix C computed as A*B is m*p where m*n and n*p are the order of A and B respectively
The transpose of a matrix is a new matrix formed by interchanging its rows with columns. In simple words, the
transpose of A[][] is obtained by changing A[i][j] to A[j][i].
// add the matrices
ADDITION OF TWO MATRIX
for (i = 0; i < m; i++) {
#include <stdio.h> for (j = 0; j < n; j++) {
int main() { c[i][j] = a[i][j] + b[i][j];
int m, n, i, j; }
printf("Enter the number of rows and columns of the matrices: "); }
scanf("%d%d", &m, &n); // print the result
int a[m][n], b[m][n], c[m][n]; printf("The sum of the two matrices is: \n");
printf("Enter the elements of matrix A: \n"); for (i = 0; i < m; i++) {
for (i = 0; i < m; i++) { for (j = 0; j < n; j++) {
for (j = 0; j < n; j++) { printf("%d ", c[i][j]);
scanf("%d", &a[i][j]); }
} printf("\n");
} }
printf("Enter the elements of matrix B: \n"); return 0;
for (i = 0; i < m; i++) { }
for (j = 0; j < n; j++) { OUTPUT
scanf("%d", &b[i][j]); Enter the number of rows and columns of the matrices: 2 2
Enter the elements of matrix A:
} 12
} 34
Enter the elements of matrix B:
56
78
The sum of the two matrices is:
68
10 12
SUBRACTION OF TWO MATRIX

#include<stdio.h>
#include<conio.h> for(i=0; i<3; i++)
int main() {
{ for(j=0; j<3; j++)
int mat1[3][3], mat2[3][3], matSub[3][3], i, j; matSub[i][j] = mat1[i][j] - mat2[i][j];
printf("Enter First 3*3 Matrix Elements: "); }
for(i=0; i<3; i++) printf("\nThe Subtraction Result is:\n");
{ for(i=0; i<3; i++)
for(j=0; j<3; j++) {
scanf("%d", &mat1[i][j]); for(j=0; j<3; j++)
} printf("%d ", matSub[i][j]);
printf("Enter Second 3*3 Matrix Elements: "); printf("\n");
for(i=0; i<3; i++) }
{ getch();
for(j=0; j<3; j++) return 0;
scanf("%d", &mat2[i][j]); }
}
TRANSPOSE OF A GIVEN MATRIX
// computing the transpose
#include <stdio.h> for (int i = 0; i < r; ++i)
int main() { for (int j = 0; j < c; ++j) {
int a[10][10], transpose[10][10], r, c; transpose[j][i] = a[i][j];
printf("Enter rows and columns: "); }
scanf("%d %d", &r, &c);
// printing the transpose
// asssigning elements to the matrix printf("\nTranspose of the matrix:\n");
printf("\nEnter matrix elements:\n"); for (int i = 0; i < c; ++i)
for (int i = 0; i < r; ++i) for (int j = 0; j < r; ++j) {
for (int j = 0; j < c; ++j) { printf("%d ", transpose[i][j]);
printf("Enter element a%d%d: ", i + 1, j + 1); if (j == r - 1)
scanf("%d", &a[i][j]); printf("\n");
} }
return 0;
// printing the matrix a[][] }
printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}
UNIT-III ARRAYS AND FUNCTIONS Periods: 09

Arrays – Initialization – Declaration – One dimensional and Two


dimensional arrays. String- String operations – String Arrays. Simple
programs- sorting- searching – matrix operations- Function – definition
of function – Declaration of function – Pass by value – Pass by
reference – Recursion
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books

1. Vikas B. Agarwal Jyoti P. Mirani, ―Computer Fundamentals , Nirali Prakashan Aug-2019,


2. Ashok N Kamthane, ―Computer Programming‖, Pearson education, Second Impression,2012.
3. VikasVerma, ―A Workbook on C ―, Cengage Learning, Second Edition,2012.
4. P.Visu, R.Srinivasan and S.Koteeswaran, ―Fundamentals of Computing and Programming‖, Fourth Edition, Sri
Krishna Publications, 2012.
5. PradipDev, ManasGhoush, ―Programming in C‖, Second Edition, Oxford University Press, 2011.
A function in C is a set of statements that when called perform some specific task. It is the basic building block of a C
program that provides modularity and code reusability. The programming statements of a function are enclosed within { }
braces, having certain meanings and performing certain operations. They are also called subroutines or procedures in
other languages.

In this article, we will learn about functions, function definition. declaration, arguments and parameters, return values, and
many more.

Syntax of Functions in C
The syntax of function can be divided into 3 aspects:

Function Declaration
Function Definition
Function Calls
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);
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
}
Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a function body. Here are all the parts of a
function −
 Return Type − A function may return a value. The return_type is the data type of the value the function returns.
Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword
void.
 Function Name − This is the actual name of the function. The function name and the parameter list together
constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define whatthe function does.
Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value
between the two −

/* function returning the max between two numbers */


int max(int num1, int num2) {
/* local variable declaration */ int result;
if (num1 > num2) result = num1;
else
result = num2;
return result;
}

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.
} Calling a Function
#include <stdio.h>
/* function declaration */ While creating a C function, you give a definition
int max(int num1, int /* function returning the max between two
of what the function has to do. To use a function,
num2);int main () { numbers */ int max(int num1, int num2) {
you will have to call that function to perform the
/* local variable
definition */int a = /* local variable declaration defined task.
100; */ int result; When a program calls a function, the program
int b =
200;int control is transferred to the called function. A
if (num1 > num2)
ret; called function performs a defined task and when
result = num1;
else its return statement is executed or when its
/* calling a function to get result = num2; function- ending closing brace is reached, it
max value */ret = max(a, b);
printf( "Max value is : returns the program control back to the main
return result;
%d\n", ret );return 0; } 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. For example −
Sr.No. Call Type & Description

1 Call by value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.

2 Call by reference
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made to
the parameter affect the argument.
PASS BY VALUE /*
* C program to demonstrate pass by Value.
Pass by value is a way to pass a variable to a */
function. The variable is passed by value, not by #include <stdio.h> void swap
reference. This means that the function does not have (int a, int b)
access to the variable’s memory address. The function {
can only access the variable’s value. int temp = a;a = b;
b = temp;
In the case of pass by value, the space allocated }
for the variable is copied to the function’s memory int main ()
space. This means that the function can modify the {

variable’s value without affecting the variable’s int a = 10;int b = 20;


memory address. printf ("Before swap, a = %d, b = %d\n", a, b);
swap (a, b);
printf ("After swap, a = %d, b = %d\n", a, b);
return 0;
}
Program Output
Before swap, a = 10, b = 20After
swap, a = 20, b = 10
PASS BY REFERENCE /** C Program to Illustrate Pass by Reference by Swapping Numbers*/
#include <stdio.h>
In pass by reference, we pass the void swap(int *a,int *b)
address of the variable instead of passing the { //*(asterix) is used to de-reference the variable
int temp=*a;
value of the variable and access the variable
*a=*b;
using the pointers in the Function. All the *b=temp;
changes made to variable in the function will }
be reflected in the main Program int main()
{
int a,b;
printf("Enter two numbers:"); scanf("%d
%d",&a,&b);
printf("Numbers Before Swapping: %d and %d\n",a,b);
//Calling swap function by passing address
swap(&a,&b);
printf("Numbers After Swapping: %d and %d",a,b);return 0;
}

Program Output
Enter two numbers: 1 2
Numbers Before Swapping: 1 and 2
Numbers After Swapping: 2 and 1
RECURSIVE FUNCTION
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows
you to call a function inside the same function, then it is called a recursive call of the function.

void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need
to be careful to define an exit condition from the function; otherwiseit will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.
#include <stdio.h>
unsigned long long int
factorial(unsigned int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1); When the above code is compiled and executed, it produces the following
}
result −Factorial of 12 is 479001600
int
mai
n()
{int
i=
12;
printf("Factorial of %d is
%d\n", i, factorial(i));return 0;
}

You might also like