C Program Debug explanation: Based on the following code, what was the bug and w
ID: 3749299 • Letter: C
Question
C Program Debug explanation:
Based on the following code, what was the bug and why did it cause incorrect output?
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
void ComputeFibonacci (int Fibo[SIZE]){
int i;
Fibo[0]= 1;
Fibo[1]= 1;
for (i = 1; i>=SIZE; i++){
Fibo[i]= Fibo[i--]+ Fibo[i-2]
}
}
void PrintFibonacci (int Fibo[SIZE]){
int i;
printf("Here are the 10 first elements of Fibonacci: ");
for(i = 1; i<=SIZE; i++){
printf ("%d,", Fibo[i]);
}
printf("%d ", Fibo[SIZE]);
}
int main () {
int FiboArray[SIZE];
ComputeFibonacci(FiboArray);
PrintFibonacci(FiboArray);
system ("PAUSE");
return 0;
}
Do not post the correct code as I have it, just need an explanation of what went wrong with the above code, and how the code below rectified it. I have an idea but need a thorough understanding, please.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
void ComputeFibonacci(int Fibo[])
{
int i;
Fibo[0] = 0;
Fibo[1] = 1;
for (i = 2; i < SIZE + 2; i++) {
Fibo[i] = Fibo[i - 1] + Fibo[i - 2];
}
}
void PrintFibonacci(int Fibo[])
{
int i;
printf("Here are the 10 first elements of Fibonacci: ");
for (i = 0; i < SIZE + 2; i++) {
printf("%d", Fibo[i]);
if (i < SIZE + 1)
printf(",");
}
printf(" ");
}
int main()
{
int FiboArray[SIZE + 2];
ComputeFibonacci(FiboArray);
PrintFibonacci(FiboArray);
system("PAUSE");
return 0;
}
Explanation / Answer
1.
int FiboArray[SIZE]; // It allocates space for 8 variables since SIZE is 8 but we need first 10 fibonacci numbers so change int FiboArray[SIZE+2];
2.
Fibo[0]= 0; // change first fibonaccii number is 0
3.
for (i = 1; i>=SIZE; i++)
i value 1 and SIZE is 8 so 1> = 8 condition fail because 1 is not bigger than 8
Fibo[0] = 0;
Fibo[1] = 1;
Obsrve the above index 0 and 1 already filled so start index with 2 as below
for (i = 2; i < SIZE + 2; i++)
4.
Fibo[i]= Fibo[i--]+ Fibo[i-2] // Here the value of i decremented by 1 in the whole block but we need current position so change to i-1
Fibo[i]= Fibo[i-1]+ Fibo[i-2];
5.
for(i = 1; i<=SIZE; i++) // Here index start from 0 i changed to 0 and total 10 elements so use i < SIZE + 2 so it run for 0 throgh 9
for (i = 0; i < SIZE + 2; i++)
These are the reasons for changes
Additional statement:
if (i < SIZE + 1) // It is true for all elements except last element
printf(","); // It print ,
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.