a variable in C must be a specified data type, and you must use a format specifier inside the printf() function to display it:
#include<stdio.h>
int main() {
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
The data type specifies the size and type of information the variable will store.
Data Type | Size | Description |
---|---|---|
int | 2 or 4 bytes | Stores whole numbers, without decimals |
Float | 4 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 7 decimal digits |
Double | 8 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits |
Char | 1 byte | Stores a single character/letter/number, or ASCII values |
There are different format specifiers for each data type. Here are some of them:
#include<stdio.h>
int main() {
int myNum = 5; // integer
printf("%d\n", myNum);
printf("%i\n", myNum);
return 0;
}
#include<stdio.h>
int main() {
float myFloatNum = 5.99; // Floating point number
printf("%f", myFloatNum);
return 0;
}
#include<stdio.h>
int main() {
double myDoubleNum = 19.99; // Double (floating point number)
printf("%lf", myDoubleNum);
return 0;
}
#include<stdio.h>
int main() {
char myLetter = 'D'; // Character
printf("%c", myLetter);
return 0;
}
#include<stdio.h>
int main() {
char greetings[] = "Hello World!";
printf("%s", greetings);
return 0;
}