C Data Types


Data Types

As explained in the , a variable in C must be a specified data type, and you must use a format specifier inside the printf() function to display it:

Example

// Create variables
int myNum = 5;             // Integer (whole number)
float myFloatNum = 5.99;   // Floating point number
char myLetter = 'D';       // Character

// Print variables
printf("%dn", myNum);
printf("%fn", myFloatNum);
printf("%cn", myLetter);

Basic Data Types

The data type specifies the size and type of information the variable will store.

In this tutorial, we will focus on the most basic ones:

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 6-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

Basic Format Specifiers

There are different format specifiers for each data type. Here are some of them:

Format Specifier Data Type Try it
%d or %i int
%f float
%lf double
%c char
%s Used for (text), which you will learn more about in a later chapter

Set Decimal Precision

You have probably already noticed that if you print a floating point number, the output will show many digits after the decimal point:

Example

float myFloatNum = 3.5;
double myDoubleNum = 19.99;

printf("%fn", myFloatNum); // Outputs 3.500000
printf("%lf", myDoubleNum); // Outputs 19.990000

If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a number that specifies how many digits that should be shown after the decimal point:

Example

float myFloatNum = 3.5;

printf("%fn", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1fn", myFloatNum); // Only show 1 digit
printf("%.2fn", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum);   // Only show 4 digits

C Exercises

Test Yourself With Exercises

Exercise:

Add the correct data type for the following variables:

 myNum = 5;
 myFloatNum = 5.99;
 myLetter = 'D';



Data Types

Login
ADS CODE