Professional Documents
Culture Documents
Arrays and Strings: by Kushal Ghimire (072 BCT) Anish Joshi (074 BCT)
Arrays and Strings: by Kushal Ghimire (072 BCT) Anish Joshi (074 BCT)
[00] [01]
1D 2D
Arrays & it’s Properties
An array is static type i.e. fixed size must be declared initially(macro definition and array
initialization are exceptions).
Arrays share same name. The individual elements are characterized by array name followed
by one(One Dimensional) or more(Multi Dimensional) subscripts or indices enclosed in a
square brackets.
Random access to every element using numeric index, index starts from 0 and ends at size-1.
Till the array elements are not given any specific values, they are supposed to contain
garbage values. The values can be assigned to elements at the time of array declaration,
which is called array initialization.
Logical representation of an array
10000
#include<stdio.h>
MEMORY ADDRESSESS
{
2004 E
char letters[5] = {‘A’,’B’,’C’,’D’,’E’};
return 0;
2003 D
}
2002 C
A B C D E 2001 B
letters[0] letters[1] letters[2] letters[3] letters[4] 2000 A
0
Logical representation of an array
10000
#include<stdio.h>
MEMORY ADDRESSESS
2009
int main() 2008
{ 2007
int numbers[2] = {100,101}; 2006
return 0; 2005
} 2004
2003
2000 2002 Address 2002 101
2001
100 101 100
Value 2000
10000
#include<stdio.h>
MEMORY ADDRESSESS
2009
int main() 2008
{ 2007
float numbers[2] = {10.1,10.2}; 2006 10.20000
return 0; 2005
2004 0
}
2003
2000 2004 Address 2002 10.100000
2001
10.100000 10.200000 Value 2000
Examples:
1. int a[5] = {12, 13, 14, 15, 16}; => a[0]=12, a[1]=13, a[2]=14, a[3]=15, a[4]=16
2. int a[5] = {12, 13, 14}; => a[0]=12, a[1]=13, a[2]=14, a[3]=0, a[4]=0
3. int a[ ] = {12, 13, 14, 15, 16}; => size is automatically set by the compiler.
4. int a[size] = {12, 13, 14}; => [Be careful] VALID if “size” is defined in MACRO but INVALID
if “size” is defined in VARIABLES.
Accessing 1D Array Elements
1. All the elements of an array cannot be set at once.
int a[5];
a = 0; // not allowed a[1] = 12; // allowed
return 0; return 0;
} }
//output //output
Enter a[0]: 11 Element a[0] is 11
Enter a[1]: 22 Element a[1] is 22
Enter a[2]: 33 Element a[2] is 33
Enter a[3]: 44 Element a[3] is 44
Enter a[4]: 55 Element a[4] is 55
To be continued..