Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Computer Programming

BITS Pilani Pratik Narang


Pilani Campus
BITS Pilani
Pilani Campus

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?:

• int intArray[6] = { 1, 2, 3, 4, 5, 6};


• float floatArray[ 100 ] = { 1.0f, 5.0f, 20.0f };
• double fractions[ ] = {3.141592654,1.570796327,0.785398163 };
int main(){
int 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?
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

What is the right way in such a scenario?


int main(){
int intArray[6];
for (int i=0;i<6;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
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”;

• Are they the same?


Char arrays
• Write a C program which reads a 1D char array, converts all elements
to uppercase, and then displays the converted array.
• Hint: use toupper(ch) of <ctype.h>

You might also like