0% found this document useful (0 votes)
32 views

Arrays and Strings

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Arrays and Strings

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

ARRAYS AND STRINGS

Outline
1 dimensional array
What is an array ?

Array is a group of related data items which share a common name.

• Each individual value in the array is called an element.


• Array elements could be int, float, char etc
• Each individual element in an array (array element) is referred to
by its position (using index or subscript) in the group.
Array Declaration

The array has to be declared before it can be used in a program.


The general form of declaration of an array is :

type variable_name[size] ;
Assigning values to array elements

• Use assignment operator (=)


Accessing the elements of an array

• Access using the index or subscript


• marks[0] is the first element of the array, marks[1] is the
second and so on.

It is also important to note here that C performs no bounds


checking on arrays, i.e. there is no check on whether the subscript
has exceeded the size of the array. Therefore it is our responsibility
to ensure that we do not attempt to enter data exceeding the
bound of the array, otherwise this data will be simply placed in
memory outside the array and the results might be unpredictable.
Example

1. Program that declare and assign value to an array


2. Program that input and output array elements using
loop structure
Example
/* Program to illustrate the use of array */

main() {
int num[5];
int sum, i;
float avg;
for(i =0; i< 5;i++)
scanf(“%d”, &num[i]);
sum = 0;
for(i=0; i< 5; i++)
sum = sum + num[i];
avg = sum/5;
printf(“The average of numbers is %7.2’’, avg);
}
Array Initialisation

The general form of initialisation of elements in an array is :

type array_name[size] = {val1, val2,....};

Example
int marks[5] = {40, 70, 32, 80, 76};

Is equivalent to
marks[0] = 40
marks[1] = 70
marks[2] = 32
marks[3] = 80
marks[4]= 76
Example
/*Program to input numbers into array a and then copy them to array b */

main()
{
int i, a[10], b[10];
for (i = 0; i< 10; i++){
printf(“Enter element:);
scanf(“%d”, & a[i]);
printf(“\n”);
}
for (i = 0; i< 10; i++)
b[i] = a[i];
for (i = 0; i< 10; i++)
printf(“%d\t%d\n”, a[i], b[i]);
}
2 dimensional array
TWO DIMENSIONAL ARRAYS
A two dimensional array is also called a matrix.

Each row represents the marks obtained by a particular student in all


the four subjects, whereas each column represents the marks obtained
by all the students in a particular subject.
Two dimensional array

The two dimensional array can be declared as follows :

type array_name[row_size][col_size];

Thus the above table can be represented in a two dimensional


array as :
int stud[5][4];
Accessing the elements of an array (2D)
Initializing Two Dimensional Arrays

• Two dimensional arrays can also be initialized like the one


dimensional arrays with their declaration followed by the list of
values of the elements.
• This list is enclosed in braces, with each element being
separated by a comma.
• The elements are initialized row wise.
Initializing Two Dimensional Arrays

int arr[2][3] = {10,5,3,15,20,25};

This initialization will initialize the array elements of array arr as


follows:
arr[0][0] = 10
arr[0][1] = 5
arr[0][2] = 3
arr[1][0] = 15
arr[1][1] = 20
arr[1][2] = 25
Initializing Two Dimensional Arrays

int arr[2][3] = {10,5,3,15,20,25};

int arr[2][3] = {{10, 5, 3}, {15, 20, 25}};


or
int arr[2][3] ={
{10,5,3},
{15,20,25}
};
Example (2D)
/* Program to store elements in a 2 dimensional array */

#define ROWS 5
#define COLS 5
main() { /*--start main--*/
int arr1 [ROWS][COLS], i, j, rows, cols;
printf(“\nEnter number of rows :”);
scanf(“%d”,&rows);
printf(“\nEnter number of columns :”);
scanf(“%d”, &cols);
for(i=0; i< rows; i++) {
for(j = 0; j < cols; j++) {
printf(“\nEnter value :”);
scanf(“%d”, &arr1[i][j]);
}
}
Cont…..
Example (2D) cont…
printf(“\nThe elements are”);
for(i=0; i< rows; i++) {
for(j = 0; j < cols; j++) {
printf(“%d\t”, arr1[i][j]);
}
printf(“\n”);
}
} /*--end main--*/
Multi-dimensional array
Multi-dimensional array

• A multidimensional array is declared using the


following syntax:
type array_name[d1][d2][d3][d4]………[dn];
• Where each d is a dimension, and dn is the size of final
dimension.

Example:

float y[2][4][3];
Initialization Example

int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Example
// C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i){
for (int j = 0; j < 3; ++j){
for (int k = 0; k < 2; ++k){
scanf("%d", &test[i][j][k]);
}
}
}
Example (cont.)
/ Printing values with proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k){
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
STRINGS
String
• An array of characters is a string.
• Any group of characters within double quotation marks is a
constant string.
• A string constant is a one dimensional array of characters
• A string variable is any valid C variable name and since a string is
an array of char we always declare a string as an array. The
general form of a string variable is :
char string_name[size];
• The size determines the number of characters in the string_name.
eg.
char name[20];
char address[25];
String constant

• A string constant is an array of characters terminated


by a null (‘\0’).
• A string constant can be initialised as follows :
char str1[] = {‘P’, ‘R’, ‘O’, ‘G’ ‘R’ ‘A’, ‘M’ ‘\0’};
or
char str1[] = “PROGRAM”;
Reading and Writing Strings
• The scanf function can be used to read strings. The format
specification used to read strings as has already been
introduced is ‘%s’.
• Example : To read string with the help of scanf
main() {
char name[15];
printf(“Enter your name :”);
scanf(“%s”, name);
printf(“Good Morning %s”, name);
}
Output
Points to remember when using scanf

• Take care to ensure that you do not enter more


characters than the size you have defined while
declaring the character array. C does not perform any
bounds checking on character arrays.
• Note that scanf terminates its input as soon as it
encounters a white space. A white space may be a
blank space, a tab, carriage return, form feed, new
line. This means that scanf is not able to receive more
than one word strings.
Points to remember when using scanf

A sample output of the above program :


Enter your name : John Smith
Good Morning John
gets() and puts()
Example :
/*Program to illustrate the use of gets and puts */
main() {
char name[25];
printf(“Enter your name :”);
gets(name);
puts(“Good Morning”);
puts(name);
}
gets() and puts()

A sample output of the above program :

Enter your name :cherry mae


Good Morning
cherry mae
gets() and puts()

• gets() and puts() are capable of handling only one


string at a time.
• Therefore it is required to use two puts() in the above
program to print the two strings Good Morning and
cherry mae
• Note that puts() automatically takes the cursor on the
next line. Hence the two strings are output on
different lines.
getchar() function
String Handling Functions
Example

• Compare: Comparing two string if they are equal or


not.
– C-style string function: strcmp(s1, s2);
• Concatenate: Adding one string at the end of the
other.
– C-style string function: strcat(s1, s2);
• Length: Finding the length of the string.
– C-style string function: strlen(s1);
Activity

• Program to copy one string into another using LOOP


• String concatenation Program using LOOP
What is an Array of Strings?
A string is a 1-D array of characters, so an array of strings
is a 2-D array of characters.

NOTE: It is important to end each 1-D array by the null character, otherwise,
it will be just an array of characters.
Example

You might also like