In: Computer Science
Question 2. The following code defines an array size that sums elements of the defined array through the loop.
#include <stdio.h>
#define A 10
int main(int argc, char** argv) {
int Total = 0;
int numbers[A];
for (int i=0; i < A; i++)
numbers[i] = i+1;
int i =0;
while (i<=A){
Total += numbers[i];
i++;
}
printf("Total =%d\n", Total);
return 0;
}
Submission
For this assignment, you need to write a report file of your work. The report should answer each question in details, providing outputs of the code to justify your answer.
Given Code :-
#include <stdio.h>
#define A 10
int main(int argc, char** argv) {
int Total = 0;
int numbers[A];
for (int i=0; i < A; i++)
numbers[i] = i+1;
int i =0;
while (i<=A){
Total += numbers[i];
i++;
}
printf("Total =%d\n", Total);
return 0;
}
Problem :- We know the value of A in above code 10 and the array(number) size is also 10. So, 10 position needs to be filled from index 0 to size-1=9. From the for loop we can understand the every index is filled.
Now when we are adding each number in array we have used while loop. The while is starting from 0 and ending at 10, i.e. it is running for 11 iteration and there no 10th index available in number array.
This problem is known as array out of bound error. In java, there is function that prevent the program from accessing array out of bound by generating a exception such as java.lang.ArrayIndexOutOfBoundsException.
But in case of c language there is no functionalaity available like the java. And if, programmer use the index out of the range then value at that index will be the garbage.
So the correct code is :-
#include <stdio.h>
#define A 10
int main(int argc, char** argv) {
int Total = 0;
int numbers[A];
for (int i=0; i < A; i++)
numbers[i] = i+1;
int i =0;
while (i<A){
Total += numbers[i];
i++;
}
printf("Total =%d\n", Total);
return 0;
}