Programming in C - Structures
Programming in C - Structures
Module II
Contents:
Arrays – definition, initialization and processing of arrays – Searching algorithms – Linear search,
Binary Search, Sorting algorithms – Selection sort, Quick sort, Passing arrays to functions - Strings –
Representation of strings in C – String input and output - String processing – copy, concentrate,
length, comparison, pattern searching etc - builtin String functions – Implementation of string
functions.
Arrays:
● An array is a collective name given to a group of ‘similar elements’.
● It is a fixed-size sequenced collection of elements of the same data type, which can be any
primitive or user defined data types..
● Eg: Marks of 100 students can be represented by an integer array, salary of 200 employees by a
float array.
● An array is also known as a subscripted variable or indexed variable.
● The first element in the array is said to be at index 0, so the last element is at index 1 less than
the size of the array.
● Array initialization: An array can be initialized with values during the declaration also.
● Eg:
○ int num[6] = { 2, 4, 12, 5, 45, 5 } ;
○ int n[ ] = { 2, 4, 12, 5, 45, 5 } ; // automatically allocates 6 locations
○ float pressure[ ] = { 12.3, 34.2, -23.4, -11.3 } ;
int main()
{
int arr[10][10], i, j, m, n;
printf("Enter the number of elements in the row:");
scanf("%d", &m);
printf("Enter the number of elements in the column:");
scanf("%d", &n);
printf("Enter the elements:");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &arr[i][j]);
}
}
return 0;
}
Initialization of a 2D array
● The following matrix can be initialized as given below.
printf("Matrix is\n");
for(i=0;i<rows;i++)
{
S3 CT, GPTC Cherthala 3
for(j=0; j<cols; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("Transpose is\n");
for(i=0;i<cols;i++)
{
for(j=0; j<rows; j++)
{
printf("%d ", a[j][i]);
}
printf("\n");
}
}
Matrix is
1 2
3 4
5 6
Transpose is
1 3 5
2 4 6
Features of Arrays
1. Contiguous Memory Allocation
2. Fixed Size
3. Zero-Based Indexing
4. Direct Access to Elements
5. Initialization
6. Array Name as a Pointer
7. Multi-Dimensional Arrays
int main( )
{
int main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ; //call by reference
return 0;
}
● Here, we are passing addresses of individual array elements to the function display( ).
Hence, the variable in which this address is collected (n) is declared as a pointer variable.
And since n contains the address of array element, to print out the array element we are using
the ‘value at address’ operator (*).
● If the value at the pointer n is changed, the actual array element also will be changed.
Searching Algorithms
Linear Search
Linear search is a straightforward searching algorithm that sequentially checks each element in
a list or array until a match is found or all elements have been checked.
Steps:
1. Start from the beginning of the list.
2. Compare each element of the list with the target value sequentially.
3. If a match is found, the search stops, and the index of the matched element is returned (or the
element itself, depending on the implementation).
4. If the end of the list is reached without finding the target value, the search concludes with a
message indicating that the target value is not in the list.
Program:
#include <stdio.h>
int main()
{
int arr[10], i, key, n, index=-1;
printf("Enter the number of elements:");
scanf("%d", &n);
printf("Enter the elements:");
for(i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
if (index == -1)
{
printf("Element is not found in the array\n");
}
else
{
printf("Element is found at index %d\n", index);
}
return 0;
}
Binary Search
Binary Search is a search algorithm that is used to find the position of an element in a sorted
array. The binary search algorithm works by comparing the element to be searched by the middle
element of the array and based on this comparison follows the required procedure.
Case 1: if element == middle, the element is found and returns the index.
Case 2: if element < middle, search for element in the left sub-array starting from index 0 to
middle-1.
Case 3: if element > middle, search for the element in the right sub-array starting from
middle+1 index to the last element (index n-1).
This division and searching continues until the search element is found (successful search) or
the lower and upper indexes cross each other (unsuccessful search).
After every cycle of search, the algorithm divides the size of the array into half hence in the
next iteration it will work only in the remaining half of the array.
Binary search works efficiently on sorted data whatever be the size of the data.
Example 1.
Array of 10 elements: 3 5 7 9 12 15 18 20 23 25
Key to be searched is 20
first = 0, last =9
middle=(first+last)/2 = 4
Compare the element at middle and the key, ie, 12 and 20
Since 20 is greater than 12, take the right sub-array starting from index middle+1 to last, ie, 5
to 9.
Continue searching until the key is found or interval is zero.
Example 2.
Here L represents first, H represents end and M represents middle.
int main()
{
int a[10] ; // array with max size 10
int val; // value to be searched
int n; // size of array
int i;
int res; // stores the result
printf( "Enter number of items: ");
scanf("%d",& n);
S3 CT, GPTC Cherthala 8
printf( "Enter the sorted items: \n");
for(i = 0; i< n; i++)
{
scanf("%d",& a[i]);
}
printf( "Enter key to be searched: ");
scanf("%d",& val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at index %d of the array", res);
return 0;
}
Sorting algorithms
Selection Sort
The algorithm repeatedly selects the smallest element from the unsorted portion of the list and
swaps it with the first element of the unsorted part. Then it becomes part of the sorted list. This
process is repeated for the remaining unsorted portion until the entire list is sorted.
Steps:
1. Initialization: Start with the entire array considered as unsorted.
2. Find Minimum: Iterate through the unsorted part of the array to find the minimum element.
3. Swap: Swap the minimum element with the first element of the unsorted part (or place it
directly at the end of the sorted part).
4. Repeat: Move the boundary between the sorted and unsorted parts one element to the right and
repeat steps 2 and 3 until the entire array is sorted.
5. End: The array is now sorted.
Eg:
Program:
#include <stdio.h>
S3 CT, GPTC Cherthala 9
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, minposition, swap;
Quick Sort
● Quick sort is a commonly used sorting algorithm that is often preferred over other sorting
algorithms due to its efficiency and effectiveness.
● Uses a divide-and-conquer approach to sort elements.
● Quick Sort divides the array into smaller parts (sub-arrays) and recursively sorts these parts. It
then combines these sorted parts to produce the final sorted array.
● The core idea of Quick Sort is to select a 'pivot' element from the array. This pivot element is
used to partition the array into two sub-arrays: elements less than the pivot and elements
greater than the pivot.
● The array is rearranged so that all elements less than the pivot come before the pivot and all
elements greater than the pivot come after it. The pivot is then placed in its correct position in
the sorted array.
● Quick Sort is then applied recursively to the sub-arrays formed by the partitioning step. This
process continues until the base case is reached (usually when the sub-array has one or zero
elements, which is inherently sorted).
Program:
void quicksort(int number[],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
int main(){
int i, count, number[25];
printf("How many elements are you going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: \n", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
Strings
● A string is a one-dimensional array of characters terminated by a null ( ‘\0’ ).
● ‘\0’ is called the null character and its ASCII value is 0.
● Each character in the array occupies one byte of memory and the last character is always ‘\0’.
● ‘\0’ is the only way for the program to understand that the string has ended.
● Eg:
○ char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
● Reading a string:
(1) scanf(“%s”, name”);
○ Here the characters are stored in the variable name till it reaches a delimiter such as
Space or Enter.
○ The number of characters must not be greater than the memory space allocated for the
string when declared.
○ Eg: if “good morning” is entered, only “good” is stored.
(2) gets(name);
● Here all the characters including space are stored until Enter key is reached. This can
be used to enter a line of characters.
○ if “good morning” is entered, “good morning” is stored.
(3) scanf ( "%[^\n]s", name ) ;
● Similar to gets(). All characters until a ‘\n’ is reached are stored in the array.
Example Program: To check whether a string is palindrome or not using standard string functions.
#include<stdio.h>
#include<string.h>
int main()
{
char source[10], reverse[10];
int length,i;
printf("Enter the string in lowercase: ");
scanf("%s",source);
printf("Reverse is %s\n",reverse);
if(strcmp(source,reverse)==0)
{
printf("The given string is palindrome\n");
}
else
{
printf("The given string is not palindrome\n");
}
return 0;
}
***************************************
Nov 2022
1. Write the initialization statement of the following matrix. (1)
Nov 2023
1. The library function used to find the length of a string is ......... (1)
2. Write a C statement to initialize an array with values 3,7,2,4,1. (1)
3. Illustrate the steps to solve problems using divide and conquer methods. (3)
4. (a)Differentiate between one dimensional and two dimensional arrays. (3 Marks)
(b)Write a C program to find the transpose of a given matrix. (4 Marks)
5. Write a C program to implement binary search algorithm. (7)
6. Explain any four string manipulation functions with examples. (7)
7. Write a C program to check whether a given string is palindrome or not. (7)