Nothing Special   »   [go: up one dir, main page]

Array

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

ARRAYS

Array refers to a collection of same kind of data items.


or
An array is a fixed-sized sequenced collection of elements of the same data type that share a common
name. An array can be used to represent a list of numbers, or a list of names.
Features of arrays:
1. Array stores similar data types.
2. Contiguous (continuous) memory is allocated for the elements.
3. All the elements can be accessed with their index numbers where the first array element gets
0 index by default and the second element gets 1 and so on.
4. Last index of array element is size of array-1
5. Accessing elements with their index number is very fast (have greater performance).
6. Once array is created, its size is fixed. That is, at runtime its size cannot be changed.
7. C supports single and multi-dimensional arrays.

One dimensional arrays


Explanation:
To store total mark of a student in a class, we can use an integer variable,
int mark;
But if we need to store total mark of 50 students in a class, it is difficult to use 50 integer variables.
For this an integer array mark is used. int mark[50];
Thus, ordinary variables are capable of holding only one value at a time.
However, there are situations in which we would want to store more than one value at a time in a
single variable. Arrays are used for this.

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

number[0] number[1] number[2] number[3] number[4]

The values to the array elements can be


assignmed as follows:
number[0] = 45;
number[1] = 35;
number[2] = 25;
number[3] = 50;
number[4] = 9;

1
Initialization of one-dimensional arrays

An array can be initialized while declaring it. The general form of initialization of arrays is:

data-type array-name[size] = { list of values };

The values in the list are separated by commas.

Following are a few examples that demonstrate this.


1. int num[6] = { 2, 4, 12, 5, 45, 5 } ;
2. int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
• The size may be omitted. In such cases, the compiler allocates enough space for all
initialized elements.

3. float temperature[5] = {31.5, 29.7, 30.7};


• If the number of values in the list is less than the size of array, then only that many elements
will be initialized. The remaining elements will be set to zero automatically.

Character arrays
• Character arrays may be initialized in a similar manner;

char name[ ] = { ‘J’, ‘o’, ‘h’, ‘n’, ‘\0’};

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

• Alternatively, we can assign the string directly as follows:

char name [ ] = “John”;

Accessing Array Elements

•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[].

printf (“%d”, age[3]);

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

Reading Data from an Array


Suppose we want to find the average of marks of all students

for ( i = 0 ; i <= 29 ; i++ )


{
sum = sum + marks[i] ;
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;

Passing One-dimensional arrays to functions

• 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;
}

float average(float a[])


{
int i;
float avg, sum=0.0;
for(i=0;i<6;++i)
{
sum+=a[i];
}
avg =(sum/6);
return avg;
}

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.

The general syntax for declaring a two-dimensional array is as follows:

data-type array_name [rows] [columns];

Example:
int marks[4][3];

Initialization of two-dimensional arrays

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

Conceptually, the array arrangement can be shown as follows:

Passing two-dimensional arrays to Functions

The rules for passing two-dimensional array to a user-defined function are:

1. The function must be called by passing only the array name.


2. In the function definition, we must indicate that the array has two-dimensions by including
two set of brackets.
3. The size of the second dimension must be specified.
4. The prototype declaration (function declaration) should be similar to the function header.

Example Program : Program to read and display matrix using user-defined functions.

#include <stdio.h>

void read_mat(int a[][10],int,int);


void print_mat(int a[][10],int,int);
int main()

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

void read_mat(int a[][10],int x,int y)


{
int i,j;
printf("Enter the matrix elements : \n");
for(i=0;i<x;i++)
for(j=0;j<y;j++)
scanf("%d",&a[i][j]);
}

void print_mat(int a[][10],int x,int y)


{
int i,j;
printf("The given matrix is : \n");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}

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.

Working of Selection Sort

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.

Note:Video link is given below


(24) Selection Sort Algorithm and C program | Malayalam tutorial - YouTube

Selection Sort Program

#include <stdio.h>
int main()
{
int a[100],i,j,min_indx,n;
printf("Enter the number of elements to enter : ");
scanf("%d",&n);

/*Reading array elements */

printf("Enter %d numbers :\n",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;
}
}

/* Printing Sorted Array */

printf("The sorted array is :\n");


for(i=0;i<n;i++)
printf("%d\n",a[i]);

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

void quicksort(int number[],int first,int last)


{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(number[i]<=number[pivot] && i < last)
i++;
while(number[j]>number[pivot] && j > first)
j--;
if(i<j)
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}

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;

printf("Enter the number of elements : ");


scanf("%d",&n);
printf("Enter %d numbers :\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to search : ");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(a[i]==search)
{
found=1;
printf("%d is found in the array at position = %d\n",search,i+1);
break;
}
}
if(found==0)
{
printf("%d does not exist in the array\n",search);
}
return 0;
}
----------------------------------------------------------------------------------------
BINARY SEARCH

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;

printf("Enter the number of elements : ");


scanf("%d",&n);

/* Reading array elements */

printf("Enter %d numbers :\n",n);


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
/* Sorting Array */

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

/* Printing Sorted array */

printf("The sorted array is :\n");


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

/*Reading search element */

printf("Enter the element to search : ");


scanf("%d",&search);

/*Binary Search */

low=0;
high=n-1;

while(low <= high)


{
mid = (low + high)/2;

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.

• (Strings-special kind of array consists of group of characters.)

• Character arrays or strings are used by programming languages to manipulate text such as words
and sentences.

DECLARING AND INITIALIZING STRING VARIABLES

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:

char name[30] =”Aravind P”;

char city[30] = { ‘D’, ’E’, ’L’, ’H’, ’I’, ’\0’ };

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,

char city[ ] = “Thiruvananthapuram”;

char name[ ] = {‘A’, ‘N’, ‘I’, ‘L’, ‘\0’};

Reading Strings from Terminal

• 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’;

printf(“Your name is %s\n”,name);


return 0;
}
gets() function
Another and more convenient method of reading a string of text containing whitespaces is to use the
library function gets() available in the <stdio.h> header file.

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

printf(“Your name is %s “, 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

1. Program to find the length of a string.

#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;
}

2. Program to convert characters of a string to upper case.

#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;
}

3. Program to convert characters of a string to lower case.

#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;
}

4. Program to append (concatnation) a string to another string.

#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';

printf("After concatnation, the string is : %s\n",str);


return 0;
}

5. Program to compare two strings


#include <stdio.h>
int main()
{
char str[100],str1[100];
int i=0,j=0,l1,l2,same=0;
printf("Enter the first string : ");
gets(str);
printf("Enter the second string : ");
gets(str1);
while(str[i] != '\0')
{ i++; }
l1=i;

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

Following are the most commonly used string handling 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);

string1 and string2 are character arrays.


• When the function strcat() is executed, string2 is appended to string1. It does so by removing
the null character at the end of string1 and placing string2 from there. The string at string2
remains unchanged.

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

word1 = GOOD MORNING


word2 = MORNING

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

string1 and string2 may be string variables or constants.

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

and assigns the contents of string2 to string1.

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

You might also like