Evaluate Rational Expressions in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to evaluate rational expressions in C programming. The lab covers the fundamental steps of reading the numerator and denominator expressions, computing the fraction value safely by handling division by zero, and printing the final result. This hands-on exercise will help you develop the necessary skills to work with algebraic expressions using C.

The lab starts by guiding you through the process of reading the numerator and denominator inputs from the user, ensuring that the values are properly stored in your program. It then introduces the concept of handling division by zero, a common issue when working with fractions, and demonstrates how to address this scenario. Finally, the lab covers the computation of the fraction value and the output of the final result.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/variables -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/data_types -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/operators -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/if_else -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/user_input -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} c/math_functions -.-> lab-435178{{"`Evaluate Rational Expressions in C`"}} end

Read Numerator and Denominator Expressions

In this step, you will learn how to read numerator and denominator expressions in C, which is a fundamental skill for evaluating rational expressions.

First, create a new C file to implement rational expression input:

cd ~/project
nano rational_expressions.c

Now, add the following code to read numerator and denominator:

#include <stdio.h>

int main() {
    int numerator, denominator;

    printf("Enter the numerator: ");
    scanf("%d", &numerator);

    printf("Enter the denominator: ");
    scanf("%d", &denominator);

    printf("Numerator: %d\n", numerator);
    printf("Denominator: %d\n", denominator);

    return 0;
}

Compile and run the program:

gcc rational_expressions.c -o rational_expressions
./rational_expressions

Example output:

Enter the numerator: 10
Enter the denominator: 5
Numerator: 10
Denominator: 5

Let's break down the code:

  • scanf() is used to read integer inputs from the user
  • %d format specifier is used for integer input
  • We store the numerator and denominator in separate integer variables
  • printf() is used to display the input values

Compute the Fraction Value

In this step, you will learn how to compute the fraction value safely by handling potential division by zero and performing the calculation.

Update the previous rational_expressions.c file to include fraction computation:

cd ~/project
nano rational_expressions.c

Modify the code to compute the fraction value:

#include <stdio.h>

int main() {
    int numerator, denominator;
    float fraction_value;

    printf("Enter the numerator: ");
    scanf("%d", &numerator);

    printf("Enter the denominator: ");
    scanf("%d", &denominator);

    // Check for division by zero
    if (denominator == 0) {
        printf("Error: Division by zero is not allowed.\n");
        return 1;
    }

    // Compute fraction value
    fraction_value = (float)numerator / denominator;

    printf("Numerator: %d\n", numerator);
    printf("Denominator: %d\n", denominator);
    printf("Fraction Value: %.2f\n", fraction_value);

    return 0;
}

Compile and run the program:

gcc rational_expressions.c -o rational_expressions
./rational_expressions

Example output:

Enter the numerator: 10
Enter the denominator: 4
Numerator: 10
Denominator: 4
Fraction Value: 2.50

Key points in the code:

  • Added a check for division by zero to prevent runtime errors
  • Used (float) type casting to ensure floating-point division
  • Displayed the fraction value with two decimal places using %.2f

Print the Result or Handle Division by Zero

In this step, you will enhance the rational expression program to provide more robust error handling and result presentation.

Update the rational_expressions.c file to improve output and error handling:

cd ~/project
nano rational_expressions.c

Modify the code to include advanced error handling and result formatting:

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

int main() {
    int numerator, denominator;

    // Input validation and error handling
    printf("Enter the numerator: ");
    if (scanf("%d", &numerator) != 1) {
        printf("Error: Invalid numerator input.\n");
        return 1;
    }

    printf("Enter the denominator: ");
    if (scanf("%d", &denominator) != 1) {
        printf("Error: Invalid denominator input.\n");
        return 1;
    }

    // Comprehensive division by zero handling
    if (denominator == 0) {
        printf("Error: Cannot divide by zero. Denominator must be non-zero.\n");
        return 1;
    }

    // Compute and print results with different formats
    double fraction_value = (double)numerator / denominator;

    printf("\n--- Rational Expression Results ---\n");
    printf("Numerator:      %d\n", numerator);
    printf("Denominator:    %d\n", denominator);
    printf("Fraction Value: %.2f\n", fraction_value);
    printf("Integer Result: %d\n", numerator / denominator);
    printf("Remainder:      %d\n", numerator % denominator);

    return 0;
}

Compile and run the program:

gcc rational_expressions.c -o rational_expressions
./rational_expressions

Example outputs:

Successful computation:

Enter the numerator: 10
Enter the denominator: 4

--- Rational Expression Results ---
Numerator:      10
Denominator:    4
Fraction Value: 2.50
Integer Result: 2
Remainder:      2

Division by zero:

Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero. Denominator must be non-zero.

Invalid input:

Enter the numerator: abc
Error: Invalid numerator input.

Key improvements:

  • Added input validation using scanf() return value
  • Enhanced error messages for different scenarios
  • Provided multiple result representations
  • Used double for more precise floating-point calculations

Summary

In this lab, you learned how to read numerator and denominator expressions in C, which is a fundamental skill for evaluating rational expressions. You also learned how to compute the fraction value safely by handling potential division by zero and performing the calculation. Finally, you implemented the ability to print the result or handle division by zero. These steps provide a solid foundation for working with rational expressions in C programming.

Other C Tutorials you may like