1. What is Debugging?
Debugging is the process of identifying, analyzing, and fixing errors (bugs) in a program.
2. Why Debugging is Important:
Debugging helps to:
- Fix runtime errors
- Identify logical mistakes
- Prevent infinite loops
- Solve recursion errors
- Improve program performance
Without debugging, even small mistakes can cause the entire application to fail.
3. Debugging Rule (Recursion):
Always check:
• Is there a base condition?
• Is the recursive call correct?
• Is the value changing in each call?
If these three are missing, recursion will fail. ⚠️
4. Debugging Recursion Example:
Recursion is a function calling itself until a condition is met. If the stopping condition is missing, the program will run infinitely and crash.
Incorrect Program:
public class DebugExample {
static int fact(int n) {
int factorial = 0; **// mistake**
if (n == 1)
return factorial;
factorial = n * fact(n - 1);
return factorial;
}
public static void main(String[] args) {
int number = 5;
int result = fact(number);
System.out.println(result);
}
}
1. Check the Output
Program output = 0
2. Compare with Expected Result
Expected = 120
Actual = 0 → Output is wrong ❌
3. Find the Mistake
int factorial = 0; // wrong
In factorial calculation, multiplication with 0 always gives 0.
Example:
5 × 0 = 0
4 × 0 = 0
3 × 0 = 0
Also in base condition:
if (n == 1)
return factorial;
When n == 1, the function returns 0, and the entire recursion becomes 0.
Correct Program:
public class DebugExample {
static int fact(int n) {
if (n == 1)
return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
int number = 5;
int result = fact(number);
System.out.println(result);
}
}
Debugging Process (Correct Version):
1. Check the Input
number = 5
Program calls:
fact(5)
2. Check Base Condition
if (n == 1)
return 1;
This is the Base Condition
When n = 1, recursion stops.
Base condition exists ✅
3. Check Recursive Call
return n * fact(n - 1);
Function calling itself:
fact(n - 1)
Recursive call correct ✅
4. Check Value Changing
n - 1
Value decreases every time:
5 → 4 → 3 → 2 → 1
Value changing correctly ✅
5. Step-by-Step Execution
Program Flow:
fact(5)
= 5 * fact(4)
fact(4)
= 4 * fact(3)
fact(3)
= 3 * fact(2)
fact(2)
= 2 * fact(1)
fact(1)
= 1 (Base condition reached)
6. Backtracking (Return Values)
Now values return back:
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
fact(4) = 4 * 6 = 24
fact(5) = 5 * 24 = 120
7. Final Output
120
Top comments (0)