In: Computer Science
#include <stdio.h> #include <stdlib.h> #include <time.h> void sort(int a[], int size); void printArray(int a[], int size); int main(){ int arraySize, limit, count, srand(time(0)); print f("Enter the size of array\n"); scanf("%d", arraySize); int array[arraySize]; printf("Enter the upper limit\n"); scanf("%d", &limit); count = 0; while(count <= arraySize){ array[count] = (rand() % (limit + 1)); count++; } printArray(array, &arraySize); sort(array, arraySize); printArray(array, arraySize); Return 0; } void printArray(int a[], int size){ int i = 0; printf("Array: ["); while(i < size){ if(i != size - 1){ printf("%d, ", a[i]); } else { printf("%d]\n", a[i]); } printf("%d, ", a[i]); } }
Find the bugs in the given code and write the correct line of code where the bug is. There are a total of 7 bugs.
Going from the top :
Bug 1 : int arraySize, limit, count, => This should end with a semi-colon
Bug 2 : scanf("%d", arraySize); => "&" is missing in arraySize
Bug 3: while(count <= arraySize) => Because count starts from 0 , it shoul have "<" instead of "<="
Bug 4 : printArray(array, &arraySize); => According to the declaration of the func, it should not have "&"
Bug 5 : sort(array, arraySize); => Definition for the sort func is missing
Bug 6 : Return 0; => R should be small i.e "return 0"
Bug 7 : printf("%d, ", a[i]); in printArray func => instead of this it should have a "i++" .
Here's the working code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sort(int a[], int size);
void printArray(int a[], int size);
void swap(int*,int*);
int main(){
int arraySize, limit, count; //Bug1
srand(time(0));
printf("Enter the size of array\n");
scanf("%d",&arraySize);//Bug2
int array[arraySize];
printf("Enter the upper limit\n");
scanf("%d", &limit);
count = 0;
while(count < arraySize){//Bug3
array[count] = (rand() % (limit + 1));
count++;
}
printArray(array, arraySize);//Bug4
sort(array,arraySize);//Bug5
printArray(array, arraySize);
return 0;//Bug6
}
void printArray(int a[], int size){
int i = 0;
printf("Array: [");
while(i < size){
if(i != size - 1){
printf("%d, ", a[i]);
} else {
printf("%d]\n", a[i]);
}
i++;//Bug7
}
}
sort(int a[],int size){
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-i-1;j++){
if(a[j]>a[j+1]){
swap(&a[j],&a[j+1]);
}
}
}
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
Output: