Module 2
Arrays and Strings
GXEST 204 : Programming in C
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Module 2 Syllabus
Arrays. Single dimensional arrays. Defining an array. Array initialization.
Accessing array elements. Enumerated data type. Type definition. Two
dimensional arrays. Defining a two dimensional array. Programs for matrix
processing. Programs for sequential search. Bubble sort.
Strings. Declaring a string variable. Reading and displaying strings. String related
library functions. Programs for string matching.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Introduction to Arrays
An array is a collection of elements of the
same data type stored in contiguous memory
locations. Each element is accessed using an
index. Indexing in C starts from 0.
Array Representation
Example:
10 20 30 40 50
int a[5] = {10,20,30,40,50}; 0 1 2 3 4
printf("%d", a[2]);
Output: 30
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Defining an Array
An array must be defined before it is used in a program. The definition specifies
the data type and the number of elements.
General Syntax:
data type array name[size];
Example:
int a[5];
This statement defines an integer array named a that can store 5 elements.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Array Initialization
Array initialization assigns values to array elements at the time of declaration.
Syntax:
data type array name[size] = {value1, value2, ...};
Example:
int a[5] = {10, 20, 30, 40, 50};
Partial Initialization:
int b[5] = {1, 2};
Remaining elements are automatically initialized to zero.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Partial Initialization of Arrays
If fewer initializers are provided than the array size, the remaining elements are
automatically initialized to 0 for numeric types or null characters for character
types.
Example:
int values[10] = {1, 2, 3};
Elements values[3] to values[9] will be initialized to 0.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Implicit Size Initialization
If an array is initialized without specifying its size, the compiler automatically
determines the size based on the number of initializers.
Example:
int scores[] = {85, 90, 78, 92};
The array scores will have a size of 4.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Initialization After Declaration
Array elements can be assigned values individually after the array has been
declared.
Example:
int data[3];
data[0] = 100;
data[1] = 200;
data[2] = 300;
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Accessing Array Elements
Index:
Array elements are accessed using an index. Indexing in C starts from 0. The first
element has index 0, the second element has index 1, and so on.
Syntax:
array name[index]
Example:
int numbers[5] = {10, 20, 30, 40, 50};
int first_Element = numbers[0]; // 10
int third_Element = numbers[2]; // 30
numbers[4] = 60; // modifies fifth element
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Accessing an Array/traversing through array
Array elements are accessed using their index value. The index starts from 0 and
goes up to size - 1.
Example using loop:
#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50};
int i;
for(i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Insertion of a Value in an Array
Program:
#include<stdio.h> Explanation:
void main() The array initially contains some
{ values and the remaining positions
int x[]={3,6,9,12};
are filled with zero.
int n,i,temp,position;
printf("Enter Position:"); The user enters the position
scanf("%d",&position);
(1-based indexing) and the new
printf("Enter New Element:");
scanf("%d",&n); element to be inserted.
for(i=0;i<5;i++)
From the specified position, all
{
if(i>=position-1) existing elements are shifted one
{ position to the right.
temp=x[i];
x[i]=n; A temporary variable is used to
n=temp; prevent loss of data during
} shifting.
}
for(i=0;i<5;i++) Finally, the new element is
printf("%d ",x[i]); inserted at the required position.
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Algorithm: Deletion of an Element from an Array
Step 1: Start the program.
Step 2: Declare an array with initial values and empty positions.
Step 3: Read the position of the element to be deleted.
Step 4: Shift all elements from the given position to the left by one position.
Step 5: Set the last element of the array to zero.
Step 6: Display the array after deletion.
Step 7: Stop the program.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Deletion of an Element from an Array
#include<stdio.h>
void main()
{
int x[10]={3,6,9,12,15,
18,21,0,0,0};
x[9]=0;
int i,position;
printf("Array After Deletion:\n");
printf("Enter Position:");
for(i=0;i<10;i++)
scanf("%d",&position);
printf("%d ",x[i]);
}
for(i=0;i<9;i++)
{
if(i>=position-1)
x[i]=x[i+1];
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Algorithm: Sequential Search
Step 1: Start the program.
Step 2: Declare and initialize the array.
Step 3: Read the element to be searched.
Step 4: Compare the search element with each array element starting from the
first.
Step 5: If a match is found, display the position and stop searching.
Step 6: If the end of the array is reached without a match, display “element not
found”.
Step 7: Stop the program.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Sequential Search in an Array
for(i=0;i<10;i++)
#include<stdio.h> {
void main() if(x[i]==n)
{ {
int x[10]={3,6,9,12,15, printf("Element Found at %d",i+1);
18,21,24,27,30}; break;
int i,n; }
}
printf("Enter Search Element:"); if(i==10)
scanf("%d",&n); printf("Element not found");
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Algorithm: Bubble Sort
Step 1: Start the program.
Step 2: Declare and initialize the array.
Step 3: Repeat the following steps for all array elements.
Step 4: Compare adjacent elements.
Step 5: Swap the elements if they are in the wrong order.
Step 6: Continue passes until the array is sorted.
Step 7: Display the sorted array.
Step 8: Stop the program.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Bubble Sort
#include<stdio.h>
void main()
{
int a[10]={25,10,35,5,20,
15,30,40,45,50};
int i,j,temp;
for(i=0;i<9;i++)
{
for(j=0;j<9-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<10;i++)
printf("%d ",a[i]);
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Programming Exercises – One Dimensional Arrays
Exercise 1: Write a C program to read elements into an array and display the
elements in reverse order.
Exercise 2: Write a C program to find the sum of all elements in a given array.
Exercise 3: Write a C program to count the number of even and odd elements in
an array.
Exercise 4: Write a C program to find the largest element in a given array.
Exercise 5: Write a C program to find the smallest element in a given array.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Two-Dimensional Array
A two-dimensional array in C is an array of arrays.
It is used to represent data in a tabular form consisting of rows and columns.
A two-dimensional array can be visualized as a grid or a matrix.
Examples of applications include matrices, tables, and game boards.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Declaration of Two-Dimensional Array
Syntax:
data type array name[rows][columns];
Where:
data type specifies the type of elements.
array name is the name of the array.
rows indicates number of rows.
columns indicates number of columns.
Examples:
int matrix[3][4];
float table[5][2];
char board[8][8];
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Memory Representation of Two-Dimensional Array
A two-dimensional array is stored in contiguous memory locations.
Elements are stored in row-wise order.
All elements of the first row are stored first, followed by elements of the second
row, and so on.
This memory layout helps in efficient access and manipulation of array elements.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Two-Dimensional Array Representation
Matrix Representation
a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
Rows and columns are accessed using row index and column index starting from 0.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Initialization of Two-Dimensional Array
Row-wise Initialization:
int matrix[2][3] = {{1,2,3}, {4,5,6}};
Linear Initialization:
int matrix[2][3] = {1,2,3,4,5,6};
Elements are filled in row-major order.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Partial Initialization of 2D Array
If fewer values are provided, remaining elements are automatically initialized to
zero.
Example:
int matrix[3][3] = {{1,2},{3}};
Unassigned elements will be set to 0.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Initialization After Declaration
Individual elements can be assigned values after declaration.
int data[2][2];
data[0][0] = 10;
data[0][1] = 20;
data[1][0] = 30;
data[1][1] = 40;
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Accessing Two-Dimensional Array Elements
Array elements are accessed using row and
column indices. Before Modification
Indexing starts from 0 for both rows and (0,0)=1 (0,1)=2 (0,2)=3
columns. (1,0)=4 (1,1)=5 (1,2)=6
Example: After Modification
1 10 3
int matrix[2][3] = {{1,2,3},{4,5,6}}; 4 5 6
int element = matrix[1][2];// element = 6
matrix[0][1] = 10
matrix[0][1] = 10;
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Traversing Two-Dimensional Arrays
Two-dimensional arrays are traversed using
nested loops.
The outer loop iterates through rows and the
inner loop iterates through columns.
Example:
#include <stdio.h>
int main() Traversal Order
{
1 2 3
int matrix[2][3]={{1,2,3},{4,5,6}};
4 5 6
int i,j;
for(i=0;i<2;i++)
Row-wise traversal using nested
{ loops
for(j=0;j<3;j++)
printf("%d ",matrix[i][j]);
printf("\n");
}
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Addition of Two Matrices
In matrix addition, corresponding elements of two matrices are added and stored
in a third matrix.
Example:
Matrix X + Matrix Y
21 22 23 11 12 13
24 25 26 + 14 15 16
27 28 29 17 18 19
Result Matrix Z
32 34 36
38 40 42
44 46 48
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Algorithm: Addition of Two Matrices
Step 1: Start the program.
Step 2: Declare three two-dimensional arrays for matrices X, Y, and Z.
Step 3: Read elements of the first matrix X.
Step 4: Read elements of the second matrix Y.
Step 5: Add corresponding elements of X and Y and store the result in Z.
Step 6: Display matrices X, Y, and Z.
Step 7: Stop the program.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Addition of Two Matrices
#include<stdio.h>
void main()
{ for(i=0;i<3;i++)
int x[3][3],y[3][3],z[3][3]; {
int i,j; for(j=0;j<3;j++)
z[i][j]=x[i][j]+y[i][j];
for(i=0;i<3;i++) }
{
for(j=0;j<3;j++) for(i=0;i<3;i++)
scanf("%d",&x[i][j]); {
} for(j=0;j<3;j++)
printf("%d ",z[i][j]);
for(i=0;i<3;i++) printf("\n");
{ }
for(j=0;j<3;j++) }
scanf("%d",&y[i][j]);
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Multiplication of Two Matrices
In matrix multiplication, each element of the result matrix is obtained by
multiplying elements of a row of the first matrix with the corresponding elements
of a column of the second matrix and then adding them.
Example:
Matrix A × Matrix B
1 2 5 6
×
3 4 7 8
Result Matrix C
(1 × 5 + 2 × 7) (1 × 6 + 2 × 8) 19 22
=
(3 × 5 + 4 × 7) (3 × 6 + 4 × 8) 43 50
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Algorithm: Multiplication of Two Matrices
Step 1: Start the program.
Step 2: Declare two matrices A and B and a result matrix C.
Step 3: Read the number of rows and columns of matrix A.
Step 4: Read the number of rows and columns of matrix B.
Step 5: Check whether the number of columns of matrix A is equal to the
number of rows of matrix B. If not, matrix multiplication is not possible.
Step 6: Read the elements of matrix A.
Step 7: Read the elements of matrix B.
Step 8: Multiply matrices using three nested loops:
Outer loop for rows of matrix A
Middle loop for columns of matrix B
Inner loop for summation of products
Step 9: Store the computed value in the corresponding position of matrix C.
Step 10: Display the resultant matrix C.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Multiplication of Two Matrices
#include<stdio.h> for(i=0;i<3;i++)
void main() {
{ for(j=0;j<3;j++)
int a[3][3],b[3][3],c[3][3]; {
int i,j,k; c[i][j]=0;
for(k=0;k<3;k++)
for(i=0;i<3;i++) c[i][j]+=a[i][k]*b[k][j];
{ }
for(j=0;j<3;j++) }
scanf("%d",&a[i][j]);
} for(i=0;i<3;i++)
{
for(i=0;i<3;i++) for(j=0;j<3;j++)
{ printf("%d ",c[i][j]);
for(j=0;j<3;j++) printf("\n");
scanf("%d",&b[i][j]); }
} }
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Programming Exercises – Two-Dimensional Arrays
Exercise 1: Write a C program to find the transpose of a given matrix.
Exercise 2: Write a C program to display the diagonal elements of a square
matrix.
Exercise 3: Write a C program to find the sum of diagonal elements of a square
matrix.
Exercise 4: Write a C program to find the determinant of a 2 Ö 2 matrix.
Exercise 5: Write a C program to check whether a given matrix is symmetric.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Enumerated Data Type (enum)
The enumerated data type is a user-defined data type in C.
It consists of a set of named integer constants called enumerators.
The enum keyword is used to create an enumerated data type.
Enumerated data types improve code readability and maintainability.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Syntax of enum
General Syntax:
enum enum name { value1, value2, ..., valueN };
Where:
enum name is the name of the enumerated type.
value1, value2, ..., valueN are named integer constants.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
enum Example Program
#include<stdio.h>
enum Days {
SUN, MON, TUE, WED, THU, FRI, SAT
};
int main()
{
enum Days today = WED;
if(today == WED)
printf("Today is Wednesday.\n");
printf("Numeric value of WED is %d", WED);
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Strings in C
In C, a string is a sequence of characters stored in an array of characters.
Every string in C is terminated by a special character called the null character
’\0’.
String handling includes declaration, initialization, manipulation, and comparison.
Most string operations use functions from the string.h library.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
String Declaration and Initialization
Character Array Declaration:
char str[20];
This declaration can store up to 19 characters plus one null character.
Initialization Examples:
char str[] = "Hello";
char str[6] = {’H’,’e’,’l’,’l’,’o’,’\0’};
Government Engineering College Thrissur Department of Electronics & Communication Engineering
String Storage in Memory
Example 1: String Literal Initialization
char str[] = "Hello";
H e l l o \0
0 1 2 3 4 5
Example 2: Character Array with Larger Size
char string[10] = "hello";
h e l l o \0 \0 \0 \0
0 1 2 3 4 5 6 7 8
The first null character \0 marks the end of the string. Remaining locations are
also filled with \0.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Null Character in Strings
The null character ’\0’ indicates the end of a string.
String functions rely on the null character to determine string length.
Without the null character, string functions may produce incorrect results.
Hence, every valid string in C must end with ’\0’.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Reading Strings using scanf()
The scanf() function can be used to read strings in C.
Syntax:
scanf("%s", string name);
The %s format specifier reads characters until a whitespace is encountered.
Example:
scanf("%s", name);
This reads a single word (no spaces).
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Using Field Width in scanf()
A field width can be specified to limit the number of characters read.
Syntax:
scanf("%ws", string name);
This reads at most w characters and automatically appends the null character.
Example:
char name[10];
scanf("%5s", name);
This helps prevent buffer overflow.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Reading Strings using gets()
The gets() function reads an entire line including spaces.
Syntax:
gets(string name);
Example:
char address[];
gets(address);
Note:
The gets() function is unsafe and has been removed from modern C standards
due to buffer overflow issues.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Reading Strings using getch()
The getchar() function reads a single character without echoing it.
It can be used to read strings character by character.
Concept:
Characters are read one by one until the Enter key is pressed.
Example Logic:
char ch;
ch = getchar();
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Writing Strings using printf()
The printf() function is commonly used to display strings in C.
Syntax:
printf("%s", string name);
Example:
printf("%s", name);
This prints the string until the null character is encountered.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Formatted String Output using printf()
The printf() function allows formatting using width and precision.
Syntax:
printf("%[Link]", string name);
Where:
w specifies the minimum field width.
p specifies the maximum number of characters to print.
Example:
printf("%10.5s", "Programming");
This prints only the first 5 characters right-aligned in a field of width 10.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Writing Strings using puts()
The puts() function is used to display a string.
It automatically moves the cursor to the next line after printing the string.
Syntax:
puts(string name);
Example:
puts("Welcome to C Programming");
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Writing Characters using putchar()
The putchar() function is used to display a single character on the screen.
It writes the character to the standard output (stdout).
Syntax:
putchar(character);
Example:
putchar(’A’);
Note:
The putchar() function can be used inside a loop to print a string character by
character.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
String Handling Functions in C
Function Description
strlen() Finds length of a string
strcpy() Copies one string to another
strncpy() Copies first n characters
strcmp() Compares two strings
stricmp() Case-insensitive string comparison
strncmp() Compares first n characters
strnicmp() Case-insensitive comparison (n chars)
strcat() Concatenates two strings
strrev() Reverses a string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
strstr() Finds first occurrence of a substring
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strlen() Function
The strlen() function returns the number of characters in a string, excluding
the null character.
Example:
char msg[] = "Peacock";
int l = strlen(msg);
printf("Length = %d", l);
Output: Length = 7
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strcpy() and strncpy()
strcpy(): Copies entire source string to destination.
char src[] = "Hello";
char dest[15];
strcpy(dest, src);
strncpy(): Copies only first n characters.
strncpy(dest, src, 2);
Destination string becomes "He"
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strcpy() Function Example
#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "Hello";
char destination[20];
strcpy(destination, source);
printf("Source string : %s\n", source);
printf("Destination string : %s\n", destination);
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strcat() Function
The strcat() function appends one string to another.
Example:
char String1[] = "Hello";
char String2[] = "World";
strcat(String1, String2);
Result: Hello World
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strcat() Function Example
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20] = "Hello ";
char string2[] = "World";
strcat(string1, string2);
printf("After concatenation:\n");
printf("%s", string1);
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strcmp() Function
The strcmp() function compares two strings.
It returns:
strings are equal
first string is smaller
0
first string is larger
-1
1
Example:
0
-1
strcmp("BAOU","BAOU")
strcmp("BAOU","baou")
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Program to Compare Two Strings
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[] = "Hello";
int result;
result = strcmp(str1, str2);
if(result == 0)
printf("Both strings are equal");
else
printf("Strings are not equal");
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
String Modification Functions
strrev(): Reverses a string.
"Gujarat" "tarajuG"
strlwr(): Converts string to lowercase.
"BSC-IT" "bsc-it"
strupr(): Converts string to uppercase.
"baou" "BAOU"
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strrev() and Palindrome Check
#include <stdio.h> Explanation:
#include <string.h> The program reads a string from the
user.
int main()
{ The original string is copied into
char str[20], rev[20]; another array.
printf("Enter a string: "); The copied string is reversed using
scanf("%s", str); the strrev() function.
strcpy(rev, str); The original and reversed strings are
strrev(rev);
compared using strcmp().
if(strcmp(str, rev) == 0) If both strings are equal, the string
printf("Palindrome");
else is a palindrome; otherwise, it is not.
printf("Not a Palindrome");
Output:
return 0; input:madam, reversed: madam,
} output: Palindrome
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strstr() Function
The strstr() function finds the first occurrence of a substring.
Example:
strstr("Programming","gram");
Returns address of substring "gram".
If substring is not found, it returns NULL.
Government Engineering College Thrissur Department of Electronics & Communication Engineering
strstr() Function – String Matching
Question: Write a C program to find
whether a substring is present in a given
string.
Output:
#include <stdio.h>
#include <string.h> Substring found
int main() Explanation:
{
char str[] = "Programming"; The function strstr() searches for
char sub[] = "gram"; the substring "gram" inside the
char *result;
string "Programming".
result = strstr(str, sub); If the substring is found, it returns
if(result != NULL) the address of its first occurrence.
printf("Substring found");
else
If the substring is not found, it
printf("Substring not found"); returns NULL.
return 0;
}
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Programming Exercises – Strings
1. Write a C program to read your name and display it.
2. Write a C program to extract the substring "gram" from the string
"programming" and display it.
3. Write a C program to read a string and display its characters in alphabetical
order. Example: name aemn
4. Write a C program to read a string and determine whether it is a palindrome.
5. Write a C program to read two strings and combine (concatenate) them.
6. Write a C program to compare two strings and check whether they are equal.
7. Write a C program to find the number of occurrences of a substring in a given
string.
8. Write a C program to count the number of occurrences of a given character in
a string.
9. Write a C program to find largest and smallest word in a sentence.
10. Write a C program to replace character ’e’ with ’a’ in the string "hello".
Government Engineering College Thrissur Department of Electronics & Communication Engineering
Thank You
Government Engineering College Thrissur Department of Electronics & Communication Engineering