Documente Academic
Documente Profesional
Documente Cultură
Course Description:
This course is aimed at enabling the students to
Total 100%
Lecture Notes
UNIT II
ARRAYS AND STRINGS
Learning Objectives
• Practicing the array concept to solve the
problems
• Memory allocation for 1D, 2D ...arrays
• Know about the storage of strings.
• Practicing how to deal with strings.
Arrays in C
int studmark[1000]
ARRAYS
By using an array, we just declare like this,
int studMark[1000];
This will reserve 1000 contiguous memory locations for storing the
students’ marks.
Graphically, this can be depicted as in the following figure.
ARRAYS
Simplified our declaration of the variables.
Use index or subscript to identify each element
For example, studMark[0] will refer to the first element of
the array.
Subscrpits varies from 0 to number of items in the array -1
In an array declaration int a[10] will hold 10 integer data
items/ values and can be accessed using a[0]…a[9].
a is known as base address. Address of the first item in an
array.
Address of second item is a+1; here a+1 will be
automatically incremented depending on the data type of
the array.
Note: Not to change the base address in the program ie. a.
ARRAYS
One Dimensional Array: Declaration
array_element_data_type array_name[array_size];
int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];
The first example declares two arrays named xNum and yNum of type int.
Array xNum can store up to 20 integer numbers while yNum can store up to
50 numbers.
The second line declares the array fPrice of type float. It can store up to 10
floating-point values.
fYield is basic variable which shows array type can be declared together
with basic type provided the type is similar.
The third line declares the array chLetter of type char. It can store a string
with up to 69 characters.
Why 69 instead of 70? Remember, a string has a null terminating character
(\0) at the end, so we must reserve for it.
ARRAYS
Array Initialization
An array may be initialized at the time of declaration.
Giving initial values to an array.
Initialization of an array may take the following form:
type array_name[size] = {a_list_of_value};
For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7}; // idNum[0]=1, idNum[1]=2
int a[4] = { 1,2}; // a[0]=1,a[1]=2,a[2]=0,a[3]=0
float ft[3] = {5.6, 5.7, 5.8};// 5.6 to ft [0], 5.7 to ft[1]
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};
Assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so
on. Note again, for characters we must use the single
apostrophe/quote (') to enclose them.
Also, the last character in chVowel is NULL character ('\0').
ARRAYS
Initialization of an array of type char for holding strings
may take the following form,
char array_name[size] = "string_literal_constant";
for (count=0;rc!=EOF;count++)
rc=scanf("%f", &A[count]);
Caution! Caution! Caution!
• It is the programmer’s responsibility to avoid
indexing off the end of an array
• Likely to corrupt data
• May cause a segmentation fault
• Could expose system to a security vulnerability!
• C does NOT check array bounds
• I.e., whether index points to an element within the
array
• Might be high (beyond the end) or negative (before the
array starts)
ARRAYS
Two Dimensional/2D Arrays
For examples,
int xInteger[3][4];
float matrixNum[20][25];
The first line declares xInteger as an integer array with 3 rows and 4
columns.
Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
ARRAYS
If we assign initial string values for the 2D array it will look
something like the following,
char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole",
"Kidman", "Arnold", "Jodie"};
For example,
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
Arrays Address = 1000
1 2 3
• int a[2][3] = { 1,2,3,4,5,6}; 4 5 6
stack
(dynamically allocated)
SP
Static
array
when s allo
progr cated h
a m is ere
loade
d.
heap
address space (dynamically allocated)
static data
program code PC
(text)
0x00000000
Data Allocation
Auto
matic
here arra
upon ys alloca
block entry ted
.
0xFFFFFFFF
to
stack
(dynamically allocated)
SP
heap
address space (dynamically allocated)
static data
program code PC
(text)
0x00000000
Dynamic Array Size Determination
• gcc supports the following:–
void func(<other parameters>, const int n) {
double Arr[2*n];
} //func
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Column subscript
Array name
Row subscript
Multiple-Subscripted Arrays
• Initialization 1
3
2
4
– int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
– Initializers grouped by row in braces
– If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
• Referencing elements 1
3
0
4
– Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
MULTIDIMENSIONAL ARRAY
1 /*
2 Double-subscripted array example */
3 #include <stdio.h>
4 #define STUDENTS 3
5 #define EXAMS 4 1. Initialize
6 variables
7 int minimum( const int [][ EXAMS ], int, int );
8 int maximum( const int [][ EXAMS ], int, int );
9 double average( const int [], int );
1.1 Define
10 void printArray( const int [][ EXAMS ], int, int ); functions to take
Each row is a particular
double scripted
11
12 int main()
student, each column is the
arrays
13 { grades on the exam.
14 int student;
15 const int studentGrades[ STUDENTS ][ EXAMS ] =
16 { { 77, 68, 86, 73 },
17 { 96, 87, 89, 78 },
18 { 70, 90, 86, 81 } };
19
1.2 Initialize
20 printf( "The array is:\n" ); studentgrades[][]
21 printArray( studentGrades, STUDENTS, EXAMS );
22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",
2. Call functions
23 minimum( studentGrades, STUDENTS, EXAMS ),
24 maximum( studentGrades, STUDENTS, EXAMS ) );
minimum, maximum,
25 and average
26 for ( student = 0; student <= STUDENTS - 1; student++ )
27 printf( "The average grade for student %d is %.2f\n",
28 student,
29 average( studentGrades[ student ], EXAMS ) );
30
31 return 0;
32 }
33
34 /* Find the minimum grade */
35 int minimum( const int grades[][ EXAMS ],
36 int pupils, int tests )
37 { 3. Define functions
38 int i, j, lowGrade = 100;
39
40 for ( i = 0; i <= pupils - 1; i++ )
41 for ( j = 0; j <= tests - 1; j++ )
42 if ( grades[ i ][ j ] < lowGrade )
43 lowGrade = grades[ i ][ j ];
44
45 return lowGrade;
46 }
47
48 /* Find the maximum grade */
49 int maximum( const int grades[][ EXAMS ],
50 int pupils, int tests )
51 {
52 int i, j, highGrade = 0;
53
54 for ( i = 0; i <= pupils - 1; i++ )
55 for ( j = 0; j <= tests - 1; j++ )
56 if ( grades[ i ][ j ] > highGrade )
57 highGrade = grades[ i ][ j ];
58
59 return highGrade;
60 }
61
62 /* Determine the average grade for a particular exam */
63 double average( const int setOfGrades[], int tests )
64 {
65 int i, total = 0;
66
67 for ( i = 0; i <= tests - 1; i++ )
68 total += setOfGrades[ i ];
69 3. Define functions
70 return ( double ) total / tests;
71 }
72
73 /* Print the array */
74 void printArray( const int grades[][ EXAMS ],
75 int pupils, int tests )
76 {
77 int i, j;
78
79 printf( " [0] [1] [2] [3]" );
80
81 for ( i = 0; i <= pupils - 1; i++ ) {
82 printf( "\nstudentGrades[%d] ", i );
83
84 for ( j = 0; j <= tests - 1; j++ )
85 printf( "%-5d", grades[ i ][ j ] );
86 }
87 }
The array is:
[0] [1] [2] [3]
studentGrades[0] 77 68 86 73
studentGrades[1] 96 87 89 78
Program Output
studentGrades[2] 70 90 86 81
Lowest grade: 68
Highest grade: 96
The average grade for student 0 is 76.00
The average grade for student 1 is 87.50
The average grade for student 2 is 81.75
Arrays and Matrices in C
– int matrix[3][4]; 1
0
Row 0 4 1 0 2 2
-1
Row 1 -1 2 4 3 2
4
Row 2 0 -1 3 1 3
0
-1
3
54
Accessing Array Elements
int matrix[3][4];
• matrix has 12 integer elements
• matrix[0][0] element in first row, first
column
• matrix[2][3] element in last row, last
column
• matrix is the address of the first element
• matrix[1] is the address of the Row 1
• matrix[1] is a one dimensional array (Row
55
1)
Initialization
int x[4][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
int x[][4] = { {2, 3, 7, 2},
{7, 4, 5, 9},
{5, 1, 6, -3},
{2, 5, -1, 3}};
56
Initialization
int i, j, matrix[3][4];
for (i=0; i<3; i++)
for (j=0; j<4; j++)
matrix[i][j] = i;
matrix[i][j] = j;
j
j
0 1 2 3 0 1 2 3
0 0 0 0 0
0 0 1 2 3
i 1 1 1 1
1 i 0 1 2 3
1
2 2 2 2 2
2 0 1 2 3
57
Exercise
• Write the nested loop to initialize a 2D array
as follow
0 1 2 int i, j, x[4][3];
1 2 3 for(i=0; i<4; i++)
2 3 4 for(j=0; j<3; j++)
3 4 5 x[i][j] = i+j;
58
2-Dim Arrays as Arguments to Functions
59
Computations on 2D arrays
60
Max in 2D
• Find the maximum of (positive)
int matrix[3][4]
61
Find a value in 2D
int count = 0; 0 1 2 3
0 0 1 0 2
for (i=0; i<3; i++)
for (j=0; j<4; j++) 1 -1 2 4 3
if (matrix[i][j] == x) 2 0 -1 3 1
count = count + 1;
62
Matrix sum
63
solution
int matrix1[3][4],
matrix2[3][4],
sum[3][4];
// initialize matrix1 and matrix2
64
Transpose
void transpose(int a[NROWS][NCOLS],
int b[NCOLS][NROWS])
{
a /* Declare Variables. */
1 5 3 int i, j;
4 2 6
/* Transfer values to the
transpose matrix. */
b for(i=0; i<NROWS; i++) {
1 4 for(j=0; j<NCOLS; j++) {
b[j][i] = a[i][j];
5 2 }
}
3 6 return;
}
65
Matrix multiplication
double a[3][2], b[2][4], c[3][4];
• Find c = a * b;
• a= 1 2 3
4 5 6
• b= 4 5
6 7
8 9
j
j 0 1 2 3
0 1 2 3 22 29 45 35
0 3 4 2 3 7 1
0
1 5 2 x = 1 18 40 47 21
4 5 6 8 2
2 1 6 26 33 43 49
i i
j=0
c[i][j] =
2
i=0 3 4 x k = a[i][k=0]*b[k=0][j] +
4 a[i][k=1]*b[k=1][j]
k
67
Matrix Multiplication cont’d
#define N 3
#define M 2
#define L 4
void matrix_mul(a[N][M], int b[M][L], int c[N][L])
{
int i, j, k;
for(i=0; i < N; i++) {
for(j=0; j < L; j++) {
c[i][j] = 0;
for(k=0; k < M; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return;
}
68
Strings in C
• When declaring a string don’t forget to leave a space for the null
character which is also known as the string terminator character
C offers four main operations on strings
• For example
• strcpy(str, “hello world”); assigns “hello world”
to the string str, where str is the character
array or character pointer.
Example with strcpy
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “Example with strcpy”;
char y[25];
printf(“The string in array x is %s \n “, x);
strcpy(y,x);
printf(“The string in array y is %s \n “, y);
}
strcat
• strcat(destinationstring, sourcestring)
}
strcmp
• strcmp(stringa, stringb)
s1 = Happy
s2 = New Year
strcat( s1, s2 ) = Happy New Year
strncat( s3, s1, 6 ) = Happy
strcat( s3, s1 ) = Happy Happy New Year
strcmp() vs strncmp()
int strcmp( const char *s1, const char *s2 );
– Compares string s1 to s2
– Returns a negative number if s1 < s2, zero if s1
== s2 or a positive number if s1 > s2
int strncmp( const char *s1, const char *s2, size_t n );
}
Vowels Example with strlen
#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘a’)||(x[i]==‘e’)||(x[i]==‘i’)||(x[i]==‘o’)||(x[i]==‘u’)) count++;
}
printf(“The number of vowels’s in %s is %d \n “, x,count);
}
No of Words Example with strlen
#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘ ‘) count++;
}
printf(“The number of words’s in %s is %d \n “, x,count+1);
}
No of Words Example with more than one space
between words
#include <stdio.h>
#include <string.h>
main()
{
int i,j, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if ((x[i] == ‘ ‘)
{ count++;
for(j=i;x[j] != ‘ ‘;j++);
i = j;
}
}
printf(“The number of words’s in %s is %d \n “, x,count+1);
}
Input output functions of characters and strings
Output
1
12
123
1234
………….
1 2 3 4 5 6 7 8 9 10
Exercise 1
#include <stdio.h>
main()
{
int i,j;
for(j = 1; j <= 10; j++)
{
for(i=1;i <= j;i++)
{
printf(“%d “,i);
}
printf(“\n“);
}
}
Exercise 2
Output
*
**
***
****
…………….
**********
Exercise 2
#include <stdio.h>
main()
{
int i,j;
for(j = 1; j <= 10; j++)
{
for(i=1;i <= j;i++)
{
printf(“* “);
}
printf(“\n“);
}
}
Some Useful C Character Functions
while (fgets(buffer,sizeof(buffer)-1,instream)
!= NULL)
fputs(buffer,stdout);
fclose(instream);
}
Printing to a String
The sprintf function allows us to print to a string
argument using printf formatting rules
First argument of sprintf is string to print to,
remaining arguments are as in printf
Example:
char buffer[100];
sprintf(buffer,”%s, %s”,LastName,FirstName);
if (strlen(buffer) > 15)
printf(“Long name %s %s\n”,FirstName,LastName);
Reading from a String
The sscanf function allows us to read from a
string argument using scanf rules
First argument of sscanf is string to read from,
remaining arguments are as in scanf
Example:
char buffer[100] = “A10 50.0”;
sscanf(buffer,”%c%d%f”,&ch,&inum,&fnum);
/* puts ‘A’ in ch, 10 in inum and 50.0 in fnum */
Array of Strings
• Sometimes useful to have an array of string
values
• Each string could be of different length
• Example:
char *MonthNames[13]; /* an array of 13 strings */
MonthNames[1] = “January”; // String with 8 chars
MonthNames[2] = “February”; // String with 9 chars
MonthNames[3] = “March”; // String with 6 chars
etc.
Array of Strings Example
#include <stdio.h>
void main() {
char *days[7];
char TheDay[10];
int day;
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";