# Basic C Arithmetic

## Doing simple calculations in C

*To get all the required features of this website to work you need to Enable Javascipt on your browser.*

### Introduction

In any program, calculations are paramount. Whether you are creating spreadsheet software adding column data, or a video game clocking up the score; they are still doing calculations the same way. In C, doing calculations are straight forward once you get your head around the basics.

As mentioned in our previous tutorial, data is carried in *variables*; which can be used to calculate and collect the total value. To begin with we will go into a simple introduction. Your maths skill can be minimal, but you will understand the logic of doing arithmetic in C.

The key thing is, you need to know the data type that you are using for calculating. You can mix two different data type values and return a calculation in one type or another, that is called *typecasting (or casting)*. That will be covered later in this tutorial, as it is a major point you have to cover when writing C programs. First thing, we are going to cover the different basic data types that are available for us to use. Some are larger than others, but you can use them in the same way. The table below will explain the differences between the types.

### Basic Data Types in ANSI/ISO C

Data Type | Bits Size | Byte Size | Range | Brief Description |

char | 8 | 1 | -128 to 127 | Can be used for small integer numeric values; Both Negative and Positive. Or can be used to encode simple ASCII character data, or buffered binary data. |

unsigned char | 8 | 1 | 0 to 255 | Can be used for small Integer numeric values; Only Positive. Or can be used to small booleans, buffered binary data or incremental data processes. |

short | 16 | 2 | -32,768 to 32,767 |
Both Negative and Positive Integer numeric value. Could be used for medium number calculations. |

unsigned short | 16 | 2 | 0 to 65,535 |
Positive Only Integer numeric values. Same size as a short. Generally used for medium number calculations, or Unicode character encodings. |

int | 32 | 4 | –2,147,483,648 to 2,147,483,647 |
Both Negative and Positive Integer numeric value. Allows a larger range than short. In some compilers, int is the same size and scop-e as short. By Default, int is the standard integer data type used. |

unsigned int | 32 | 4 | 0 to 4,294,967,295 |
Positive Only Integer numeric value. Similar to long in size, but not range. In some compilers, it can be the same size and scope as unsigned short |

long | 32 | 4 | –2,147,483,648 to 2,147,483,647 | Integer number identical to int in size and value range scope. Difference is that int is the standard integer data type used. |

unsigned long | 32 | 4 | 0 to 4,294,967,295 | In most compilers, integer identical to unsigned int in size and value range scope. |

float | 32 | 4 | 3.4E +/- 38 (7 digits) | Floating Point value, which is good for smaller to medium Real digit numbers. |

double | 64 | 8 | 1.7E +/- 308 (15 digits) | Double floating precision to a float data value. Useful for large Real digit numbers. |

### Importance of Data Types

Now you can see that it is important to use the right data type for the right task. You do not want to use *long* to use data which will range in your code at runtime (during execution) between 0 to 30, it would be more appropriate for you to use *char*, or if you wish for a bigger value *short*, or even bigger *int*. But remember, the bigger the range that your variable data type will be using, the larger the memory foot print will become, so be careful when creating new variables. You may have noticed that in the table, there are *unsigned* data types; this basically means the value must only be a positive numeric value with the lowest value being 0. By default, and *int*, *char*, or *short*, are classified as *signed*; which means that there is both a positive and negative numeric value. You can place the *signed* keyword before a data type, but it would make no difference. You cannot assign *unsigned* to either a *float*, or a *double*. When you are creating your variable (or in later tutorials your own created functions), naming is important. These names are also known as *identifiers*, and it is important that you remember the name of each named variable you create. To keep things simple for yourself and any co-developers you may work with in the future, there are a few tips to keep in mind, like for example, identifiers are *case sensitive*, so if you name a variable identifier *employeename*, it will be a total different entity to another identifier *EmployeeName*. Upper or lower case names can be assigned in any way that makes logical sense. This wouldn't happen in real time development in the first place, as naming two variables like this would be impractical and most of all confusing. Another thing to keep in mind, you cannot name them after either *C keywords* or *already declared functions or variables identifers*, as the compiler will display an error explaining to you that they are already in use. So avoid names such as *break*,*return*, or *printf*. You can place underscore in your identifier name, but not spaces or tabs.

### Using Operators for Calculations in C

Now you get the basics of defining different data type variables, we are going to go through the basic calculations before we get into the main coding. To ensure that the calculations are done, we would have to use the necessary operators needed to do the maths. The table below show the basic operators that can be used in C.

Operator | Operator Name | Syntax | Task |

= | Basic Assignment | x = y | Assign Value, the example shows the value y being assigned to x. |

+ | Addition | x + y | Adds y value to x value |

- | Subtraction | x - y | Subtracts y from x value |

* | Multiplication | x * y | Multiples x by y value |

/ | Division | x / y | Divides x by y value |

% | Modulus | x % y | (Modulo) Gets remainder of x once value of y is used. Only used with integer value. (eg 5 mod 4 equals 1) |

++ | Increment | ++x or x++ | Increments either by Prefix (++x), or by Suffix (x++) |

-- | Decrement | --x or x-- | Decrements either by Prefix (--x), or by Suffix (x--) |

Now we have gone through the operators, it is important to look at some simple snippets of code which do simple arithmetic. In the example below you can see there are the initial integer variables with the *const* keyword. *Const* is placed before declaring a variable; which you set the data value *constant*. Once the value is set, it will stay the same during the scope it is in. It is useful for using with other variables for calculations, like the example shown.

const int x = 1; const int y = 2; const int z = 4; const int w = 8; int value_one = w * z; // VALUE 32 int value_two = x + y; // VALUE 3 int value_three = w / y; // VALUE 4 int value_four = (y + x) % z; // VALUE 3

Now those examples should clear how the base level calculations are done, we are now going through the main program for this tutorial. It is a simple Celsius to fahrenheit conversion. You enter a figure in degrees celsius, and the program will calculate and print the value in fahrenheit. This should be straight forward to execute. The first thing we will do is sketch a formula which we can use to convert to either Celsius to fahrenheit or visa versa.

Here is a logical math method...

Conversion From | Logical Math Method |

Fahrenheit to Celsius | °F to °C Deduct 32, then multiply by 5, then divide by 9 |

Celsius to Fahrenheit | °C to °F Multiply by 9, then divide by 5, then add 32 |

Conversion From To | Scientific Method |

Fahrenheit to Celsius | °C = (°F - 32) * 5 / 9 |

Celsius to Fahrenheit | °F = (°C * 1.8) + 32 |

### Example Code In Detail

**A note to show that the Celsius to Fahrenheit methods are different** in both tables. That was on purpose to empathise the flexibility you can use to calculate such formula; as long as it returns the correct value. Now we will go straight on with the coding. The program is relatively short and self explanatory.

#include <stdio.h> int celsius; float fahrenheit;

We only need the *int main()* function entry (defined as *local variables*, when inside a funciton scope), we have declared it outside the function scope; in stark contrast to the previous tutorial. This means the variables are *Global*, as they can be accessed throughout the program and any function within the program (more on this in later tutorials). The first variable that we are going to initialise is the *celsius* variable, which will be declared as a *int*. This will be variable that handles the input the user will enter. The second variable *fahrenheit*, is the identifier that will handle the converted value; this you have noticed is a *float*. This makes sense as fahrenheit is value should be as accurate as possible. This is definately will need typecasting (or *casting*), as we are using two different data types for our calculations.

printf("Can you please enter the Temperature in Degrees Celsius... "); scanf("%d", &celsius);

Now we are in the int main function scope (see above), dealing with the main body of the operation. First we print the message for the user to ask them to enter a Celsius value. When the *scanf* reads the inputted data, the value is assigned to the *celsius* variable. Now we have the entered value, we need to do the conversion. So we will assign the formula to the *fahrenheit* variable. Remember this one is a float and we will have to mix the int *celsius* value, which means that we have to do *typecasting*. In the code below you can see *fahrenheit* being assigned a value. It is the same formula we used in one of the table examples above. The only thing is we are strictly dealing with floating points, so decimal numbers will be implemented here. So we care going to need to typecast the *celsius* variable, so in the code below you can see *(float)* inside the parenthesis before the celsius data is placed in the code line. That is because it is typecasting the data; this procedure converts the celsius value from integer to float, hence the data type *float* being placed inside the parenthesis. The add value has become decimalised to fit into the floating value that fahrenheit will calculate. At the end of the numeric values in the formula, we have placed a *f* at the end, as it differentiates the floating point value as a *float* rather than *double*. It is important in C and most other language that if you are going to mix your data typed values, typecast the values that you are mixing with. Because as we mentioned earlier in this article, different data types have different sizes. If we are using a *short* data value to assign to a *long* variable, we would have to convert by typecasting the short value from 2 to 4 bytes to fit a long value. This is especially important if one of the values were unsigned. If you do not follow this rule, you can have many problems with the sums and other undefined behaviour (depending on different Compilers!), which we will go through when typecasting becomes more critical.

fahrenheit = ((float)celsius * 1.8f) + 32.0f; printf("The Converted value has returned as %.2f Degrees Fahrenheit",fahrenheit);

Displaying the data is the most important thing to do once the calculation is done. So we use our good old friend *printf*, which uses the *format specifier* to display the calculated *fahrenheit* value in the string. You may have noticed that the *format specifier* has a number attached to it; all it means that when we are using *%.2f* to *keep the precision of two* (number of digits after the decimal point - in this case two). Once that is executed, we close the program the usual way.

fflush(stdin); getchar(); return 0;

### Summary

Now we have coded the Celsius to Fahrenheit converter, your minor task for you to do is to program your own Fahrenheit to Celsius converter. Follow the mathematical methods shown before and reproduce it in code. So instead of entering celsius, enter the fahrenheit, then you know all the rest. This isn't anything more to see how far you have gone since reading this article. If you can do it, then you deserve a great pat on the back, and the confidence to go onto the next article.

/* SIMPLE ARITHMETIC main.c Reliant Code Doing the Maths... */ #include <stdio.h> int celsius; float fahrenheit; int main() { printf("Can you please enter the Temperature in Degrees Celsius... "); scanf("%d", &celsius); fahrenheit = ((float)celsius * 1.8f) + 32.0f; printf("The Converted value has returned as %.2f Degrees Fahrenheit",fahrenheit); fflush(stdin); getchar(); return 0; }