Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views14 pages

Unit Ii

This document covers Unit II of a Programming in C course, focusing on arrays and strings. It includes topics such as array declaration, initialization, types of arrays, string operations, and algorithms for searching and sorting. The document provides examples and syntax for implementing these concepts in C programming.
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)
4 views14 pages

Unit Ii

This document covers Unit II of a Programming in C course, focusing on arrays and strings. It includes topics such as array declaration, initialization, types of arrays, string operations, and algorithms for searching and sorting. The document provides examples and syntax for implementing these concepts in C programming.
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/ 14

PROGRAMMING IN C

UNIT II
Arrays and Strings

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
Unit II
Topics
2.1 Arrays
2.2 Types of arrays
2.3 String and Its Operations
2.4 Searching and Sorting Algorithm

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
CS3251 PROGRAMMING IN C LT PC 3 0 0 3

UNIT II
ARRAYS AND STRING

Introduction to Arrays: Declaration, Initialization – One dimensional array –Two dimensional


arrays - String operations: length, compare, concatenate, copy – Selection sort, linear and
binary search.

Course Outcomes

CO2: Apply and implement applications using arrays and strings K3

Course Objectives
To develop C programs using arrays and strings
Important Topics
1. Array and it’s types
2. String and it’s Operations
3. Selection sort and linear search and binary search

1. ARRAYS
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., as well as derived and user-defined data types such as pointers, structures, etc.

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
1. Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In C, we
have to declare the array like any other variable before using it.
data_type array_name[size];
The above statements create an array with the name array_name, and it can store a specified
number of elements of the same data type.
Example:
// Creates array arr to store 5 integer values.
int arr[5];

2. Array Initialization
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we
need to initialize the array to some meaningful values.

Syntax:
int arr[5] = {2, 4, 8, 12, 16};

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
The above statement creates an array arr and assigns the values {2, 4, 8, 12, 16} at the time of
declaration.

3.Accessing Array Elements


Array in C provides random access to its elements, which means that we can access any
element of the array by providing the position of the element, called the index.
Syntax:
The index values start from 0 and goes up to array_size-1. We pass the index inside square
brackets [] with the name of the array.
array_name [index];
Program:
#include <stdio.h>
int main() {
int arr[5] = {2, 4, 8, 12, 16};
printf("%d ", arr[2]);
printf("%d ", arr[4]);
printf("%d ", arr[0]);
return 0;
}
Output
8 16
4.Types of Arrays
1. One-Dimensional
The simplest type of arrays, one-dimensional arrays, contains a single row of
elements. These arrays are usually indexed from 0 to n-1, where ‘n’ is the size of the
array. Utilizing its assigned index number, each element in an array can be
conveniently accessed.

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
Syntax:
data_type array_name[size];
Example:
#include <stdio.h>
int main() {
int i;
int marks[5] = {85, 90, 78, 92, 88};
printf("Student Marks:\n");
for(i = 0; i < 5; i++) {
printf("Student %d: %d\n", i + 1, marks[i]);
}
return 0;
}
Output:
Student Marks:
Student 1: 85
Student 2: 90
Student 3: 78
Student 4: 92
Student 5: 88
2. Two-Dimensional
Two-dimensional array type are arrays that contain arrays of elements. These are also
referred to as matrix arrays since they can be thought of as a grid that lays out the
elements into rows and columns. Each element within the two-dimensional array can
be accessed individually by its row and column location. This array type is useful for
storing data such as tables or pictures, where each element may have multiple
associated values.
Syntax:
data_type array_name[rows][columns];
Program:
#include <stdio.h>
int main() {
int i, j;
int matrix[2][3] = {
{1, 2, 3},

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
{4, 5, 6}
};
printf("Matrix Elements:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}

Output:
Matrix Elements:
123
456

3. Multi-Dimensional:
Multi-Dimensional arrays are a powerful data structure used to store and manage data
organizationally. This type of arrays consist of multiple arrays that are arranged
hierarchically. They can have any number of dimensions, the most common being two
dimensions (rows and columns), but three or more dimensions may also be used.
Syntax:
data_type array_name[d][r][c];
Program:
#include <stdio.h>
int main {
int arr[2][3][2] = {
{ {0, 1}, {2, 3}, {4, 5} },
{ {6, 7}, {8, 9}, {10, 11} }
};
for (int k = 0; k < 2; k++) {
printf("Layer %d:\n", k);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%2d ", arr[k][i][j]);
}
printf("\n");

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
}
printf("\n");
}
return 0;
}
Output:
Layer 0:
0 1
2 3
4 5
Layer 1:
6 7
8 9
10 11

2.Strings
1. What is String:
A String in C programming is a sequence of characters terminated with a null character
'\0'. The C String is work 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'
• Declaration: Declaring a string in C is as simple as declaring a one-dimensional
array of character type. Below is the syntax for declaring a string.
char string_name[size];
• Initialization
We can initialize a string either by specifying the list of characters or string literal.
// Using character list
char str[] = {'C', 'O', 'M', 'P', 'U', 'T', 'E', 'R', '\0'};

// Using string literal


char str[] = "computer";
2. String Length:
To find the length of a string, you need to iterate through it until you reach the null
character ('\0'). The strlen() function from the C standard library is commonly used to get
the length of a string.

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
Example:

#include <stdio.h>
int main() {
char str[] = "computer";
printf("%d", strlen(str));
return 0;
}

Output
8
3. String Compare:
In C, strcmp() is a built-in library function used to compare two strings lexicographically. It
takes two strings (array of characters) as arguments, compares these two strings
lexicographically, and then returns some value as a result.

Program:
#include <stdio.h>
#include <string.h>
int main(){
char* s1 = "Geeks";
char* s2 = "Geeks";
printf("%d", strcmp(s1, s2));
return 0;
}
Output
0
4. String Concatenate:
The strcat() function will append a copy of the source string to the end of destination string.
The strcat() function takes two arguments:
1) dest
2) src
It will append copy of the source string in the destination string. The terminating character at
the end of dest is replaced by the first character of src .
Return value: The strcat() function returns dest, the pointer to the destination string.

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
Program:

#include <stdio>
#include <string>
int main(){
char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src);
printf(“%s”, dest) ;
return 0;
}
Output:
This is an example
5. String Copy:
strcpy() is a function in the C standard library <string.h> used to copy the contents of one
null-terminated string (src) into another character array (dest), including the terminating
'\0'. It does not check whether dest is large enough to hold src—this omission can lead to
buffer overflows if dest isn't properly sized.
Program:

#include <stdio.h>
#include <string.h>
int main(void) {
char src[] = "Hello, C world!";
char dest[50];

strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}
Output:
Copied string: Hello, C world!

Searching and Sorting Algorithms


1. Selection Sort:
// C program for implementation of selection sort
#include <stdio.h>

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {

// Assume the current position holds


// the minimum element
int min_idx = i;

// Iterate through the unsorted portion


// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {

// Update min_idx if a smaller element is found


min_idx = j;
}
}

// Move minimum element to its


// correct position
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}

void printArray(int arr[], int n) {


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);

selectionSort(arr, n);

printf("Sorted array: ");


printArray(arr, n);

return 0;
}

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
Output:
Original vector: 64 25 12 22 11
Sorted vector: 11 12 22 25 64

2. Linear Search:
// 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;
}
Output
Present at Index 3

3. Binary Search:
// C program to implement iterative Binary Search
#include <stdio.h>

// An iterative binary search function.


int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high) {
int mid = low + (high - low) / 2;

// Check if x is present at mid


if (arr[mid] == x)

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251
return mid;

// If x greater, ignore left half


if (arr[mid] < x)
low = mid + 1;

// If x is smaller, ignore right half


else
high = mid - 1;
}

// If we reach here, then element was not present


return -1;
}

// Driver code
int main(void)
{
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);
if(result == -1) printf("Element is not present in array");
else printf("Element is present at index %d",result);

}
Output
Element is present at index 3

DEVENTHIRAN M |CSE
PROGRAMMING IN C | CS3251

You might also like