This document provides an overview of arrays and strings in C programming. It discusses initializing and declaring arrays of different types, including multidimensional arrays. It also covers passing arrays as arguments to functions. For strings, it explains that strings are arrays of characters that are null-terminated. It provides examples of declaring and initializing string variables, and using string input/output functions like scanf() and printf().
3. Arrays
In C programming, one of the frequently problem
is to handle similar types of data. For example: if
the user wants to store marks of 500 students,
this can be done by creating 500 variables
individually but, this is rather tedious and
impracticable. These types of problem can be
handled in C programming using arrays.
4. Arrays
• Array is a sequence of data item of homogeneous values
(same type) referred to by a common name. Marks of 500
students, number of chairs in university, salaries of 300
employees or ages of 250 students are few examples of
collection of data elements having the same data type.
• The
values in an array can be
of any type like int, float, double, char etc.
scores
: 85 92576880
name
: ‘C’ ‘Y’‘D’
‘E’
79
‘L’
5. Declaring Arrays
• Syntax: data_type array_name
[constant];
• Note declaration from our example
Tells how many elements set aside
6. Declaring Arrays
• Example specifies an array…
– each element is an integer
– there is space for 100 elements
– they are numbered 0 through 99. Note: Index starts at 0
7. 98 99
Accessing Individual Components
• Use the name of the array
• Followed by an integer expression inside the
square brackets [ ]
scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5
8. scores : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
Index can be: max = scores[0]; - constant for (x
= 0; x < 100; x++)
- variable if (scores[x] > max) - expression
max = scores[x];
MUST be an integer
Arrays: Example
#include<stdio.h>
#include<conio.h>
9. int main()
{ age[0]
int age[3], j;
age[0] = 25; age[1] age[1] = 30; age[2] = 35;
for (j=0; j<3; j++) age[2] printf(“%dn”,
age[j]); getch(); }
Arrays:
Example
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
25
30
35
10. #include<conio.h>
int main() int main()
{
{
int age[3], j; int age[3], i, j;
age[0] = 25; for (i = 0; i<3; i++) {
age[1] = 30; printf(“Enter ages n”);
age[2] = 35; scanf(“%d”, &age[i]) ; }
for (j=0; j<3; j++) for (j=0; j<3; j++)
printf(“%dn”, age[j]); printf(“%dn”, age[j]);
getch(); } getch(); }
11. Out of Bounds Index
• What happens if … float age [3];
age [5] = 123.456;
• C++ does NOT check for index out of range
• Possible to walk off into “far reaches” of memory
-- clobbers ...
– other variable locations
– .exe code
– the operating system (??)
13. Arrays: Class Exercise
Write a C++ program
using arrays that
accepts five (05)
integers and then
prints them in reverse
order.
#include<stdio.h>
#include<conio.h>
int main()
{ int age[5], i,
j;
printf(“Enter numbers: n”);
for (i = 0; i<5; i++) {
scanf(“%d”, &age[i]) ; }
14. for (j=4; j>=0; j--)
printf(“%dn”, age[j]);
getch(); }
Initializing Arrays in Declarations
• Possible to declare the size & initialize int
results [5] = {14, 6, 23, 8, 12 }
• Possible to omit size at declaration
15. – Compiler figures out size of array
float prices [ ] = { 2.41, 85.06, 19.95, 3.91
}
Arrays Initialization: Example
#include<stdio.h>
#include<conio.h>
int main()
{
int age[3] = {25, 30, 35};
int j;
for (j=0; j<3; j++)
printf(“%dn”, age[j]);
getch(); }
18. 2-Dimensional Arrays
• A collection of a fixed number of components
arranged in two dimensions
– All components are of the same type
• The syntax for declaring a two-dimensional array
is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding
positive integer values; e.g., double sales[10][5]
19. 2-Dimensional Arrays
• The two expressions intexp1 and intexp2 specify the
number of rows and the number of columns,
respectively, in the array
• Two-dimensional arrays are sometimes called matrices or
tables
21. 2-Dimensional Arrays
• The syntax to access a component of a
twodimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer values
• indexexp1 specifies the row position and
indexexp2 specifies the column position
sales[2][3] = 35.60;
23. 2-Dimensional Arrays Accessing
• Accessing all of the elements of a two-dimensional array
requires two loops: one for the row, and one for the
column.
• Since two-dimensional arrays are typically accessed row
by row, generally the row index is used as the outer loop.
for (nRow = 0; nRow < nNumRows; nRow++)
for (nCol = 0; nCol < nNumCols; nCol++)
cout << anArray[nRow][nCol];
24. 2 DIM. Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{
double sales[2][3];
//complete program by
//printing the values
which look like this:
sales[0][0] = 2.3;
sales[0][1] = 3.5;
sales[0][2] = 4.2;
sales[1][0] = 5.6;
sales[1][1] = 6.7;
26. sales[1][0] = 5.6; sales[1][1] =
6.7; sales[1][2] = 7.8;
2-Dimensional
Arrays Initialization
• Like one-dimensional arrays
– Two-dimensional arrays can be initialized when they are
declared
• To initialize a two-dimensional array when it is declared
1) Elements of each row are enclosed within braces and
separated by commas
2) All rows are enclosed within braces
27. 3) For number arrays, if all components of a row are not
specified, the unspecified components are initialized to
zero
2-Dimensional Arrays Initialization
• Example:
int anArray[3][5] =
{
{ 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, //
row 1 { 11, 12, 13, 14, 15 } // row 2
};
28. 2 DIM. Arrays: Example
#include<stdio.h>
#include<conio.h>
int main()
{ int i, j;
int matrix[2][2] = {
{2,3,}, //row0
{5,7} //row1
};
printf(“n Resultant: n“);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
{
printf(" %d”, matrix[i][j]);
}
printf("n“);
}
getch();
}
29. 2 DIM. Arrays: Class Exercise
Write a C program using 2 DIM. array that
gets 2x2 matrix input from the user and then
prints the resultant matrix. The output should
look like this:
30. 2 DIM. Arrays: Exercise Solution
#include<stdio.h>
#include<conio.h>
int main()
{
int matrix[2][2], i, j;
for(i = 0; i < 2; i++)
{
for(j = 0; j < 2; j++)
33. Write a C program
using 2 DIM. array that
gets two 2x2 matrices as
an input from the user
and then prints the sum
of entered matrices. The
output should look like
this:
34. 2 DIM. Arrays: Exercise
Solution
int main()
{
int mat1[2][2]; int
mat2[2][2]; int mat[2][2];
//resultant int i, j, k, l;
printf("n 1st Matrix: n n“);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &mat1[i][j]);
}
}
printf("n 2nd Matrix: n n“);
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf(“%d”, &mat2[i][j]);
35. }
}
printf("n Resultant: n“);
for(k=0; k<2; k++)
{
for(l=0; l<2; l++)
{
mat[k][l]=(mat1[k][l] + mat2[k][l]);
printf(“ %d ”, mat[k][l]);
}
printf("n“);
}
getch();
}
2 DIM. Arrays: Assignment
1) Write a C program using arrays that
produces the multiplication of two 2x2
matrices.
36. 2) Write a C program using arrays that gives
the following output:
Multidimensional Arrays
• A collection of a fixed number of elements (called
components) arranged in n dimensions (n >= 1)
• Also called an n-dimensional array
37. • General syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … are constant expressions
yielding positive integer values
Example: 3-Dimensional array:
int table[3][2][4];
40. Arrays as Parameters
• This is one task that CAN be done to the WHOLE array
• C always passes arrays by reference
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf (“%d”, &list[index]); }
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
41. Arrays as Parameters
• The name of the array is a pointer constant
• The address of the array is passed to the function
• Size of the
array also
passed to
control loop
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf }“%d”, &list[index]);(
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
42. Arrays as Parameters
• Note the empty brackets in parameter list
– A number can be placed here but it will be ignored
for (index = 0; index < how_many; index++)
{ printf (“Enter score %d ”, index);
scanf ( }“%d”, &list[index]);
printf (“Enter how many students”);
scanf (“%d”, &num_students); }
43. Passing Arrays to Functions
#include<stdio.h>
#include<conio.h>
int sum(int list[], int listSize)
{
int index, sum = 0; for(index=0;
index<listSize; index++) sum =
sum + list[index]; return sum; }
int main()
{ int myArray[] = {2, 3, 5};
printf( "The sum is: %d ”, sum(myArray, 3));
getch(); }
44. Home Work
Write a program of that sorts the numbers
you type in. The array may be able to get
input until you enter 0. Sample output:
45.
46. C-String OR Character-Arrays
• We have learned that the elements of an array
can be just about anything int, char, double etc.
• Consider an array whose elements are all
characters
• Such type of an array is called a C-String
• In C language, a string is not a formal data type as
it is in some languages (e.g., Pascal and Basic).
Instead, String is an array of type Char.
47. C-Strings OR Character Arrays
• Character array: An array whose components are
of type char
• String: A sequence of zero or more characters
enclosed in double quote marks (e.g., “hello”)
• Internally (by the compiler) C-stings are
terminated with null (‘0’) in memory
» (the last character in a string is the null-character
56. Declaration of C-Strings
• Similar to declaration of any array
char name[30]; // no
initialization
char title [20] = "Le Grande Fromage";
// initialized at declaration
// with a string char chList [10] =
{'a', 'b', 'c', 'd'};
// initialized with list of char
// values
57. Initializing Strings
• When a character array is declared, it is legal to use
the assignment operator to initialize
• Note : use of the “ = “ operator is legal only for char
array initialization
• But : aggregate array assignment is NOT
59. printf(“You entered: %s”, str); //display string from str
getch();
}
String I/O function
• In dealing with string input, scanf() has a
limitation that it does not accept multi-word
strings separated by spaces.
• For example, run the previous program by
providing input string as “hello world”
62. int main()
{
const int MAX = 80; //maximum characters in a
string char str[MAX]; //string variable str puts(
“Enter a string n”); gets(str); //put string in str
printf(“You entered: %s”, str); //display string from str
getch();
}
Home Work
Write a program of that reads and prints multiple
text lines.
64. Working With Strings
• C-strings are compared character by character using the
collating sequence of the system
• If we are using the ASCII character set
Used instead of assignment
Used for comparisons
65. 1) The string "Air" is smaller than the string "Boat"
2) The string "Air" is smaller than the string "An"
3) The string "Bill" is smaller than the string
"Billy"
4) The string "Hello" is smaller than "hello"