Lecture-5 Arrays
Declaration Analogous to using subscripted variables used in mathematical notations e.g. a1, a2, a3,….an Declared using the [] notation to indicate the range/size of the array Elements are indexed using the [] notation, ranging from 0 to one less than the bound
Example #include <stdio.h> int main() { Representation of array in program memory #include <stdio.h> int main() { int a=0, b[5], c=0, cnt=0; for(cnt=0;cnt<5;cnt++) { b[cnt]=cnt; } return 0; a b[0] b[1] b[2] b[3] b[4] c Memory Follow this link to arr-rev.c
Arrays Operations There are no built-in operations on arrays e.g. you cannot write a+b, to add two arrays a[] and b[] Functions cannot return arrays by value To pass or return the same array, you have to pass by reference Follow this link to ref-arr.c
In-class exercise 5-1 Write a program to: Create array a[5], and take in 5 values from the user to populate the array Create array b[5], and take in 5 values from the user to populate the array Create a third array c[5], add values of variables in a[] and b[] and store results in c[] i.e. C[] = a[] + b[]
Multidimensional Arrays Declared with one or more bracketed subscripts e.g. a[][] For function declarations, only the first index may omit the bounds e.g. void addArray(float a[][2], float cnt);
Strings (string.h) Strings are arrays with elements of type character or ‘char’ Strings are always terminated with a end-of-line control character: \n Internally strings are stored with ASCII integer values of the character which they represent
String operations gets() reads a line as a string(array of characters) from the console. Return value is the string or NULL puts() writes a string to the console strlen(): Number of characters in a strcmp(a,b): compare strings a and b strcpy(a, b): copy b into a
Example Follow this link to str-cmp.c