Chapter 7 Arrays
Array
An array is a collection of similar elements
one variable ⇒ capable of storing multiple values
Syntax
The syntax of declaring an array looks like this.
Int marks[90]; ⇒ Integer array
char name[20]; ⇒ character array or strong
float percentile[90]; ⇒ float array
The values can now be assigned to marks array like this :
marks [0] ⇒33;
marks [1] ⇒12;
NOTE; It is very important to note that the array index starts with 0
marks → 7,6,21,3,91,3,.,.,.,88,89
0 1 2 3 4 5 . . . 88 89
Total = 90 elements
Accessing elements
Elements of an array can be accessed using ;
scanf(”%d”,&marks[0]); ⇒ Input first value
printf(”%d”,marks[0]); ⇒ Output first value of the array
Initialization of an array
There are many other ways in which an array can be initialized.
int cgpa [3] = {9,8,8} ⇒ Array can be initialized while declaration
float marks[] = {33,40}
Arrays in memory
Consider this array;
int arr [3]={1,2,3} ⇒ 1 integer =4bytes
This will reserve 4*3 =12 bytes in memory
1 2 3 ⇒ arr in memory
62302 62306 62310
Pointer Arithmetic
A pointer can be incremented to point to the next memory location of that type.
Consider this example
int i =32;
int *a =&i; ⇒ a=87994
a++;
Char a=’A’
char *b =&a;
⇒ b=87994
b++;
⇒ now b =87995
Following operations can be performed on a pointers:
- Addition of number to a pointer
- subtraction of a number from a pointer
- subtraction of one pointer from another
- comparison of two pointer variables
Accessing arrays using pointers
Consider this array
7 9 2 8 1
index 0 1 2 3 4
ptr
If ptr points to index 0, ptr++ will point to index 1 & so on….
This way we can have an integer pointer pointing to first element of the array like this;
int * ptr = & arr[0]; → or simply arr
ptr++;
*ptr ⇒ will have 9 as its value
Passing arrays to functions
Arrays can be passed to the functions like this
printArray(arr,n); ⇒ function call
void printArray (int*i, int n); ⇒ functional prototype
or
void printArray (inti[], int n);
Multidimensional Arrays
An array can be of 2 dimension/3 dimension/ n dimensions
A 2 dimensional array can be defined as;
int arr [3] [2] = { {1,4}
`{7,9}`
`{11,22} };`
we can access the elements of this array as arr [0] [0] , arr [0] [1] & so on…
2-D arrays in memory
A 2d array like a1-d array is stored in contiguous memory blocks this
arr[0] arr[0] [1] ……..
1 4 7 9 11 22
87224 87228 ……..
Comments
Post a Comment