Professional Documents
Culture Documents
Arrays in C
Arrays in C
Arrays in C
What and why?
• Array – an ordered series of arrangement
• For processing multiple data items having a common characteristic
• E.g.: set of numerical data, list of student names, etc.
Defining arrays
• Storage-class data-type name[size]
• Examples:
• int count[100];
• char name[25];
• float cgpa[50];
• Good practice:
• #define SIZE 100
• int count[SIZE];
Ways of defining/initializing arrays
• Which of these are valid ways of initializing arrays in C?:
Output?
1 2 3 4 5 6
int main(){
int intArray[6] = {1, 2, 3};
for (int i=0; i<sizeof(intArray)/sizeof(intArray[0]); i++)
printf("%d\t",intArray[i]);
return 0;}
Output?
1 2 3 0 0 0
int main(){
int intArray[] = {1, 2, 3};
for (int i=0; i<sizeof(intArray)/sizeof(intArray[0]); i++)
printf("%d\t",intArray[i]);
return 0;}
Output?
1 2 3
int main(){
int intArray[6];
intArray[6] = {1, 2, 3, 4, 5, 6};
for (int i=0; i<sizeof(intArray)/sizeof(intArray[0]); i++)
printf("%d\t",intArray[i]);
return 0;}
Output?
Compile-time error
Output?
0 1 2 3 4 5
int main(){
int intArray[6];
for (int i=0;i<6;i++)
intArray[i] = i;
for (int i=0;i<9;i++)
printf("%d\t",intArray[i]);
return 0;
}
Output?
0 1 2 3 4 5 394652928 -969703505 4195872
(junk values)
int main(){
int intArray[6];
for (int i=0;i<8;i++)
intArray[i] = i;
for (int i=0;i<6;i++)
printf("%d\t",intArray[i]);
return 0;
}
Output?
0 1 2 3 4 5 Aborted (core dumped)
(segmentation fault)
Char arrays
• char color[3] = “RED”;
• char color[ ] = “RED”;