A variable is an entity whose value can be changed. In C, each variable has a data type. We choose the data type based on what we want the variable to store.
Some common primitive data types in C are:
- integer
- floating point
- character
- double floating point
Integer
These are positive and negative whole numbers. An integer can be used to store the age of a person:
int age = 13;
printf("My age is %i\n",age);
The equal sign (=) is referred to as the assignment operator. We use it to assign a value to a variable. The value on the right of the sign is stored in the variable on the left.
Floating point
These include positive and negative whole numbers and decimal numbers. We can use a float to store an amount of money or the speed of a person:
float allowance = 500.20;
float speed = 10.5;
printf("My allowance of $%.2f motivates me to run at a speed of %f m/s\n",allowance,speed);
Character
These include a letters, numbers and special characters. We can use a character to store a grade:
char grade = 'A';
printf("I received a grade %c for Computer Science!\n",grade);
Notice how we need to have single quotation marks to show what the character is.
Double floating point
These are used for scientific applications where we want to store more precise values for decimal numbers. Doubles are more precise than floats. We can use a double in order to calculate the period of a simple pendulum:
#include <stdio.h>
#include <math.h>
int main(void){
double length = 0.5; // length of 0.5 meters
double g = 9.81; // in meters per square second
double period = 2*M_PI*sqrt(length/g);
printf("The period of a simple pendulum with length %lf is %lf\n",length,period);
printf("The period of a simple pendulum with length %e is %e\n",length,period);
printf("The period of a simple pendulum with length %g is %g\n",length,period);
return 0;
}
The format specifier %e is used to express the answer in standard form (scientific notation). The format specifier %g can produce scientific notation or a rounded form of the number being displayed.
Lightning round
1) What is the format specifier used for characters?
- %i
- %d
- %g
- %c