C Programming Tutorial 12 – Arithmetic Expressions

In the previous blog, we learned how to take input and put it on the screen.  Now, let’s create a new variable, area, and make a formula! Are you new here? Start at the beginning!

Before we start working on that formula, we need to discuss operators. An operator is a thing that takes some value and does something with it. We’ve discussed the assignment operator. The assignment operator takes a value and assigns it to a variable.

Writing Formulas

When it comes to writing formulas, we have to use arithmetic operators.  You’ve seen some of these I’m sure, but just to make sure you know the most basic important ones:

+, -, /, and *.

We also have to consider the order of operations. / and * happen first from left to right, and then + – happen next.

We can also use parenthesis to force certain operators to go first.

Now, let’s write that formula.

Now, do you guys notice anything wrong with this code? This is a perfect example of what some may consider to be a logical error. A logical error is when your program compiles, but it doesn’t do what you expect it to do.

Take a moment to see if you can spot the problem. Let’s run it and see what happens.

The problem is that we are storing this data as an integer. This is giving us results we are not expecting because values are being truncated to be an integer. Truncation is when we cut off the decimal values and do not round. so if we have 1.999999, it gets truncated to 1.

To fix this, we have to introduce some new data types. This int here is an example of a data type. A data type is a description of data that tells C how to interpret that data. To use decimals, we want to use a new data type called double.

When we set everything to double, we are a step closer, but there is another problem. These format strings, the %i is telling C that we are expecting integers. We are also going to have to change that to a new format which uses %d. Now everything should work as expected.

Conclusion

This is our very first useful program! It takes a number, runs it through a fancy pants mathematical algorithm and spits it back out. You can take what you’ve learned from this video and write software to solve some of your math homework.

In the next blog we are talking about basic type casting. Don’t miss it!

Leave a Reply

Your email address will not be published. Required fields are marked *