Skip to main content

Section 12.2 Practice: Single Functions

Check Your Understanding Check Your Understanding

1.

Please add the correct prototype for the square() function to the program below:

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

#include <stdio.h>

/* insert prototype here */


/* Do not change anything below this point  */

int main(void) {
  float x;
  float result;

  printf("Please enter a number to be squared: ");
  scanf("%f", &x);
  result = square(x);
  printf("The square of %.2f is %.2f.", x, result);

  return(0);
}

float square(float x) {
  return(x*x);
}
When your program performs correctly you’ll be given a keyword to enter in Canvas.

2.

Write a function divide() that takes two floats as arguments and returns a float, namely the first number divided by the second. Obviously, you shouldn’t be dividing by zero...
You may assume that your function is not called with such input.

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

#include <stdio.h>

float divide(float, float);

/* Do not change the main function! */
int main(void) {
  float x,y;
  float result;
  
  printf("Please enter two numbers for division: ");
  scanf("%f %f", &x, &y);
  if (y==0.0) y = 1;
  result = divide(x,y);
  printf("%.2f / %.2f = %.2f. \n", x, y, result);
  
  return(0);
}

/* Please add your function here!*/
When your program performs correctly you’ll be given a keyword to enter in Canvas.