0% found this document useful (0 votes)
15 views3 pages

Functions Assignment

Uploaded by

Erik Kyama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Functions Assignment

Uploaded by

Erik Kyama
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

FUNCTIONS ASSIGNMENT

QUESTION 1

Amend your calculator code to have individual functions handling its operation. These functions need to
be callable by the main() function and return their response to main.

#include <stdio.h>

double add(double num1, double num2) {

return num1 + num2;

double subtract(double num1, double num2) {

return num1 - num2;

double multiply(double num1, double num2) {

return num1 * num2;

double divide(double num1, double num2) {

if (num2 == 0) {

printf("Error: Division by zero\n");

return -1; // Or some other error flag

} else {

return num1 / num2;

int main() {

char operator;
double num1, num2, result;

printf("Enter an operator (+, -, *, /): ");

scanf("%c", &operator);

printf("Enter two numbers: ");

scanf("%lf %lf", &num1, &num2);

switch (operator) {

case '+':

result = add(num1, num2);

break;

case '-':

result = subtract(num1, num2);

break;

case '*':

result = multiply(num1, num2);

break;

case '/':

result = divide(num1, num2);

break;

default:

printf("Invalid operator\n");

result = -1; // Or some other error flag

if (result != -1) { // Check for error flags

printf("%.1lf %c %.1lf = %.1lf\n", num1, operator, num2, result);

}
return 0;

You might also like