Bcse102L Structured and Object Oriented Programming: Module-2 Array An in C
Bcse102L Structured and Object Oriented Programming: Module-2 Array An in C
Bcse102L Structured and Object Oriented Programming: Module-2 Array An in C
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- -- -- -- -- -- -- --
0 1 2 3 4 5
Subscripting
• Declare an array of 10 integers:
int Ar[10]; // array of 10 ints
• To access an individual element we must apply a subscript
to array named Ar.
– A subscript is a bracketed expression.
• The expression in the brackets is known as the index
• Index is always a positive integer
– First element of array has index 0.
Ar[0]
– Second element of array has index 1, and so on.
Ar[1], Ar[2], Ar[3],…
– Last element has an index one less than the size of the array.
Ar[9]
• Incorrect indexing is a common error!.
Subscripting
0 1 2 3 4 5 6 7 8 9
Ar -- -- -- 1 -- -- -- -- -- --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
Array Element Manipulation
• Consider
int Ar[10], i = 7, j = 2, k = 4;
Ar[0] = 1;
Ar[i] = 5;
Ar[j] = Ar[i] + 3;
Ar[j+1] = Ar[i] + Ar[0];
Ar[8] = 12;
0 1 2 3 4 5 6 7 8 9
Ar 1 -- 8 6 3 -- -- 5 12 --
Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5] Ar[6] Ar[7] Ar[8] Ar[9]
Program to read 10 score values and find their
sum
void main()
{
int score[10]; Array index always starts at 0.
For n element array : index values
int i,sum=0; are 0 to n-1
//read 10 scores
for(i=0;i<10;i++)
{
printf(“Enter score %d : “,i);
scanf(“%d”,&score[i]);
}
for(i=0;i<10;i++)
{
printf(“Score %d: %d”,i,score[i]);
sum=sum+score[i];
}
printf(“Sum of scores= %d”,sum);
}
Program to read 10 score values and find their
Min and Max
void main()
{
int score[10], i, min=1000,max=0;
//read 10 scores
for(i=0;i<10;i++)
{
printf(“Enter score %d : “,i);
scanf(“%d”,&score[i]);
}
for(i=0;i<10;i++)
{printf(“Score %d : %d”,i,score[i]);
if(score[i]<min) min=score[i];
if(score[i]>max) max=score[i];
}
printf(“Min score = %d, Max score = %d”, min,max);
}
Initialization
Only A[0] initialized
// To initialize all elements with 0 void main() to 1; rest A[1] to
void main() { A[9] are set to 0
{ int i, A[10]={1};
int i, A[10]={0}; //or A[i]={}; for(i=0;i<10;i++)
for(i=0;i<10;i++) printf("%d\t",A[i]);
printf("%d\t",A[i]); }
}