Skip to main content

Section 12.5 Practice Your Functions!

Subsection 12.5.1 Functions: Your Turn!

Activity 12.1.

Write a C program that converts temperature from Fahrenheit to Celsius or from Celsius to Fahrenheit, depending on user input. Here is a sample session:
Please enter a temperature: 45 F
45 degrees Fahrenheit correspond to approximately 7.2 degrees Celsius.
And another sample session:
Please enter a temperature: 28 C
28 degrees Celsius correspond to approximately 82.4 degrees Fahrenheit.
The overall structure of the program is provided for you below. Your program should use functions for the temperature conversions: one for Fahrenheit to Celsius, and another for Celsius to Fahrenheit.

Compile and run the code below in your own C environment.

#include <stdio.h>

/* prototypes here */

int main(void) {
    
    int usertemp;
    char unit;
    float convertedtemp;
    
    printf("Please enter a temperature: ");
    scanf("%d %c", &usertemp, &unit);
    
    /* complete the code */
    
    if (unit=='C'){
        printf("%d degrees Celsius corresponds to approximately %.1f degrees Fahrenheit.\n", usertemp, convertedtemp);
    }else if (unit=='F'){
        printf("%d degrees Fahrenheit corresponds to approximately %.1f degrees Celsius.\n", usertemp, convertedtemp);
    }
    
    return(0);
}

/* functions here */

Subsection 12.5.2 Another One!

Activity 12.2.

Write a function factorial() that accepts an integer as an argument and returns an integer, namely the factorial of the argument. A test program has already been provided for you below; you only need to write the function itself and add the prototype and the function call to the program.

Compile and run the code below in your own C environment.

#include <stdio.h>

/* prototype here */

int main(void) {
    
    int num;
    int result;
    
    printf("Please enter an integer: ");
    scanf("%d", &num);
    
    /* complete the code */
    
    printf("\n%d! = %d. \n", num, result);
    
    return(0);
}

/* function here */