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

Module 4

This document provides an overview of arrays and strings in C programming, detailing their types, properties, advantages, and disadvantages. It explains the declaration, initialization, and accessing of one-dimensional and two-dimensional arrays, along with examples of operations such as traversal, updating, and matrix multiplication. Additionally, it covers the concept of strings as arrays of characters, including their declaration and initialization methods.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 4

This document provides an overview of arrays and strings in C programming, detailing their types, properties, advantages, and disadvantages. It explains the declaration, initialization, and accessing of one-dimensional and two-dimensional arrays, along with examples of operations such as traversal, updating, and matrix multiplication. Additionally, it covers the concept of strings as arrays of characters, including their declaration and initialization methods.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

‘C’ Programming

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.

● An array in C is a fixed-size collection of similar data items stored in contiguous


memory locations.

● 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.

● C array is beneficial if you have to store similar elements. For example, if we


want to store the marks of a student in 6 subjects, then we don't need to define
different variables for the marks in the different subject.

● 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

1) Code Optimization: Less code to the access the data.

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.

Syntax for Declaration of Single Dimensional Array:

data_type : is a type of data of each array


block.
array_name : is the name of the array
using which we can refer to it.
array_size : is the number of blocks of
memory array going to have.
Important Point: What if we provide fewer elements than the size of the array?
In this scenario, the rest of the memory block will be filled with the default value, which is null
for string array, 0 for integer array, etc. See the example below for further illustration.
Output :

78000
Initialisation of Single Dimensional Array:

We can initialize an array by providing a list of elements separated by commas and


enclosed by curly braces.
data_type array_name[array_size] = {element1, element2, element3, ......... , elementN};

//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:

int <array name>[size] = {0};


Array Accessing

In one-dimensional arrays in C, elements are accessed by specifying the array name and
the index value within the square brackets.

Array indexing starts from 0 and ends with size-1.

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];

C Program to Enter 5 Numbers and Print them in Reverse Order.


Note :
Output :

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.

Inside the loop, we have only one


statement, and we are printing the
element at i th index.
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array traversal, we use loops
to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++) {
array_name[i];
}
Update Array Element
We can update the value of an element at the given index i in a
similar way to accessing an element by using the array subscript
operator [ ] and assignment operator =.
array_name[i] = new_value;
● Array is a collection of more than one data item of same
type.
● All the data items are stored in Contiguous memory
locations.
● Number of data items array holds is size of array
● Once size has declared, it can't be changed at runtime
(fixed size)
● Index starts from o known as derived data type.
● Accessing of any element is faster using Index of array .
● It allows to store data in multidimensional form.
● Inserting & deleting elements from array is costly
● No bound checking in C
Initialisation
is different
here
Output
Elements in Array: 10 20 100 40 50
Find largest and second largest elements from integer Array (Without sorting Method)
With Sorting
Find largest and second largest
elements from integer Array (With
sorting Method)
Array of Characters (Strings)

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];

Two dimensional array:


int two_d[10][20];
The array int x[10][20] can store total (10*20) = 200 elements.
A two-dimensional array or 2D 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).
Declaration of Two-Dimensional Array in C

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

The various ways in which a 2D array can be initialized are as follows:


1. Using Initializer List
2. Using Loops

1. Initialization of 2D array using Initializer List


We can initialize a 2D array in C by using an initializer list as shown in the example below.
First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
The above array has 3 rows and 4 columns. The elements in the braces from left to right are
stored in the table also from left to right. The elements will be filled in the array in order: the
first 4 elements from the left will be filled in the first row, the next 4 elements in the second
row, and so on.
Second Method (better):
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
This type of initialization makes use of nested braces. Each set of inner braces represents one row.
In the above example, there is a total of three rows so there are three sets of inner braces. The
advantage of this method is that it is easier to understand.
Note: The number of elements in initializer list should always be less than or equal to the
total number of elements in the array.
2. Initialization of 2D array using Loops
We can use any C loop to initialize each member of a 2D array one by one as shown in the
below example.
Example:
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
scanf (”%d”&x[i][j]) ; }}
Accessing Elements 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");
} }

printf("Enter rows and columns for second matrix:\n");


scanf("%d %d",&p,&q);
printf("\nSecond matrix is:\n"); for(k=0;k<n;k++)
for(i=0;i<p;i++) {
{ sum=sum+(a[i][k]*b[k][j]);
for(j=0;j<q;j++) }
{ c[i][j]=sum;
printf("%d\t",b[i][j]); }
} }
printf("\n"); printf("\nMultiplication matrix is:\n");
} for(i=0;i<m;i++)
{
if(n!=p) for(j=0;j<q;j++)
{ {
printf("Cannot multiply\n"); printf("%d\t",c[i][j]);
} }
else printf("\n");
{ }
for(i=0;i<m;i++) }
{ return 0;
for(j=0;j<q;j++) }
{
sum=0;
String Character
● It is a 1D array of characters ● It is a single letter
terminated with a null character. ,number,punctuation mark or
symbol that can be represented in
● String is a set of characters a computer.
Docker,program, Neeti Panigrahi, subject A, g.y,1,7,!,&,#

● Double quotation mark is used to ● Character is a single element.


represent the string.
● Single quotation is used to
String str=”Neeti”; represent the character.
Char str [7]=[‘c’,‘o’,‘d’,‘i’,‘n’,‘g’,‘\0’]; char ch=’123’
Char ch=’a’;
● Multiple letters on digit can be enclosed
in the double quotation marks ● In characters only one digit or
letter can be enclosed in single
quotation.
String
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];

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 initialize a C string in 4 different ways which are as follows:

1. Assigning a String Literal without Size


String literals can be assigned without size. Here, the name of the string str acts as a pointer
because it is an array.

char str[ ] = "Somaiya";

2. Assigning a String Literal with a Predefined Size


String literals can be assigned with a predefined size. But we should always account for one
extra space which will be assigned to the null character. If we want to store a string of size n
then we should always declare a string with a size equal to or greater than n+1.

char str[50] = "Somaiya";


3. Assigning Character by Character with Size

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.

char str[14] = {‘S’,’o’,’m’,’a’,’i’,’y’,’a’’,\0'};

4. Assigning Character by Character without Size


We can assign character by character without size with the NULL character at the end.
The size of the string is determined by the compiler automatically.

char str[ ] = { ‘S’,’o’,’m’,’a’,’i’,’y’,’a’’,\0'};

Note: When a Sequence of characters enclosed in the double quotation marks is


encountered by the compiler, a null character ‘\0’ is appended at the end of the string by
default.
Format specifier for String is %s
The strlen() function takes a
string as an argument and
returns its length. The returned
value is of type size_t (an unsigned
integer type).

It is defined in the <string.h>


header file.

Note: The C language does not


provide an inbuilt data type for
strings but it has an access
specifier “%s” which can be used
to print and read strings directly.
Read a String Input From the User

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.

As str[ ] is a character array so using str


without braces ‘[‘ and ‘]’ will give the
base address of this string.

That’s why we have not used ‘&’ in this


case as we are already providing the
base address of the string to scanf.
Input : Somaiya for Students
output : Somaiya

Here, the string is read only


till the whitespace is
encountered.

Note: After declaration, if we


want to assign some other
text to the string, we have to
assign it one by one or use
the built-in strcpy() function
because the direct
assignment of the string
literal to character array is
only possible in declaration.
How to Read a String Separated by Whitespaces in C?
We can use multiple methods to read a string separated by spaces in C. The two of the common ones are:

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.

1. Example of String Input using gets()

warning: the `gets' function is dangerous and should


not be used.

Enter a string: Somaiya for Students


Somaiya for Students
Drawback of Scanf() and gets() …. Buffer Overflow

warning: the `gets' function is


dangerous and should not be used.

Enter a string: Somaiya For Students


Somaiya For Students
fgets():

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.

Using fgets() is safer compared to


gets() because it allows you to
specify the maximum number of
characters to read, thus preventing
buffer overflow vulnerabilities.
Additionally, it handles whitespace
characters properly.
2. Example of String Input using scanset

Input :
Somaiya for Students

output :
Somaiya for Students
C String Length

The length of the string is the number of characters present


in the string except for the NULL character.
We can easily find the length of the string
using the loop to count the characters from the start till the NULL
character is found.

Passing Strings to Function

As strings are character arrays, we can pass


strings to functions in the same way we pass
an array to a function. Below is a sample program
to do this:
String is :
Somaiyaforstudents
Note: We can’t read a string value
with spaces, we can use either
gets() or fgets() in the C
programming language.
Strings and Pointers

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

String Manipulations In C Programming Using Library


Functions

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

int strlen(string name);

Parameters

str: It represents the string variable whose length we have to find.

Return Value

strlen() function in C returns the length of the string.


The strlen() function takes a
string as an argument and
returns its length.

The returned value is of type size_t


(an unsigned integer type).

It is defined in the <string.h>


header file.
we used sizeof to get the size of a string/array.

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

char strcpy(destination, source);

Parameters

destination: Points to the destination array where the content is to be copied.


source: string which will be copied.

Return Value

strcpy() function returns a pointer pointing to the output string.


strcpy() can read and copy whitespaces just like any other character. It copies
characters from the source string until it encounters a null terminator ('\0') indicating
the end of the string. Whitespace characters like space (' '), tab ('\t'), newline ('\n'), etc.,
are treated just like any other character and are copied by strcpy().

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.

Disadvantages of using string functions in C:


String functions in C can be limited in functionality.
String functions in C may not be optimal for specific use cases.
String functions in C may introduce security problems if used incorrectly.
String functions in C can be memory-intensive for large strings.
String functions in C may not be portable across different systems or architectures.

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.

You might also like