In: Computer Science
Write a program in C that declares the following array:
int. array[] = { 1, 2, 4, 8, 16, 32 }
Then write some code that accepts a number between 0 and 5 from the user and stores it in a variable called "index".
Write some code that retrieves the item specified by the index, like this:
int item = array[index];
Then write code that outputs the corresponding array entry based on the number the user entered. Example output:
The item at array index 3 is 8.
Now change the code that retrieves the item so that it looks like this:
int item = index[array];
And notice that you still get the same output. Why does this work? Is this good coding style? Explain in a brief paragraph after the final version of your code below and then add some comments to your program.
Here is the C program asked to write:
#include <stdio.h>
int main()
{
int array[] = { 1, 2, 4, 8, 16, 32 };
int index;
scanf("%d",&index); //taking input for the index variable
if(index >=0 && index<=5){ //program proceeds only if
index is between 0 and 5 inclusive
int item = array[index]; //style 1
printf("The item at array index %d is %d\n",index, item);
//printing the item retrived from style 1
item = index[array]; // changed to style 2
printf("The item at array index %d is %d\n",index, item);
//printing the item retrived from style 2
}
return 0;
}
And the output we get is for input 4:
Actually , we get same output in both the cases because, of pointer arithemetic. Because index[array] and array[index] are finally represented as (index + arrayBasePointer) and (arrayBasePointer + index). In any of the ways, both are some. Here, arrayBasePointer is incremented by index number of integer blocks not index number of bytes. It is incremented by index number of integer blocks because, the arrayBasePointer is integer pointer. So, it will increment index number of elements from the arrayBaseAddress.