Module 4
Module 4
Module 4
By Asst. Prof. Sudeshna Baliarsingh
Information & Technology Dept.
KJSIT, Mumbai
● Arrays and Strings
● Introduction to Arrays
● Declaration and initialization of one
dimensional and two-dimensional arrays.
● Definition and initialization of String
● String functions
● Introduction to Arrays
● It is a simple and fast way of storing multiple values under a single name.
● It can be used to store the collection of primitive data types such as int, char,
float, etc., and also derived and user-defined data types such as pointers,
structures, etc.
● Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.
Properties of Array
The array contains the following properties.
1. Each element of an array is of same data type and carries the same size, i.e.
int = 4 bytes.
2. Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the
size of the data element.
Advantage of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList
Types of Arrays
Arrays in C are classified into three types:
● One-dimensional arrays
● Two-dimensional arrays
● Multi-dimensional arrays
Single Dimensional Array
The single-dimensional array is one of the most used types of the array in C. It is a linear
collection of similar types of data, and the allocated memory for all data blocks in the
single-dimensional array remains consecutive.
78000
Initialisation of Single Dimensional Array:
//Example
int evenNumbers[5] = {0, 2, 4, 6, 8};
We can skip the writing size of the array within square brackets if we initialize array elements
explicitly within the list at the time of declaration. In that case, it will pick elements list size as array
size.
Example:
int nums[5] = {0, 1, 2, 3, 4}; //array nums is initialized with elements 0,1,2,3,4
If we want to initialize all elements of an integer array to zero, we could simply write:
In one-dimensional arrays in C, elements are accessed by specifying the array name and
the index value within the square brackets.
If we try to access array elements out of the range, the compiler will not show any error
message; rather, it will return some garbage value.
Syntax:
<arr_name>[index];
Accessing Elements of Single Dimensional Array
We can access the element of the single-dimensional array by providing the index of the
element with the array name. The index of the array starts with zero.
arrayName[index];
6 10 1 8 7
The last index of an array
is:array length - 1. Beginners
make the mistake of considering the
last index as 5 if the array size is 5;
that's why it is an important point as a
takeaway.
In C, we store the words, i.e., a sequence of characters in the form of an array of characters terminated by a NULL
character. These are called strings in C language.
Output:
Program
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of
the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with
more dimensions than 3d arrays but they are avoided as they get very complex and occupy a
large amount of space.
A. Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions.
They can be visualized in the form of rows and columns organized in a two-dimensional
plane.
Syntax of 2D Array in C
array_name[size1] [size2];
The basic form of declaring a 2D array with x rows and y columns in C is shown below.
Syntax:
data_type array_name[x][y];
where,
● data_type: Type of data to be stored in each element.
● array_name: name of the array
● x: Number of rows.
● y: Number of columns.
We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20 columns as:
Example:
int x[10][20];
Initialization of Two-Dimensional Arrays in C
Elements in 2D arrays are accessed using row indexes and column indexes. Each element in
a 2D array can be referred to by:
Syntax:
array_name[i][j]
where,
● i: The row index.
● j: The column index.
Example:
int x[2][1];
The above example represents the element present in the third row and second column.
WAP to Print matrix and Calculate the Sum:
WAP to Print Transpose of the matrix:
Output:
Matrix is
123
456
Transpose of matrix
14
25
36
WAP to Print First and second matrix and save the sum in third matrix:
WAP to Print First and second matrix and save the sum in third matrix: Using Function
Herethe program adds two square matrices of size 4*4, we can change N for different dimensions.
Output:
Matrix A is
1111
2222
3333
4444
Matrix B is
1111
2222
3333
4444
Result matrix is
2222
4444
6666
8888
Matrix Multiplication in C
Example
Input:
Mat1[ ][ ] = {{1, 2}, Output:
{3, 4}} {{19, 22},
{43, 50}}
Mat2[ ][ ] = {{5, 6},
Multiplication of two matrices is done by multiplying
{7, 8}}
corresponding elements from the rows of the first
matrix with the corresponding elements from the
Multiplication of two matrices: columns of the second matrix and then adding these
{{1*5 + 2*7 1*6 + 2*8}, products.
{3*5 + 4*7 3*6 + 4*8}}
Note: The number of columns in the first matrix
must be equal to the number of rows in the
second matrix.
#include<stdio.h> printf("\nEnter second matrix: \n");
#define N 50 for(i=0;i<p;i++)
int main() {
{ for(j=0;j<q;j++)
int a[N][N], b[N][N], c[N][N]; {
int i,j,k, sum, m,n,p,q; scanf("%d",&b[i][j]);
}
printf("Enter rows and columns for first matrix:\n"); }
scanf("%d %d",&m,&n);
printf("\nFirst matrix is:\n");
printf("Enter first matrix:\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\t", a[i][j]);
scanf("%d", &a[i][j]); }
} printf("\n");
} }
char string_name[size];
In the above syntax string_name is any name given to the string variable and
size is used to define the length of the string, i.e the number of characters
strings will store.
There is an extra terminating character which is the Null character (‘\0’) used to
indicate the termination of a string that differs strings from normal character
arrays.
C String Initialization
A string in C can be initialized in different ways. We will explain this with the help of an
example. Below are the examples to declare a string with the name str and initialize it with
“Somaiya”.
We can also assign a string character by character. But we should remember to set the
end character as ‘\0’ which is a null character.
The following example demonstrates how to take string input using scanf() function in C
You can see in the above program that
Input : the string can also be read using a
single scanf statement. Also, you might
Somaiya
be thinking that why we have not used
the ‘&’ sign with the string name ‘str’ in
scanf statement!
output
We know that the ‘&’ sign is used to
: provide the address of the variable to
the scanf() function to store the value
Somaiya read in memory.
We can use the fgets() function to read a line of string and gets() to read characters from the standard input
(stdin) and store them as a C string until a newline character or the End-of-file (EOF) is reached.
We can also scanset characters inside the scanf() function.
However, if you are concerned about safety and potential buffer overflow issues, it's better
to use fgets(): fgets() reads input from the
standard input (stdin), which is
typically the keyboard.
It reads at most sizeof(input) - 1
characters from the user, leaving
room for the null terminator.
It stores the input in the character
array input.
The printf() statement then prints
out the input string.
Input :
Somaiya for Students
output :
Somaiya for Students
C String Length
Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements
of the string. We recommended you to check C Arrays and Pointers before you check this example.
Standard C Library – String.h Functions
OR
You need to often manipulate strings according to the need of a problem. Most, if not all,
of the time string manipulation can be done manually but, this makes programming
complex and large.
To solve this, C supports a large number of string handling functions in the standard
library "string.h".
Some String Functions in C
Here are some commonly used string functions in C:
Note:
Functions gets() and puts()
are two string functions to take
string input from the user and
display it respectively
strlen() Function
The strlen() function calculates the length of a given string. It doesn’t count the null
character ‘\0’.
Syntax
Parameters
Return Value
Note that sizeof and strlen behaves differently, as sizeof also includes the \0 character when counting:
Example
Note:
It is also important that you know that sizeof will always return the memory size (in bytes), and not the actual
string length
strcpy ()
The strcpy() is a standard library function in C and is used to copy one string to another. In C, it is present in
<string.h> header file.
Syntax
Parameters
Return Value
Output:
Concatenate Strings
strcat() is a function in C used to concatenate (i.e., append/combine) one string to the end of another. It takes
two arguments: the destination string and the source string.
It appends a copy of the source string to the end of the destination string, overwriting the null terminator of the
destination string, and then adds a new null terminator at the end of the concatenated string.
If the source string contains whitespaces, strcat() will copy those whitespaces to the destination string just like
any other character. However, it's important to note that strcat() does not print anything by itself. It only modifies
the contents of the destination string.
Illustration of strcat() : input with whitespace
Output
dest Before: This is an
dest After: This is an example
Write a C program to concatenate first, middle and last name using function.part 1
Write a C program to concatenate first, middle and last name using function.part 2
Advantages of using string functions in C:
String functions in C are efficient.
String functions in C are reusable.
String functions in C have a standardized interface and behaviour.
String functions in C are robust and handle edge cases and error conditions.
String functions in C prevent buffer overflows and other security problems.
Conclusion
In conclusion, String functions in C provide a convenient and efficient way to manipulate
strings. These functions, such as strlen(), strcpy(), strcat(), and strcmp(), allow for common
string operations like finding their length, copying them, concatenating them, and comparing
them. Careful use of these functions can lead to more robust and efficient programs.