UNIT 3 Notes
UNIT 3 Notes
Contents
Arrays: Introduction – One dimensional Array – Two dimensional arrays –
Multidimensional arrays. Strings: Operations of Strings.
Functions – Definition of function – Declaration of Function – Function Prototype – Types
of Functions – Pass by value – Pass by reference – recursion – Programming Examples.
ARRAYS
Introduction:
If we need to store multiple copies of the same data then it is very difficult for the user. To
overcome the difficulty a new data structure is used called arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.
An array can be declared of any standard or custom data type.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100
variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C
programming arrays is introduced in C which gives the capability to store the 100 roll numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Programming Arrays
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
1. Individual data items can be accessed by the name of the array and an integer enclosed in
square bracket called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguous
memory.
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special
purposes then we can say that these 200 blocks are going to reserve contiguous memory.
1. Two registers are used while implementing the contiguous memory scheme. These
registers are base register and limit register.
2. When OS is executing a process inside the main memory then content of each register are
as
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address
from base register and then it will refer relative address of memory location with respect to
base address.
Array Terminologies:
Characteristics of an array:
1. The declaration int a [5] is nothing but creation of five variables of integer types
in memory instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or
array variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
Array has to be declared before using it in C Program. Array is nothing but the collection of
elements of similar data types.
Requirement Explanation
Data Type specifies the type of the array. We can compute the size
Data Type required for storing the single cell of array.
3. Number of Dimension
Types of Array
1. Single or One Dimensional array is used to represent and store data in a linear form.
Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set
of values to array element before executing program. i.e. at compilation time.
Here we are learning the different ways of compile time initialization of an array.
As at the time of compilation all the elements are at specified position So This initialization
scheme is Called as “Compile Time Initialization“.
Graphical Representation
In this scheme of compile time Initialization, We do not provide size to an array but instead we
provide set of values to the array.
Explanation:
1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines
the Size of An Array.
2. After counting the number of elements inside the braces, The size of array is considered
as 5 during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time Initialization“
Example Program
#include <stdio.h>
int main()
int num[] = {2,8,7,6,0};
int i;
for (i=0;i<5;i++) {
return 0;
Output:
Array Element num[0] = 2
Array Element num[1] = 8
Array Element num[2] = 7
Array Element num[3] = 6
Array Element num[4] = 0
4. Merging – The elements of two arrays are merged into a single one.
#include<stdio.h>
#include<stdlib.h>
#define size 10 int
main()
{
int a[3] = { 11, 22, 33 };
Output:
a[0],value=11 : address=2358832
a[1],value=22 : address=2358836
a[2],value=33 : address=2358840
#include<stdio.h>
int main()
{
int i, arr[50], num;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Reading values into Array printf("\
nEnter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
//Printing of all elements of array
for (i = 0; i < num; i++) ]
{
printf("\narr[%d] = %d", i, arr[i]);
}
return (0);
}
Output:
Enter no of elements : 5
#include<stdio.h>
int main()
{
int i, arr[50], sum, num;
printf("\n Enter no of elements :");
scanf("%d", &num);
//Reading values into Array printf("\
nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
//Computation of total
sum = 0;
Output:
Enter no of elements : 3
a[0]=11
a[1]=22
a[2]=33
Sum=66
#include<stdio.h>
int main()
{
int a[30], i, num, smallest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as smallest
smallest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] < smallest)
{ smallest = a[i];
}
}
// Print out the Result
Output:
Enter no of elements : 5 11 44 22 55 99
Smallest Element : 11
#include<stdio.h>
int main()
{
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as largest
largest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] > largest)
{
largest = a[i];
}
}
// Print out the Result
Output:
Enter no of elements : 5 11 55
33 77 22
Largest Element : 77
1. Array having more than one subscript variable is called Multi-Dimensional array.
5, 6, 7
8, 9, 0
};
In the above example we are declaring 2D array which has 2 dimensions. First dimension will
refer the row and 2nd dimension will refer the column.
1 integer roll 1 10
int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++)
{
printf("%d",a[i][j]);
}
3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.
4. Name of 2-D array is „a„ and each block is identified by the row & column number.
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
Memory Representation:
3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.
4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of
a[0][0] 4000
a[0][1] 4002
a[0][2] 4004
a[1][0] 4006
a[1][1] 4008
a[1][2] 4010
a[2][0] 4012
a[2][1] 4014
a[2][2] 4016
Initializing 2D Array
For initializing 2D Array we need to assign values to each element of an array using the below
syntax.
int a[3][2] = { {1, 4}, {5, 2}, {6, 5} };
Example Program
#include<stdio.h>
int main()
{
int i, j;
int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };
printf("\n");
}
return 0;
Output:
1 4
5 2
6 5
Row 3: {6, 5}
Initialize all Array elements but initialization is much straight forward. All values are assigned
sequentially and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Example Program:
#include <stdio.h>
int main()
{
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
}
return 0;
Output:
1 4
5 2
6 5
#include<stdio.h>
int main()
{
int i, j,
mat1[10][10],
mat2[10][10],
mat3[10][10];
int row1, col1, row2, col2;
printf("\nEnter the number of Rows of Mat1 : ");
scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);
printf("\nEnter the number of Rows of Mat2 : ");
scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);
/* before accepting the Elements Check if no of rows and columns of both matrices is equal
*/
if (row1 != row2 || col1 != col2)
{ printf("\nOrder of two matrices is not same "); exit(0); }
scanf("%d", &mat2[i][j]);
{
for (j = 0; j < col1; j++)
{
printf("%d\t", mat3[i][j]);
}
printf("\n"); }
return (0);
}
Output:
246
422
242
2. C Program to Multiply two 3 X 3 Matrices
#include<stdio.h>
int main()
{
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;
printf("\nEnter First Matrix : "); for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter Second Matrix :");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The First Matrix is : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf(" %d ", b[i][j]);
}
printf("\n");
}
//Multiplication Logic
sum = 0;
for (k = 0; k <= 2; k++)
{
c[i][j] = sum;
}
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{ printf(" %d ", c[i][j]); }
printf("\n"); }
return (0);
Output:
2 2 2
2 2 2
2 2 2
The First Matrix is :
1 1 1
1 1 1
1 1 1
The Second Matrix is :
2 2 2
2 2 2
2 2 2
6 6 6
6 6 6
6 6 6
Limitations of Arrays
Array is very useful which stores multiple data under single name with same data type.
Following are some listed limitations of Array in C Programming.
A. Static Data
1. Elements belonging to different data types cannot be stored in array because array data
structure can hold data belonging to same data type.
2. Example : Character and Integer values can be stored inside separate array but cannot
be stored in single array
C. Inserting data in an array is difficult
1. Inserting element is very difficult because before inserting element in an array we have
to create empty space by shifting other elements one position ahead.
2. This operation is faster if the array size is smaller, but same operation will be more and
more time consuming and non-efficient in case of array with large size.
D. Deletion Operation is difficult
1. Deletion is not easy because the elements are stored in contiguous memory location.
2. Like insertion operation , we have to delete element from the array and after deletion
empty space will be created and thus we need to fill the space by moving elements up in
the array.
E. Bound Checking
1. If we specify the size of array as „N‟ then we can access elements up to „N-1‟ but in C if
we try to access elements after „N-1‟ i.e. Nth element or N+1th element then we does not
get any error message.
2. Process of checking the extreme limit of array is called Bound Checking and C does not
perform Bound Checking.
3. If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory
1. Array is Static data structure. Memory can be allocated at compile time only Thus if after
executing program we need more space for storing additional information then we cannot
allocate additional space at run time.
2. Shortage of Memory , if we don‟t know the size of memory in advance
G. Wastage of Memory
Applications of Arrays
Array is used for different verities of applications. Array is used to store the data or values
of same data type. Below are the some of the applications of array –
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.
B. Array Used for maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need
to declare following –
int roll1, roll2, roll3, roll4, roll5;
1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
3. Maintaining all the variables and remembering all these things is very difficult.
Consider the Array int roll[5]; Here we are using array which can store multiple values and we
have to remember just single variable name.
C. Array can be used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
Different Sorting Techniques are:
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Bucket Sort
Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
Matrix can be multi dimensional.
E. Array can be used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented using
the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more
about Round Robin Scheduling Algorithm | Video Animation]
F. Array can be used in Recursive Function
When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back. This is
similar operation like stack.
So any changes made inside function do not affect the original value.
STRINGS
String is a sequence of character enclosed with in double quotes (“ ”) but ends with \0.
The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
Syntax
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Output:
Enter String
Welcome
Given String Length Is:7
The strcat() is used to concatenate two strings. The second string will be appended to
the end of the first string. This process is called concatenation.
Syntax
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Output:
strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until
there is a mismatch or end of one of the strings is reached (whichever occurs first). If the two
strings are identical, strcmp( ) returns a value zero. If they‟re not, it returns the numeric
difference between the ASCII values of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20]; int res;
clrscr();
Output:
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Output:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
Output:
Enter String
WELCOME
Lowercase String : welcome
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
Output:
Enter String
WELCOME
Reverse String : emoclew
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
Output:
Enter String welcome
Uppercase String : WELCOME
FUNCTIONS IN C
1. Library functions
2. User-defined functions
Library functions are those functions which are already defined in C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are defined by the user
at the time of writing program. These functions are made for code reusability and for saving
time and space.
Benefits of Using Functions
2. It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
3. In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
4. It makes the program more readable and easy to understand.
Function Declaration
Like any variable or an array, a function must also be declared before its used.
Function declaration informs the compiler about the function name, parameters is accept,
and its return type.
The actual body of the function can be defined separately. It's also called as Function
Prototyping.
i. returntype
When a function is declared to perform some sort of calculation or any operation and is expected
to provide with some result at the end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.
Note: In case your function doesn't return any value, the return type would be void.
2. functionName
Function name is an identifier and it specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same naming rules like other variables in C
language.
3. parameter list
The parameter list declares the type and number of arguments that the function expects when it
is called. Also, the parameters in the parameter list receives the argument values when the
function is called. They are often referred as formal parameters.
The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function
header and the statement(s) within curly braces is called function body
functionbody
The function body contains the declarations and the statements(algorithm) necessary for
performing the required task. The body is enclosed within curly braces { ... } and consists of
three parts.
a return statement to return the result evaluated by the function(if return type
is void, then no return statement is required).
Calling a function
When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
Int main()
{
// function
greatNum();
call
return0;
}
#include<stdio.h>
intgreatNum(); // function
declaration
int main()
{
int result;
result = greatNum(); // function
callis: %d",
printf("The greater number
result);
return0;
}
#include<stdio.h>
intmain()
{
inti, j;
#include<stdio.h>
Recursion cannot be applied to all the problem, but it is more useful for
the tasks that can be defined in terms of similar subtasks.
void recursion() {
recursion(); /* function calls itself */
}
int main()
{ recurs
ionn();
}