Evaluate Piecewise Functions in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to evaluate piecewise functions in C programming. The lab covers the steps to read an input value, use if/else statements to determine which formula to apply, and print the evaluated result. You will start by prompting the user to enter a value for the variable x, then implement a piecewise function with different formulas based on the input value. This lab will help you develop your skills in working with algebraic expressions and conditional logic in C.


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/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} c/variables -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} c/operators -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} c/if_else -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} c/user_input -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} c/function_declaration -.-> lab-435176{{"`Evaluate Piecewise Functions in C`"}} end

Read Input Value x

In this step, you will learn how to read an input value for a piecewise function in C programming. We'll create a simple program that allows users to input a numeric value to be used in function evaluation.

First, let's create a new C file in the project directory:

cd ~/project
nano piecewise_function.c

Now, add the following code to the file:

#include <stdio.h>

int main() {
    double x;

    // Prompt the user to enter a value for x
    printf("Enter a value for x: ");

    // Read the input value
    scanf("%lf", &x);

    // Print the input value to confirm
    printf("You entered x = %.2f\n", x);

    return 0;
}

Compile the program:

gcc piecewise_function.c -o piecewise_function

Run the program:

./piecewise_function

Example output:

Enter a value for x: 5.5
You entered x = 5.50

Let's break down the code:

  • #include <stdio.h> includes the standard input/output library
  • double x; declares a variable to store the input value
  • printf() displays a prompt to the user
  • scanf() reads the input value as a double-precision floating-point number
  • %.2f formats the output to display two decimal places

Use if/else to Determine Which Formula to Apply

In this step, you will modify the previous program to implement a piecewise function using if/else statements. We'll create a function with different formulas based on the input value x.

Let's update the piecewise_function.c file:

cd ~/project
nano piecewise_function.c

Replace the previous content with the following code:

#include <stdio.h>

// Define a piecewise function
double piecewise_function(double x) {
    // Condition 1: If x is less than 0
    if (x < 0) {
        return x * x;  // f(x) = x^2 for x < 0
    }
    // Condition 2: If x is between 0 and 5
    else if (x >= 0 && x < 5) {
        return 2 * x + 3;  // f(x) = 2x + 3 for 0 ≤ x < 5
    }
    // Condition 3: If x is greater than or equal to 5
    else {
        return x - 2;  // f(x) = x - 2 for x ≥ 5
    }
}

int main() {
    double x;

    // Prompt the user to enter a value for x
    printf("Enter a value for x: ");

    // Read the input value
    scanf("%lf", &x);

    // Calculate and print the result of the piecewise function
    double result = piecewise_function(x);
    printf("f(%.2f) = %.2f\n", x, result);

    return 0;
}

Compile the program:

gcc piecewise_function.c -o piecewise_function

Run the program with different input values:

./piecewise_function

Example output 1:

Enter a value for x: -2
f(-2.00) = 4.00

Example output 2:

Enter a value for x: 3
f(3.00) = 9.00

Example output 3:

Enter a value for x: 6
f(6.00) = 4.00

Let's break down the code:

  • piecewise_function() implements three different formulas based on x's value
  • if/else statements check the conditions and apply the appropriate formula
  • The function returns the calculated value based on the input x

Print the Evaluated Result

In this final step, you will enhance the piecewise function program to provide more detailed output and demonstrate the function's behavior across different input ranges.

Let's modify the piecewise_function.c file to add more comprehensive result printing:

cd ~/project
nano piecewise_function.c

Update the code with the following implementation:

#include <stdio.h>

// Define a piecewise function
double piecewise_function(double x) {
    // Condition 1: If x is less than 0
    if (x < 0) {
        return x * x;  // f(x) = x^2 for x < 0
    }
    // Condition 2: If x is between 0 and 5
    else if (x >= 0 && x < 5) {
        return 2 * x + 3;  // f(x) = 2x + 3 for 0 ≤ x < 5
    }
    // Condition 3: If x is greater than or equal to 5
    else {
        return x - 2;  // f(x) = x - 2 for x ≥ 5
    }
}

int main() {
    double x;

    // Prompt the user to enter a value for x
    printf("Piecewise Function Evaluator\n");
    printf("Function rules:\n");
    printf("  f(x) = x^2      for x < 0\n");
    printf("  f(x) = 2x + 3   for 0 ≤ x < 5\n");
    printf("  f(x) = x - 2    for x ≥ 5\n\n");

    printf("Enter a value for x: ");

    // Read the input value
    scanf("%lf", &x);

    // Calculate the result of the piecewise function
    double result = piecewise_function(x);

    // Provide detailed output
    printf("\nInput Analysis:\n");
    printf("  Input value x: %.2f\n", x);

    // Determine and print the applied formula
    if (x < 0) {
        printf("  Applied formula: f(x) = x^2\n");
    }
    else if (x >= 0 && x < 5) {
        printf("  Applied formula: f(x) = 2x + 3\n");
    }
    else {
        printf("  Applied formula: f(x) = x - 2\n");
    }

    // Print the final result
    printf("  Result f(x): %.2f\n", result);

    return 0;
}

Compile the program:

gcc piecewise_function.c -o piecewise_function

Run the program with different input values:

./piecewise_function

Example output 1 (x < 0):

Piecewise Function Evaluator
Function rules:
  f(x) = x^2      for x < 0
  f(x) = 2x + 3   for 0 ≤ x < 5
  f(x) = x - 2    for x ≥ 5

Enter a value for x: -3

Input Analysis:
  Input value x: -3.00
  Applied formula: f(x) = x^2
  Result f(x): 9.00

Example output 2 (0 ≤ x < 5):

Piecewise Function Evaluator
Function rules:
  f(x) = x^2      for x < 0
  f(x) = 2x + 3   for 0 ≤ x < 5
  f(x) = x - 2    for x ≥ 5

Enter a value for x: 3

Input Analysis:
  Input value x: 3.00
  Applied formula: f(x) = 2x + 3
  Result f(x): 9.00

Example output 3 (x ≥ 5):

Piecewise Function Evaluator
Function rules:
  f(x) = x^2      for x < 0
  f(x) = 2x + 3   for 0 ≤ x < 5
  f(x) = x - 2    for x ≥ 5

Enter a value for x: 6

Input Analysis:
  Input value x: 6.00
  Applied formula: f(x) = x - 2
  Result f(x): 4.00

Key improvements in this step:

  • Added detailed function rules explanation
  • Provided input analysis with the applied formula
  • Enhanced output readability
  • Demonstrated the piecewise function behavior across different input ranges

Summary

In this lab, you learned how to read an input value for a piecewise function in C programming and how to use if/else statements to determine which formula to apply based on the input value. You created a simple program that allows users to input a numeric value, and then evaluated the piecewise function using different formulas depending on the value of x. The key learning points are reading user input, implementing conditional logic with if/else statements, and applying different mathematical formulas within a piecewise function.

Other C Tutorials you may like