Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views3 pages

C Debugging Exercises Final Exam

Uploaded by

ol chanthoeun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

C Debugging Exercises Final Exam

Uploaded by

ol chanthoeun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

C Programming Debugging Exercises - Final Exam Level

Question 1: Array Declaration & Input


#include <stdio.h>
int main() {
int n, i, arr[]; // Error at Line 3
printf("Enter number of elements: ");
scanf("%d", n); // Error at Line 5

for(i = 0; i < n; i++) {


scanf("%d", arr[i]); // Error at Line 8
}

return 0;
}
Fixed Code:

- Line 3: int arr[] -> int arr[100];

- Line 5: scanf("%d", n); -> scanf("%d", &n);

- Line 8: scanf("%d", arr[i]); -> scanf("%d", &arr[i]);

Question 2: Function Return


int add(int a, int b) {
int result = a + b; // Error: missing return
}
Fixed Code:

- Add: return result;

Question 3: Pointer Misuse


int main() {
int x = 10;
int *ptr;
*ptr = &x; // Error at Line 4
printf("%d", *ptr);
return 0;
}
Fixed Code:

- Line 4: *ptr = &x; -> ptr = &x;

Question 4: Recursive Call Missing Argument


int factorial(int n) {
if(n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
printf("%d", factorial()); // Error at Line 8
return 0;
}
Fixed Code:

- Line 8: factorial() -> factorial(5);

Question 5: Loop Error


int main() {
int i;
for(i = 1; i <= 5; i--){ // Error at Line 4
printf("%d\n", i);
}
return 0;
}
Fixed Code:

- Line 4: i-- -> i++

Question 6: String Misuse


int main() {
char name;
printf("Enter your name: ");
scanf("%s", name); // Error at Line 5
return 0;
}
Fixed Code:

- Use char name[50]; instead of char name;

Question 7: Format Specifier


int main() {
float a = 5.2, b = 3.1;
printf("Sum is %d\n", a + b); // Error at Line 3
return 0;
}
Fixed Code:

- Use %%f instead of %%d -> printf("Sum is %.2f\n", a + b);

Question 8: File Handling


int main() {
FILE *f = fopen("data.txt", "r");
char ch;
while((ch = fgetc(f)) != EOF) {
putchar(ch);
}
fclose(f);
return 0;
}
Fixed Code:

- Add check: if(f == NULL) { printf("Cannot open file.\n"); return 1; }

You might also like