Array1
Array1
Data Structures
1
Basic Concept
• Many applications require multiple data
items that have common characteristics.
– In mathematics, we often express such groups
of data items in indexed form:
• x1, x2, x3, …, xn
• Why are arrays essential for some
applications?
– Take an example.
– Finding the minimum of a set of numbers.
2
3 numbers 4 numbers
if ((a <= b) && (a <= c)) if ((a <= b) && (a <= c) && (a <= d))
min = a; min = a;
else else
if (b <= c) if ((b <= c) && (b <= d))
min = b; min = b;
else else
min = c; if (c <= d)
min = c;
else
min = d;
3
The Problem
• Suppose we have 10 numbers to handle.
• Or 20.
• Or 100.
4
Using Arrays
• All the data items constituting the group
share the same name.
int x[10];
X is a 10-element one
dimensional array
5
Declaring Arrays
• Like variables, the arrays that are used in a
program must be declared before they are
used.
• General syntax:
type array-name [size];
– type specifies the type of element that will be
contained in the array (int, float, char, etc.)
– size is an integer constant which indicates the
maximum number of elements that can be stored
inside the array.
int marks[5];
• marks is an array containing a maximum of 5 integers.
6
• Examples:
int x[10];
char line[80];
float points[150];
char name[35];
• If we are not sure of the exact size of the array,
we can define an array of a large size.
int marks[50];
though in a particular run we may only be using,
say, 10 elements.
7
How an array is stored in memory?
• Starting from a given memory location, the
successive array elements are allocated space in
consecutive memory locations.
Array a
x x+k x+2k
• Let
x: starting address of the array in memory
k: number of bytes allocated per array element
– Element a[i] :: allocated memory location at address
x + i*k
• First array index assumed to start at zero.
8
Accessing Array Elements
• A particular element of the array can be accessed
by specifying two things:
– Name of the array.
– Index (relative position) of the element in the array.
• In C, the index of an array starts from zero.
• Example:
– An array is defined as int x[10];
– The first element of the array x can be accessed as
x[0], fourth element as x[3], tenth element as x[9],
etc.
9
Contd.
• The array index must evaluate to an integer
between 0 and n-1 where n is the number of
elements in the array.
a[x+2] = 25;
b[3*x-y] = a[10-x] + 5;
10
A Warning
• In C, while accessing array elements, array
bounds are not checked.
• Example:
int marks[5];
:
:
marks[8] = 75;
– The above assignment would not necessarily cause an
error.
– Rather, it may result in unpredictable program results.
11
Initialization of Arrays
• General form:
type array_name[size] = { list of values };
• Examples:
int marks[5] = {72, 83, 65, 80, 76};
char name[4] = {‘A’, ‘m’, ‘i’, ‘t’};
• Some special cases:
– If the number of values in the list is less than the
number of elements, the remaining elements are
automatically set to zero.
float total[5] = {24.2, -12.5, 35.1};
è total[0]=24.2, total[1]=-12.5, total[2]=35.1,
total[3]=0,
total[4]=0
12
Contd.
– The size may be omitted. In such cases the
compiler automatically allocates enough space for
all initialized elements.
13
Example 1: Find the minimum of a set of 10 numbers
#include <stdio.h>
main()
{
Array
int a[10], i, min;
declaration printf(“Give 10 values \n”);
for (i=0; i<10; i++) Reading
scanf (“%d”, &a[i]); Array Element
min = 99999;
for (i=0; i<10; i++)
{
if (a[i] < min)
Accessing
min = a[i];
} Array Element
printf (“\n Minimum is %d”, min);
}
14
Alternate
#include <stdio.h>
Version 1 #define size 10
main()
{
int a[size], i, min;
printf(“Give 10 values \n”);
for (i=0; i<size; i++)
Change only one scanf (“%d”, &a[i]);
line to change the
problem size min = 99999;
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf (“\n Minimum is %d”, min);
}
15
#include <stdio.h>
Alternate
Version 2 main()
{
int a[100], i, min, n;
17
How to copy the elements of one array to another?
18
How to read the elements of an array?
• By reading them one element at a time
int a[25];
for (j=0; j<25; j++)
scanf (“%d”, &a[j]);
• The ampersand (&) is necessary.
• The elements can be entered all in one line or
in different lines.
19
How to print the elements of an array?
• By printing them one element at a time.
for (j=0; j<25; j++)
printf (“\n %d”, a[j]);
– The elements are printed one per line.
printf (“\n”);
for (j=0; j<25; j++)
printf (“ %d”, a[j]);
– The elements are printed all in one line (starting
with a new line).
20
Example: Matrix Addition
#include <stdio.h> for (p=0; p<m; p++)
for (q=0; q<n; q++)
main() c[p]q] = a[p][q] + b[p][q];
{
int a[100][100], b[100][100], for (p=0; p<m; p++)
c[100][100], p, q, m, n; {
printf (“\n”);
scanf (“%d %d”, &m, &n); for (q=0; q<n; q++)
printf (“%f ”, a[p][q]);
for (p=0; p<m; p++)
for (q=0; q<n; q++) }
scanf (“%d”, &a[p][q]); }
21
Character Strings
22
Introduction
• A string is an array of characters.
–Individual characters are stored in
memory in ASCII code.
–A string is represented as a sequence
of characters terminated by the null
(‘\0’) character.
“Hello” è H e l l o ‘\0’
23
Character Strings
Character vs. String
• A string constant is a sequence of characters
enclosed in double quotes.
– For example, the character string:
char s1[2]="a"; //Takes two bytes of
storage.
s1: a ‘\0’
26 February 2022 28
Reading Words
• scanf with “%s” format:
char name[30];
:
:
scanf (“%s”, name);
– The ampersand (&) is not required before the
string name.
– Point to remember here is that the string is taken
to be upto the first white space (blank, tab,
carriage return, etc.)
• If we type “Rupak Biswas”
• name will be assigned the string “Rupak”
26 February 2022 29
Reading a Line
char line[81];
:
:
scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line);
è Reads a string containing uppercase
characters and blank spaces
char line[81];
:
scanf (“%[^\n]”, line);
char name[50];
:
:
printf (“\n %s”, name);
26 February 2022 31
Processing Character Strings
• C library functions for character string
manipulation.
– strcpy :: string copy
– strlen :: string length
– strcmp :: string comparison
– strtcat :: string concatenation
• It is required to include the following
#include <string.h>
26 February 2022 32
strcpy()
• Works very much like a string assignment
operator.
strcpy (string1, string2);
– Assigns the contents of string2 to string1.
• Examples:
strcpy (city, “Hamirpur”);
strcpy (city, mycity);
• Warning:
– Assignment operator does not work for
strings.
city = “Hamirpur”; è INVALID
26 February 2022 33
strlen()
• Counts and returns the number of
characters in a string.
len = strlen (string); /* Returns an integer
*/
n is assigned 8
26 February 2022 35