Arrays
Introducing Arrays
Array are collection of elements of same data type.
All elements are consecutively in memory.
Each element can be individually referenced by adding an index to a unique name.
Uses:
Arrays are useful when we store related data items.
Using arrays we can store N elements of int type
Introducing Arrays
Examples:
List of marks of students List of grades of students
List of employees in an organization List of names of students
Declaration of an Array
type Array_name[size];
⚫ Here size indicates the maximum number of elements.
⚫ The subscript value start from 0 to size-1.
⚫ Example:
⚫ int number[10];
⚫ float number[10];
Initialising an Array
⚫ An array is initialised after it is declared.
⚫ The following array can hold marks of five subjects:
int marks[5];
An array can be initilised in following ways:
First approach: The value of each element is listed within two curly brackets { } and a comma (,)is used to separate one element from another.
Initialising an Array
Second approach:
elements of array can be initilised one at a time.
Ex. mark[0] = 55;
mark[1] = 60;
mark[2] = 40;
mark[3] = 80;
mark[4] = 90;
Note: In an array index of first element is considered
Declaring an Array
#include<stdio.h>
void main() {
int A[10],i,j,temp;
printf(“Enter 10 numbers”);
for(i=0; i<10; i++) scanf(“%d”,&A[i]);
}
Size of an Array
Once an array is declared, its size is fixed.
After that it can not changed.
Ex. int A[10];
Can store only 10 elements (A[0] to A[9]).
Initialising an Array
⚫ Declaring, creating and initilising in single step:
⚫ int marks[5]={50, 60, 40, 80, 90}
Multidimensional Array
⚫ The type of array that we have discussed till now is single dimensional array as it has only single index.
⚫ Two dimensional arrays also called as matrix.
⚫ Two dimensional arrays looks like this:
Row 0 Row 1 Row 2 Row 3
Column 0 Column 1 Column 2 Column 3
Declaration: Multidimensional Array
⚫ type array_name[row_size][column_size];
⚫ row_size –>Number of rows in matrix
⚫ column_size –> Number of columns in matrix
Ex: We can declare an array to store 100 students marks for five subjects.
int marks[100][5];
⚫ Examples:
⚫ int number[4][3]; /* 12 elements */
⚫ float number[3][2]; /* 6 elements */
⚫ char name[10][20]; /* 200 chars */
Initialization of a 2-D Array
⚫ int a[2][3]={1,2,3,4,5,6};
⚫ int a[2][3]={{1,2,3}, {4,5,6}};
⚫ int a[][3]={{1,2,3}, {4,5,6}}
⚫ int a[2][3]={0}
⚫ Following initializations are not allowed
⚫ int a[3][]={2,4,6,8,10,12};
⚫ int a[][]={2,4,6,8,10,12};
⚫ Note: If the first bracket pair is empty, then compiler take the size from the number of inner brace pairs
Example
#include <stdio.h>
#define row 4
#define col 3 void main() {
int M[row][col];
int i,j,k;
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row;i++) {
for(j=0;j<col;j++) {
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
Memory Map for 2-D Arrays
Kept in memory as a linear sequence of variables.
⚫Two methods for storing-
◦ Row major
◦ Column major Example:
int a[3][3];
Row major storage:
a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2]
Column major storage:
Strings
Strings
• The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character arrays are many a time also called strings.
• A string is a one-dimensional array of characters terminated by a null ( ‘\0’ ).
• Normally each character is stored in one byte, successive characters are stored in successive
Null Character
⚫ The terminating null (‘\0’) is important, because it is the only way to know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters.
Declaring strings
Char stringname[size];
The size determines the number of characters in the string name.
Example:
char monthname[12];
char address[100];
The size of the array should be one byte more than
Initializing Strings
char month[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’ ,’\0’};
Or
char month[ ]={”january”};
Then the string month is initializing to January.
This is perfectly valid but C offers a special way to initialize strings. The above string can be initialized
char month1[ ]=”January”.
The characters of the string are enclosed within a part of double quotes.
String Initialization:
char str[9] = “I like C”;
same as
char str[9]={‘I’,‘ ‘,’l’,‘i’,’k’,’e’,‘ ‘,’C’,’\0’};
Q. Is there any difference between following Initialization?
char str[]=“ITMU”;
char str[4]= “ITMU”;
Ans: Yes, in second declaration there is no null character
Reading Strings from the terminal:
• The function scanf with %s format specification is needed to read the character string from the
terminal.
•
Example:
•
char address[15];
scanf(“%s”,address);
Scanf statement has a draw back it just terminates the statement as soon as it finds a blank space,
suppose if we type the string New York then only the string New will be read and since there is a
blank space after word “New” it will terminate
Arrays of Strings
⚫ Declaration:
⚫ char name[5][30];
⚫ Five strings each contains maximum thirty characters.
⚫ Initialization:
⚫ char[5][10]={“One”,”Two”,”Three”,”Four”,”Five”};
⚫ Other valid declarations
⚫ char[][]={“One”,”Two”,”Three”,”Four”,”Five”};
Copying String
• we cannot assign one string to another directly.
For example:
•
String1=”xyz”;
String2=string1;
Are not valid.
• To copy the chars in one string to another string we may do so on a character to character basis.
String operations (string.h)
• C library supports a large number of string handling functions that can be used for string manipulations such as:
• Length (number of characters in the string).
• Concatenation (adding two are more strings)
• Comparing two strings. (if equal or not)
• Copy(copies one string over another)
• To do all the operations described here it is essential to include string.h library header file in the program.
strlen() function:
• This function counts and returns the number of characters in a string. The length does not include a null character.
•
Syntax
• n=strlen(string);
Where n is integer variable. Which receives the value of length of the string.
Example
length=strlen(“Hollywood”);
•
The function will assign number of characters 9 in the string to a integer variable length.
strcat() function:
• when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. It takes the following form
strcat(string1,string2)
string1 & string2 are character arrays. When the function strcat is executed string2 is appended to string1.
Example
strcpy(string1,”deep”);
strcpy(string2,”kamal”);
strcat(string1,string2);
strcmp function:
• In C you cannot directly compare the value of 2 strings in a condition like if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same.
The syntax of strcmp() is given below:
•
Strcmp(string1,string2)
Example:
•
strcmp(“Newyork”,”Newyork”) will return zero because 2 strings are equal.
strcmp(“their”,”there”) will return a 9 which is the numeric difference between ASCII ‘i’ and ASCII ’r’.
strcmp(“The”, “the”) will return 32 which is the numeric difference between
strcpy() function:
• C does not allow you to assign the characters to a string directly as in the statement name=”Robert”;
Instead use the strcpy function found in most compilers.
• syntax
strcpy(string1,string2);
•
Strcpy function assigns the contents of string2 to string1.
string2 may be a character array variable or a string constant.
•
strcpy(Name,”Robert”);
•
In the above example Robert is assigned to the string called