Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can someone help me find the bug in this C program? #include <stdio.h> #include

ID: 3637516 • Letter: C

Question

Can someone help me find the bug in this C program?

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

#define RAMANUJAN 1729

#define DYNAMIC_ARRAY_SIZE 10

int print_array(int *arr, int size);

int array[] = {3, -5, 99};
int size = 3;
int sum = 0;

char cs[10];

int main(int argc, char *argv[])
{
top:
if (size < 0)
goto finish;
sum += array[size];
--size;
goto top;

finish:
printf("Sum: %d ", sum);

printf("Array elements: ");
print_array(array, 3);

{
int i;
int *arr = (int *) malloc(DYNAMIC_ARRAY_SIZE * sizeof(int));

if (arr == NULL) exit(ENOMEM);

for (i = 0; i < DYNAMIC_ARRAY_SIZE; ++i)
arr[i] = i + 1;

printf(" Dymamic array: ");
print_array(arr, DYNAMIC_ARRAY_SIZE);
}

return EXIT_SUCCESS;
}

int print_array(int *arr, int size)
{
for ( ; size >= 0; --size, ++arr)
printf(" %2d ", *arr);
return RAMANUJAN;
}

Explanation / Answer

1st bug as below:

int main(int argc, char *argv[])
{
top:  
if (size < 0)         // bug is if(siz < 0), it should be if(size == 0)
goto finish;
sum += array[size];
--size;
goto top;

finish:
printf("Sum: %d ", sum);

=========================================================================

 

The 2nd bug is in the below line:
int print_array(int *arr, int size)
{
for ( ; size >= 0; --size, ++arr)        // bug is here
printf(" %2d ", *arr);
return RAMANUJAN;
}

===================================================================================================

Correct code should be as below:

int print_array(int *arr, int size)
{
for ( ; size > 0; --size, ++arr)   // insted of size>=, the code should be only size > 0
printf(" %2d ", *arr);
return RAMANUJAN;
}

I hope this will help you.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote