C Tutorial

C Project: Calculator

A four-function calculator with a switch on the operator and a guard for divide-by-zero.

What you will build

This project is a four-function calculator in C17: add, subtract, multiply, and divide. The operator is a single char. A switch picks the branch. Division checks the right-hand value first so a zero divisor never reaches the / operator.

The programs on this page use hardcoded operands so they compile and print at once. ClickTry it in C under an example to open /c/try. That editor is gcc.

Switch on a char operator

You can switch on a char because a character is an integer code. The labels are character constants: '+', '-', '*', '/'. Each case computes one result and prints it. default covers any other symbol.

Example

#include <stdio.h>

int main(void) {
  double a = 12.0;
  double b = 4.0;
  char op = '*';

  switch (op) {
    case '+':
      printf("%.1f\n", a + b);
      break;
    case '-':
      printf("%.1f\n", a - b);
      break;
    case '*':
      printf("%.1f\n", a * b);
      break;
    case '/':
      printf("%.1f\n", a / b);
      break;
    default:
      printf("unknown operator\n");
      break;
  }
  return 0;
}

Change op to '+' or '/' and compile again. Leave the numbers asdouble so division keeps a fractional part. Integer / would truncate.

Guard divide-by-zero

If b is 0.0, do not evaluate a / b. Print a clear message and skip the result. A helper that returns 0 on failure and 1 on success keeps main short. The result is written through a pointer so the function can return a status and a number.

Example

#include <stdio.h>

int divide(double a, double b, double *out) {
  if (b == 0.0) {
    return 0;
  }
  *out = a / b;
  return 1;
}

int main(void) {
  double result;

  if (divide(8.0, 2.0, &result)) {
    printf("8.0 / 2.0 = %.1f\n", result);
  } else {
    printf("cannot divide by zero\n");
  }

  if (divide(8.0, 0.0, &result)) {
    printf("8.0 / 0.0 = %.1f\n", result);
  } else {
    printf("cannot divide by zero\n");
  }
  return 0;
}

Compile this in /c/try. You should see one successful quotient and one refused division. That is the C editor, not the Python, HTML, or C++ playground.

A batch of problems

A real calculator run is a list of problems, not one pair of numbers. Store each problem as a small struct: left value, operator, right value. Loop the array. Call one apply function that switches on the operator and reuses the zero check for division.

Example

#include <stdio.h>

struct Problem {
  double a;
  char op;
  double b;
};

int apply(double a, char op, double b, double *out) {
  switch (op) {
    case '+':
      *out = a + b;
      return 1;
    case '-':
      *out = a - b;
      return 1;
    case '*':
      *out = a * b;
      return 1;
    case '/':
      if (b == 0.0) {
        return 0;
      }
      *out = a / b;
      return 1;
    default:
      return -1;
  }
}

int main(void) {
  struct Problem list[] = {
      {10.0, '+', 3.0},
      {10.0, '-', 3.0},
      {10.0, '*', 3.0},
      {10.0, '/', 4.0},
      {10.0, '/', 0.0},
      {10.0, '%', 3.0},
  };
  int n = (int)(sizeof list / sizeof list[0]);

  for (int i = 0; i < n; i++) {
    double result;
    int status = apply(list[i].a, list[i].op, list[i].b, &result);
    if (status == 1) {
      printf("%.1f %c %.1f = %.2f\n", list[i].a, list[i].op, list[i].b, result);
    } else if (status == 0) {
      printf("%.1f %c %.1f : cannot divide by zero\n",
             list[i].a, list[i].op, list[i].b);
    } else {
      printf("unknown operator '%c'\n", list[i].op);
    }
  }
  return 0;
}

sizeof list / sizeof list[0] is the number of elements. The last two rows exercise the error paths: a zero divisor and a character that is not one of the four operators.

Optional typed input

After the batch program prints a stable table, you can read one problem with scanf. The listing below is complete, but it waits for input. Prefer the hardcoded programs above in/c/try unless you are ready to type values.

Example

#include <stdio.h>

int main(void) {
  double a;
  double b;
  char op;
  double result;

  printf("enter a op b: ");
  if (scanf("%lf %c %lf", &a, &op, &b) != 3) {
    printf("bad input\n");
    return 1;
  }

  switch (op) {
    case '+':
      result = a + b;
      break;
    case '-':
      result = a - b;
      break;
    case '*':
      result = a * b;
      break;
    case '/':
      if (b == 0.0) {
        printf("cannot divide by zero\n");
        return 1;
      }
      result = a / b;
      break;
    default:
      printf("unknown operator\n");
      return 1;
  }

  printf("%.4f\n", result);
  return 0;
}

Common mistakes

  • Forgetting break after a case. Execution then falls into the next operator and you print two results or the wrong one.
  • Switching on a string. C switch does not accept an array of char. Use onechar, or compare strings with strcmp in an if chain.
  • Storing operands as int. Then 10 / 4 becomes 2. Usedouble and print with %.2f.
  • Dividing first and checking zero afterwards. The check must run before the division.

Practice

  1. Add a remainder case for integers only: if the operator is '%' and both values are whole, print the remainder; otherwise print an error.
  2. Reject a zero divisor with a message that includes both operands, not a generic line.
  3. Extend the batch program with three more problems of your own and confirm every line of output by hand.

FAQ: C Project: Calculator

Common questions about this page.

What is the StudyGrid C tutorial?

The StudyGrid C tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, pointers, structs, files, and the standard library. Each chapter has copy-and-run examples.

Should I run c calculator project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c calculator project in this C C lesson (C Project: Calculator).

Is the C editor the same as Try Python, Try HTML, or Try C++?

No. Try C compiles with gcc at /c/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. Try C++ stays at /cpp/try. C lessons never open those editors.

Do I need to install a compiler to learn C?

No. Open a chapter, click Try it in C, and compile in the browser. You can also download a .c file and compile locally with gcc.

Where should I start the C tutorial?

Start at C Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After pointers, open C Examples, then files and bitwise. Use Next at the bottom of each chapter.

Is the C tutorial free?

Yes. The C workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.