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;
}
Answer
Here is your answer, if you have any doubt please comment, i am here to help you.
1)
#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;
}
When this code run in c, we will get the following error.
actual expect result is 55.
This happen because the following code
//This is the error happening statement in the above program
//In C there is no exception happening in indexoutofbound
//it will access some other memory location allotted for the array.
//That means indexoutofbound will return some garbage value here.
while (i<=A){ //limit should be lessthan 10 and not equal 10, because index start at 0,
//in the assignment statement, we can see we only get value <10 not <=10. So,
//If access the index of 10 will be garbage.
Total += numbers[i];
i++;
}
Access non allocated location of memory: The program can access some piece of memory which is owned by it.
2) To make it functional just use the 'less than'(<) not use 'less than or equal'(<=) in while loop.
Here is final code and result.
#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){ //just change here < instead of <=
Total += numbers[i];
i++;
}
printf("Total =%d\n", Total);
return 0;
}
output
Any doubt please comment,
Thanks in advance