Array
Array
Definition
One-Dimensional Array or single Dimensional Array is one in which only one-subscript specification
is needed to specify a particular element of the array.
Array Declaration
The general form of array declaration is
data-type variable-name[size];
Example:
int number[5];
Conceptually you can think of a one-dimensional array as a row, where elements are stored one after
another.
The above declaration reserves five storage locations as shown below:
number
1
Initialization of one-dimensional arrays
An array can be initialized while declaring it. The general form of initialization of arrays is:
Character arrays
• Character arrays may be initialized in a similar manner;
• When initializing character arrays, we must specify one extra element, the null terminator
‘\0’ as the last character.
The above statement declares the name to be an array of five characters, initialized with the string
‘John’ ending with the null character.
•Once an array is declared, the individual elements in the array can be referred. This is done with
subscript, the number in the brackets following the array name.
Suppose we declared an array age as above. The first element is age[0], the second element
is age[1] and so on
For example,
scanf(“%d”, &age[3]);
will read and store an integer value to the 4th element of array age[].
The above statement will print the value of 4th element of the array age[].
2
Entering Data into an Array
Here is the section of code that places data into an array(for eg, marks of 30 students)
printf ( "\nEnter marks " ) ;
for ( i = 0 ; i <=30 ; i++ )
{
scanf ( "%d", &marks[i] ) ;
}
• While passing arrays to the argument, only the name of the array is passed as an argument(,i.e,
starting address of memory area is passed as argument). No need to specify the subscript operator
[] along with the array name.
• C program to pass an array containing age of person to a function. This function will return
average age and display the average age in main function.
#include <stdio.h>
float average(float a[]);
int main()
{
float c[]={23.4, 55, 22.6, 3, 40.5, 18};
float avg;
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
}
3
TWO-DIMENSIONAL ARRAY
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns.
Example:
int marks[4][3];
The two-dimensional array can be declared and initialized in the following ways.
Eg. Method 1
int stud[4][2]={
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
}
Method 2
Here is another method to initialise
int stud[4][2]= { 1234,56, 1212,33, 1434,80, 1312,78 };
Example Program : Program to read and display matrix using user-defined functions.
#include <stdio.h>
4
{
int a[10][10],i,j,r,c;
printf("Enter the order of the matrix : ");
scanf("%d%d",&r,&c);
read_mat(a,r,c);
print_mat(a,r,c);
return 0;
}
5
SELECTION SORT
Selection sort is a simple comparison-based sorting algorithm used to arrange elements in a specific
order, typically in ascending order.
Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each
iteration and places that element at the beginning of the unsorted list.
1. The algorithm starts with the entire array considered as unsorted. It maintains two subarrays:
• Sorted Subarray: Initially empty.
• Unsorted Subarray: Initially the entire array.
2. Set the first element in the unsorted list as minimum.
3. Compare minimum with second element. If the second element is smaller than minimum,
assign the second element as minimum and likewise scans through the entire unsorted list to
find the minimum.
4. Swapping: Once the minimum (or maximum) element is found, it is swapped with the first
element in the unsorted sublist. This effectively moves the smallest (or largest) element to its
correct position in the sorted sublist.
5. Repeat: Steps 2 through 4 are repeated until the entire list is sorted. In each iteration, the
smallest (or largest) remaining element in the unsorted sublist is selected and moved to the
end of the sorted sublist.
#include <stdio.h>
int main()
{
int a[100],i,j,min_indx,n;
printf("Enter the number of elements to enter : ");
scanf("%d",&n);
6
for(i=0;i<n;i++)
scanf("%d",&a[i]);
/* Sorting */
for(i=0;i<n-1;i++)
{
min_indx=i;
for(j=i+1;j<n;j++)
{
if(a[j] < a[min_indx])
{
min_indx=j;
}
}
//swapping element at position i with position min_indx
int temp;
temp = a[i];
a[i]= a[min_idx];
a[min_idx]=temp;
}
}
return 0;
}
QUICK SORT
Quick sort is a sorting algorithm based on the divide and conquer approach where,
1. An array is divided into sub-arrays by selecting a pivot element (element selected from the
array).
While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side of
the pivot.
Items in the left < pivot
Items in the right >pivot
2. The left and right subarrays are also divided using the same approach. This process continues
until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.
7
Program
#include<stdio.h>
void quicksort(int [],int,int);
int main()
{
int i, count, number[100];
printf("Enter the number of elements (Max. - 100): ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("The Sorted Order is: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
LINEAR SEARCH
Linear search, also called sequential search is a very simple method used for searching an array for a
particular value. It works by comparing every element of the array one by one in sequence until a
match is found. Linear search is mostly used to search an unordered list of element.
8
Program to implement Linear seach
#include <stdio.h>
int main()
{
int a[100],i,search,n,found=0;
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search
interval in half.
Binary Search Algorithm: The basic steps to perform Binary Search are:
• Divide the search space into two halves by finding the middle index
“mid”.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
9
• If the key is not found at middle element, choose which half will be used
as the next search space.
• If the key is smaller than the middle element, then the left side
is used for next search.
• If the key is larger than the middle element, then the right side
is used for next search.
• This process is continued until the key is found or the total search space
is exhausted.
Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target =
23.
First Step: Calculate the mid and compare the mid element with the key. If the
key is less than mid element, move to left and if it is greater than the mid then
move search space to the right.
• Key (i.e., 23) is greater than current mid element (i.e., 16). The search
space moves to the right.
• Key is less than the current mid 56. The search space moves to the left.
Second Step: If the key matches the value of the mid element, the
element is found and stop search.
10
Program to implement Binary Search
#include <stdio.h>
int main()
{
int a[100],i,j,search,n,found=0,low,high,mid;
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
/*Binary Search */
low=0;
high=n-1;
11
if(search == a[mid])
{
found=1;
printf("%d is found in the array at position = %d\n",search,mid+1);
break;
}
else if (search < a[mid])
{
high = mid -1;
}
else
{
low = mid + 1;
}
}
if(found==0)
{
printf("%d does not exist in the array\n",search);
}
return 0;
}
STRING
• A string consists of any no. of consecutive characters can be represented as a char type array.
The last character is always a null character (\0) which is placed automatically by the
compiler.
• Character arrays or strings are used by programming languages to manipulate text such as words
and sentences.
C does not support strings as a data type. However, it allows to represent strings as character arrays.
The general form of declaration of a string variable is:
char string_variable_name[size];
Examples:
char name[20];
char city[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string.
Character arrays may be initialized when they are declared. C permits a character array to be
initialized in either of the following two forms:
12
C also permit to initialize a character array without specifying the size of the array. In such cases, the
size of the array will be determined automatically, based on the number of elements initialized. For
example,
• The scanf() function can be used with %s format specification to read in a string of characters.
• The problem with the scanf() function is that it terminates its input on the first white space it
finds.
Example:
char name[30];
scanf(“%s”,name);
The getchar() function is used to read a single character from the terminal.
We can use this function repeatedly to read successive single characters from the input and place them
into a character array. The reading is terminated when the newline character (\n) is entered and the
null character is then inserted at the end of the string.
Example:
#include <stdio.h>
int main()
{
char name[50], ch;
int c=0;
printf(“Enter your name : “);
do
{
ch = getchar();
name[c]=ch;
c++;
} while (ch != ‘\n’);
c= c-1;
line[c]=’\0’;
Example:
char name[30];
gets(name);
13
Writing Strings to Screen
The printf() function with %s format specification can be used to print strings to the screen.
Example:
char name[50];
gets(name);
C supports another character handling function putchar() to output the values of character variables.
Example:
char ch=’A’;
putchar(ch);
puts()
Another and more convenient way of printing string values is to use the function puts() declared in
the header file <stdio.h>.
Example:
char name[] = “Anil Kumar”;
puts(name);
EXAMPLE PROGRAMS
#include <stdio.h>
int main()
{
char str[100];
int i=0,length;
printf("Enter the string : ");
gets(str);
while(str[i] != '\0')
{ i++; }
length = i;
printf("The length of the string is : %d\n",length);
return 0;
}
#include <stdio.h>
int main()
{
char str[100],str1[100];
int i=0;
printf("Enter the string : ");
gets(str);
while(str[i] != '\0')
14
{
if(str[i]>='a' && str[i]<='z')
str1[i] = str[i] - 32;
else
str1[i] = str[i];
i++;
}
str1[i]='\0';
printf("The upper case string is : %s\n",str1);
return 0;
}
#include <stdio.h>
int main()
{
char str[100],str1[100];
int i=0;
printf("Enter the string : ");
gets(str);
while(str[i] != '\0')
{
if(str[i]>='A' && str[i]<='Z')
str1[i] = str[i] + 32;
else
str1[i] = str[i];
i++;
}
str1[i]='\0';
printf("The upper case string is : %s\n",str1);
return 0;
}
#include <stdio.h>
int main()
{
char str[100],str1[100];
int i=0,j=0;
printf("Enter the first string : ");
gets(str);
printf("Enter the second string : ");
gets(str1);
while(str[i] != '\0')
{
i++;
}
while(str1[j] !='\0')
{
str[i]=str1[j];
15
i++;
j++;
}
str[i]='\0';
i=0;
while(str1[i] != '\0')
{ i++; }
l2=i;
i=0;
if(l1==l2)
{
while(i<l1)
{
if(str[i] == str1[i])
{ i++; }
else
{ break; }
}
if(i==l1)
{
same=1;
printf("The strings are equal \n");
}
}
if(same == 0)
{
printf("The strings are not equal\n");
if(str[i] > str1[i])
printf("String 1 is greater than String 2 \n");
else
printf("String 1 is less than String 2\n");
}
return 0;
}
16
STRING HANDLING LIBRARY FUNCTIONS
Function Action
strcat() Concatenates two strings
strcmp() Compares two strings
strcpy() Copies one string over another
strlen() Finds the length of a string
1. Strcat() Function
The strcat() function joins two strings together. It takes the following form:
strcat(string1, string2);
Example :
#include <stdio.h>
#include <string.h>
int main()
{
char word1[30] =”GOOD “;
char word2[] =”MORNING”;
strcat(word1, word2);
printf(“word1 = %s\n”,word1);
printf(“word2 = %s\n”,word2);
return 0;
}
Output
2. strcmp() Function
The strcmp() function compares two strings indentified by the arguments and has a value of if they
are equal. If they are not, it has a positive value if the first string is alphabetically above the second
string and a negative value if the first string is alphabetically below the second string. It takes the
form:
strcmp(string1, string2);
17
Eg:
strcmp(name1, name2);
strcmp(name1,”John”);
strcmp(“Rom”, “Ram”);
3. strcpy() Function
The strcpy() function works almost like a string-assignment operator. It takes the following form:
strcpy(string1, string2);
Eg:
strcpy(city, “Delhi”);
strcpy(city1, city2);
strlen() Function
This function counts and returns the number of characters in a string. It takes the form
strlen(string);
Eg:
n=strlen(“Thiruvananthapuram”);
l=strlen(name);
18