Module 3 Notes Arrays
Module 3 Notes Arrays
Arrays
One Dimensional Array
1. WHY DO WE NEED ARRAYS?
Say we have a problem in our hand to store marks scored by 50 students in C language subject. To
store 50 marks we have to declare 50 variables of integer data type as shown below:
int marks_1, marks_2, marks_3, marks_4… .................... marks_50;
Now suppose we have to store values into these variables then 50 scanf statements or initializing 50
values has to be done as shown:
scanf(“%d”, &marks_1);
scanf(“%d”, &marks_2);
scanf(“%d”, &marks_3);
scanf(“%d”, &marks_50);
OR
marks_1=25;
marks_2=23;
marks_3=20;
…………. So on marks_50=21;
This style of programming is fine for a small set of values. But if we have to store 1000 or
10000 values declaring so many variables is a cumbersome process. Alternative solution is Arrays!
2. DEFINITION OF ARRAYS
3. TYPES OF ARRAYS
I. One-Dimensional Arrays: A list of items can be given one variable name using
only one subscript and such a variable is called a single subscripted variable or one
dimensional array.
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[5]={29.5, 30.7, 35.6, 45.7, 19.5};
b) Initialization without size: We needn’t have to specify the size of array provided
we are initializing the values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Initializing all the elements zero: If we want to store zero to all the elements
in the array we can do.
Examples: int marks[4]={0};
float temperature[5]={0};
Accessing the array elements: Accessing the array element is done using a loop
statement in combination with printf statements or any other processing statements.
Example of accessing the array elements and calculating total marks is given below:
Example: void
main( )
{
int total=0,
marks[4]={35,44,55,67};
PSP NOTES,MODULE 3 PALLAVI K N
for(i=0; i<4; i++)
total=total+marks[i]; /* calculating total
marks*/ printf(“Total marks=%d”,total);
}
Output: Total marks=201
USING ARRAYS WITH FUNCTIONS:
In large programs that use functions we can pass Arrays as parameters. Two ways of
passing arrays to functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter
Let us take an example program that uses a function square( ) to calculate square of
numbers stored in an array. In this program each array element is passed one by one.
Example-1
Example-1 cont’d:
int square(int);
void main( ) void square(int no )
{ {
}
{
square(num[i]);
} Output:
3 4 8 9 10
0 1 2 num[3]=9→ no
3 4
num[1]=4 copied → no
num[0]=3 copied to no
num[2]=8→ no
avg1=average(marks); sum=sum+score[i];
printf(“average=%f”, avg1) }
} avg=sum/5;
return (avg);
Output:
average=71.000000
71.000000
II. Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
array.
1 2 3 4
marks 5 6 7 8
9 10 11 12
29.5 30.7
city_temper
35.6 45.7
2. Run time initialization: Run time initialization is storing values in an arraywhen program is
running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example:
for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}
012 1234
345 b 5678
a
67 8 9 10 11 12
Selection Sort
Selection sort will start by comparing the first element with other elements and finds
minimum element and swaps, then it starts comparing by taking second element with
other elements and so on.
void main( )
{
int a[100],i,j,n,temp,pos;
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
SEARCHING: It is the process of finding the location of the specified element in a list.
➢ The specified element is often called the search key.
➢ If it is found search is successful, otherwise it is unsuccessful.
Ex: Binary Search, Linear Search/Sequential Search.
Linear Search
Linear search is a very basic and simple search algorithm. In Linear search, we search
an element or value in a given array by traversing the array from the starting, till the
desired element or value is found.
Binary Search
Binary search works only on a sorted set of elements. To use binary search on a
collection, the collection must first be sorted. The array is divided into two parts,
compared with middle element if it is not successful, then it is compared whether it is
lesser or greater than middle element. If it is lesser, search is done towards left part else
right part.
A N A G H A \0 Delimiter
‘\0’ indicates
0 1 2 3 4 5 6
end of string
Size 21 means it can store up to 20 characters plus the null character. Entire storage location name is
divided in to 21 boxes called bytes, each of which holds one character. Each character is element of
data type char.
Difference between a single character string and a single character array is:
Single character array takes 1 byte whereas single character string occupies two bytes as shown below:
‘A’ 25
Limitations of Strings: One string variable cannot be directly assigned to another string as in the case
of ordinary scalar variables.
Let us say int a=10, b;
b=a; /* is perfectly valid */
But take an example of string initialization:
char name1[ ] = “hello”;
char name2[10 ];
name2=name1; /* This initialization is invalid */
But this initialization can be done using a loop and assigning individual characters ofname1 to name2
as shown below:
M A N
Prints first 3 characters but in left
justified manner because of (- ) sign
Disadvantage of reading strings using scanf( ) function is multiple words strings cannot
be read. For example say we have to read NEW DELHI, following scanf( ) reads only
NEW and stops.
scanf(“%s”,
name); say
N E W D E L H I
input is
Only part of a string (NEW) is read and second half (DELHI) is ignored.
N E W
Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion
code %[ ], which specifies the type of characters that can be accepted by scanf ( )
function.
For Example say we have to accept only 0-9 digits in a string then edit set code can
be used as follows:
char name[20];
scanf(“%[0123456789]”, name)
NOTE: Suppose we want to skip particular set of characters in a string, then we have
to use:
^ symbol in edit set conversion code. Following example illustrates same:
PSP NOTES,MODULE 3 PALLAVI K N
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)
C library supports a large number of string handling functions that can be used to
carry out many of the string manipulations and are stored in header file “string.h”.
Following are the most commonly used string handling functions.
1. strcpy( ) copies one string over another
2. strlen( ) finds the length of a string
3. strcmp( ) compare two strings
4. strcat( ) concatenates two strings
5. strcpy( ) copies left most n characters of source to destination
6. strcmp( ) compares left most of n characters of source to destination.
Strcpy does not check to see whether there is room for the resulting string at the specified
location. If there is no room, it copies characters on top of whatever variables follow in
memory. This may destroy the contents of other variables.
1. strlen():the string length function can be used to find the length of the string in
bytes. It takes the form
length=strlen(str);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”KSIT”
lenth=strlen(str); //4
str=’\0’
length=strlen(str); //0
2. strcmp( ): A strcmp() is used to compare two strings. It takes the two strings as
a parameter and returns an integer value based on the relationship between two strings.
General form of call to strcmp()
3. strcat( ): often it is useful to concatenate or join two strings together. The strcat
function is used to join two strings together. The resulting string has only one null
character at the end.
General form of a call to
strcat( )
strcat(first, second);
After the call, first contains all the characters from first, followed by the ones from
second up to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it doesn’t
find a null character, strcat continues copying bytes from memory until it finds null
character. The programmer must check to make sure that the resulting string fits in the
variable.
3. strncpy( ): The strncpy function allows us to extract a substring from one string
and copy it to another location.
General form of call to strncpy
strncpy(dest, source, numchars);
The strncpy function takes three parameters. Here this statement copies the numchars of
the source string in to dest string. Since numchar does not include null character , we
have to place it explicitly in the source string.
Ex: char source[20]=”computer
world”; char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com
Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: Char name[size1][size2];
PROGRAMS
1. WACP to read N integers into an array A and to
i. Find the sum of odd numbers.
ii. Find the sum of even numbers.
iii. Find the average of all numbers.
Output the results compared with appropriate headings.
2. Program to read and write the elements of one dimensional array
3. Program to read and write the elements of two dimensional arrays
4. Program to count number of odd numbers and even numbers in an array
5. C program to find largest element in the two dimensional array.
6. Write a C program to concatenate two strings without using build in function
strcat.