Variables are named sections of memory that make it possible for your program to “remember” values. Your program can also use them in math expressions to perform calculations.
This example program, Variables and Calculations.c, declares variables named a, b, and c. It stores 25 in a, 17 in b, and the result of a + b in the variable named c.
/* Variables and Calculations.c Add two integer values together and display the result. */ #include "simpletools.h" // Include simpletools int main() // main function { int a = 25; // Initialize a variable to 25 int b = 17; // Initialize b variable to 17 int c = a + b; // Initialize c variable to a + b print("c = %d ", c); // Display decimal value of c }
Variables and Calculations.c declares an integer variable named a and assigns it the value 25 with int a = 25. Then, it declares a second variable named b and initializes it to 17 with int b = 17. The last integer variable it declares is named c, and stores the result of a + b in it.
Finally, it displays the value of c with print("c = %d", c). This variation on print displays a sequence of characters called a string, followed by a variable. The %d is called a format placeholder, and it tells print how to display the value stored in that variable as a decimal number, 42 in this case.
The term + is a binary operator, meaning that it performs an operation on two inputs. Examples of binary operators include:
+ Add
– Subtract
* Multiply
/ Divide
% Modulus (remainder of a division calculation)
Here is a modified version of the main routine that displays "a = , b = "with their values, and then "a + b = " and the value of c on a new line. Then, it repeats for a – b.
Notice that the second time it calculates the value of c, we don’t need to declare it with int. It’s just c = a – b. Notice also that print allows you to display more than one numeric value within your string. All it takes is two format placeholders in the string and two values, separated by commas, after the string.
PRO TIP: Displaying % with print
To display the output of the Modulus operator, use ("a mod b = ...") or ("a %% b = ...) in the print function. Since % has another purpose in print strings, just saying ("a % b = ...) will give unexpected results.