Error Handling and Debugging in C Practice Questions with Solutions

Introduction

Errors are a normal part of programming, especially when you are learning C. Understanding different types of errors and learning how to find and fix them will make your coding much easier. In this chapter, you will practice common C errors such as syntax errors, logical errors, runtime problems, division by zero, invalid input, and debugging techniques using printf(), return values, and standard error handling functions. Error Handling and Debugging in C practice questions with solutions to help you build concepts.

Introduction

Errors are a normal part of programming, especially when you are learning C. Understanding different types of errors and learning how to find and fix them will make your coding much easier. In this chapter, you will practice common C errors such as syntax errors, logical errors, runtime problems, division by zero, invalid input, and debugging techniques using printf(), return values, and standard error handling functions.

Q1. Find and Fix a Syntax Error

Problem Statement

The following program contains a syntax error. Find the error and write the corrected program.

Incorrect C Program

#include <stdio.h>

int main()
{
    int number = 10

    printf("Number = %d", number);

    return 0;
}

Correct C Program

#include <stdio.h>

int main()
{
    int number = 10;

    printf("Number = %d", number);

    return 0;
}

Sample Output

Number = 10

Explanation

The original program is missing a semicolon after:

int number = 10

The correct statement is:

int number = 10;

A syntax error occurs when the code does not follow the rules of the C language.

Common examples include:

int x = 10

instead of:

int x = 10;

and:

printf("Hello"

instead of:

printf("Hello");

Concepts Covered

  • Syntax errors
  • Semicolons
  • Compiler errors
  • Debugging

Q2. Find and Fix a Logical Error

Problem Statement

The following program is supposed to calculate the area of a rectangle, but it contains a logical error. Find and fix it.

Incorrect C Program

#include <stdio.h>

int main()
{
    int length = 10;
    int width = 5;
    int area;

    area = length + width;

    printf("Area = %d", area);

    return 0;
}

Correct C Program

#include <stdio.h>

int main()
{
    int length = 10;
    int width = 5;
    int area;

    area = length * width;

    printf("Area = %d", area);

    return 0;
}

Sample Output

Area = 50

Explanation

The program compiles successfully, but the answer is wrong.

The incorrect calculation was:

area = length + width;

The formula for the area of a rectangle is:

Area = Length × Width

Therefore, the correct statement is:

area = length * width;

This is called a logical error because the program runs but produces an incorrect result.

Concepts Covered

  • Logical errors
  • Debugging
  • Arithmetic operators
  • Correct formulas

Q3. Prevent Division by Zero

Problem Statement

Write a C program that divides two numbers. Before performing division, check whether the divisor is zero.

C Program

#include <stdio.h>

int main()
{
    int a = 20;
    int b = 0;

    if (b == 0)
    {
        printf("Error: Cannot divide by zero.");
    }
    else
    {
        printf("Result = %d", a / b);
    }

    return 0;
}

Sample Output

Error: Cannot divide by zero.

Explanation

Division by zero must be prevented.

Before:

a / b

we check:

if (b == 0)

If b is zero, the program displays an error instead of performing the division.

This is an important example of preventing a runtime problem through input validation.

Concepts Covered

  • Error checking
  • Division by zero
  • if-else
  • Input validation

Q4. Debug a Program Using printf()

Problem Statement

Write a program that calculates the total price of three items. Use printf() statements to check intermediate values while debugging.

C Program

#include <stdio.h>

int main()
{
    int price1 = 100;
    int price2 = 200;
    int price3 = 150;
    int total;

    printf("Price 1 = %d\n", price1);
    printf("Price 2 = %d\n", price2);
    printf("Price 3 = %d\n", price3);

    total = price1 + price2 + price3;

    printf("Total = %d", total);

    return 0;
}

Sample Output

Price 1 = 100
Price 2 = 200
Price 3 = 150
Total = 450

Explanation

When you are not sure where a calculation is going wrong, temporarily print important variable values.

For example:

printf("Price 1 = %d\n", price1);

helps you verify that the variable contains the expected value.

This technique is commonly called print debugging.

You can use it to check:

  • Input values
  • Variable values
  • Loop counters
  • Function results
  • Intermediate calculations

Concepts Covered

  • Debugging with printf()
  • Variable checking
  • Intermediate values
  • Logical debugging

Q5. Validate User Input

Problem Statement

Write a program that accepts a person’s age and checks whether the entered age is valid.

Consider ages below 0 invalid.

C Program

#include <stdio.h>

int main()
{
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age < 0)
    {
        printf("Error: Age cannot be negative.");
    }
    else
    {
        printf("Valid age = %d", age);
    }

    return 0;
}

Sample Output

Enter your age: -5
Error: Age cannot be negative.

Explanation

The program checks:

if (age < 0)

If the user enters a negative value, the program reports an error.

Input validation is important because users may enter values that do not make sense for the program.

Concepts Covered

  • Input validation
  • Error messages
  • Conditional statements
  • User input

Q6. Handle a Failed scanf() Input

Problem Statement

Write a program that checks whether the user actually entered an integer.

C Program

#include <stdio.h>

int main()
{
    int number;

    printf("Enter an integer: ");

    if (scanf("%d", &number) == 1)
    {
        printf("You entered: %d", number);
    }
    else
    {
        printf("Error: Invalid integer input.");
    }

    return 0;
}

Sample Output

If the user enters:

25

Output:

You entered: 25

If the user enters:

abc

Output:

Error: Invalid integer input.

Explanation

scanf() returns the number of input values that it successfully reads.

Here:

scanf("%d", &number)

should successfully read one integer.

Therefore:

scanf("%d", &number) == 1

means the integer was successfully read.

If the user enters text instead of an integer, scanf() does not successfully read the expected value.

Concepts Covered

  • scanf() return value
  • Input validation
  • Error checking
  • User input

Q7. Use perror() to Display an Error

Problem Statement

Write a program that attempts to open a file for reading. If the file cannot be opened, use perror() to display an error message.

C Program

#include <stdio.h>

int main()
{
    FILE *file;

    file = fopen("data.txt", "r");

    if (file == NULL)
    {
        perror("Error opening file");
        return 1;
    }

    printf("File opened successfully.");

    fclose(file);

    return 0;
}

Sample Output

If data.txt does not exist, the exact message can vary by operating system, for example:

Error opening file: No such file or directory

Explanation

fopen() attempts to open the file.

If the file cannot be opened:

file == NULL

will be true.

The program then calls:

perror("Error opening file");

perror() prints the supplied message along with an implementation-defined description of the most recent error indicated through the C library’s error mechanism.

Concepts Covered

  • File error handling
  • NULL
  • fopen()
  • perror()
  • FILE

Q8. Use Return Values for Error Handling

Problem Statement

Create a function that divides two numbers. The function should return -1 when the divisor is zero.

C Program

#include <stdio.h>

int divide(int a, int b, int *result)
{
    if (b == 0)
    {
        return -1;
    }

    *result = a / b;

    return 0;
}

int main()
{
    int result;
    int status;

    status = divide(20, 5, &result);

    if (status == 0)
    {
        printf("Result = %d", result);
    }
    else
    {
        printf("Error: Division by zero.");
    }

    return 0;
}

Sample Output

Result = 4

Explanation

The function checks:

if (b == 0)

If the divisor is zero, it returns:

return -1;

Otherwise, it calculates the result and returns:

return 0;

The calling program checks the return value:

if (status == 0)

This pattern is commonly used in C because many C functions communicate success or failure through return values.

Concepts Covered

  • Function return values
  • Error codes
  • Pointers
  • Division validation
  • Error handling

Q9. Debug an Incorrect for Loop

Problem Statement

The following program is intended to print numbers from 1 to 5, but it contains a logical error. Find and fix it.

Incorrect C Program

#include <stdio.h>

int main()
{
    int i;

    for (i = 1; i < 5; i++)
    {
        printf("%d\n", i);
    }

    return 0;
}

Correct C Program

#include <stdio.h>

int main()
{
    int i;

    for (i = 1; i <= 5; i++)
    {
        printf("%d\n", i);
    }

    return 0;
}

Sample Output

1
2
3
4
5

Explanation

The original condition was:

i < 5

This stops the loop before i reaches 5.

The corrected condition is:

i <= 5

Now 5 is also printed.

This is a logical error because the program can compile and run, but the output does not match the intended requirement.

Concepts Covered

  • Debugging loops
  • Logical errors
  • for loop
  • Loop conditions

Q10. Create a Program with Error Handling for a Simple Calculator

Problem Statement

Create a calculator that accepts two numbers and an operator. Handle division by zero and an invalid operator.

C Program

#include <stdio.h>

int main()
{
    float a, b;
    char operator;

    printf("Enter first number: ");
    scanf("%f", &a);

    printf("Enter operator (+, -, *, /): ");
    scanf(" %c", &operator);

    printf("Enter second number: ");
    scanf("%f", &b);

    switch (operator)
    {
        case '+':
            printf("Result = %.2f", a + b);
            break;

        case '-':
            printf("Result = %.2f", a - b);
            break;

        case '*':
            printf("Result = %.2f", a * b);
            break;

        case '/':
            if (b == 0)
            {
                printf("Error: Cannot divide by zero.");
            }
            else
            {
                printf("Result = %.2f", a / b);
            }
            break;

        default:
            printf("Error: Invalid operator.");
    }

    return 0;
}

Sample Output 1

Enter first number: 20
Enter operator (+, -, *, /): /
Enter second number: 5
Result = 4.00

Sample Output 2

Enter first number: 20
Enter operator (+, -, *, /): /
Enter second number: 0
Error: Cannot divide by zero.

Sample Output 3

Enter first number: 20
Enter operator (+, -, *, /): %
Enter second number: 5
Error: Invalid operator.

Explanation

This program handles two common problems.

First, it checks division by zero:

if (b == 0)

Second, the default section handles an operator that is not supported:

default:
    printf("Error: Invalid operator.");

Instead of allowing invalid situations to produce unexpected behavior, the program checks them explicitly.

Concepts Covered

  • Error handling
  • switch
  • Input validation
  • Division by zero
  • Invalid input
  • Conditional statements

Key Takeaways

  • Errors are a normal part of learning C programming.
  • Syntax errors occur when C syntax rules are broken.
  • Compilation errors prevent successful compilation.
  • Linker errors can occur when required function definitions are missing during linking.
  • Runtime problems occur while the program is executing.
  • Logical errors produce incorrect results even though the program may run.
  • printf() can be used to inspect variable values while debugging.
  • Always validate important user input.
  • Check for division by zero before performing division.
  • scanf() returns the number of successfully matched input items.
  • perror() can provide an error message for certain C library operations.
  • Functions can communicate success or failure through return values.
  • Reading compiler error messages carefully is an important debugging skill.

FAQs

1. What is debugging in C?

Debugging is the process of finding, understanding, and fixing errors or unexpected behavior in a C program.

2. What is a syntax error in C?

A syntax error occurs when the program does not follow the syntax rules of C, such as forgetting a semicolon or closing parenthesis.

3. What is a logical error in C?

A logical error occurs when the program runs but produces an incorrect result because the program’s logic is wrong.

4. How can I debug a C program?

Start by reading the compiler error, checking the reported line, examining variable values, checking conditions and formulas, and testing different inputs. Debuggers provided by IDEs can also be used to execute a program step by step.

5. How can I prevent division by zero in C?

Check the divisor before performing the division:

if (b == 0)
{
    printf("Error");
}
else
{
    result = a / b;
}

6. What does scanf() return in C?

scanf() returns the number of input items that were successfully matched and assigned. For example, when reading one integer successfully, it normally returns 1.

7. What is perror() used for in C?

perror() prints a programmer-supplied message followed by a description associated with the current error indication from the C library.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top