0% found this document useful (0 votes)
21 views15 pages

Part 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views15 pages

Part 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Data Types

As explained in the Variables chapter, 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("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);

Try it Yourself »

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. Suffic
digits

double 8 bytes Stores fractional numbers, containing one or more decimals. Suffic
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

%d or %i int
%f or %F float

%lf double

%c char

%s Used for strings (text), which you will learn more about in a later c

Note: It is important that you use the correct format specifier for the specified data type. If not, the
program may produce errors or even crash.

The char Type

The char data type is used to store a single character.

The character must be surrounded by single quotes, like 'A' or 'c', and we use the %c format specifier
to print it:

Example

char myGrade = 'A';


printf("%c", myGrade);

Try it Yourself »

Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain characters.
Note that these values are not surrounded by quotes (''), as they are numbers:

Example

char a = 65, b = 66, c = 67;


printf("%c", a);
printf("%c", b);
printf("%c", c);

Try it Yourself »

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

Notes on Characters

If you try to store more than a single character, it will only print the last character:

Example

char myText = 'Hello';


printf("%c", myText);

Try it Yourself »

Note: Don't use the char type for storing multiple characters, as it may produce errors.
To store multiple characters (or whole words), use strings (which you will learn more about in a later
chapter):

Example

char myText[] = "Hello";


printf("%s", myText);

Try it Yourself »

For now, just know that we use strings for storing multiple characters/text, and the char type for
single characters.

Numeric Types

Use int when you need to store a whole number without decimals, like 35 or 1000,
and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.

int

int myNum = 1000;


printf("%d", myNum);

Try it Yourself »

float

float myNum = 5.75;


printf("%f", myNum);

Try it Yourself »

double

double myNum = 19.99;


printf("%lf", myNum);

Try it Yourself »

float vs. double

The precision of a floating point value indicates how many digits the value can have after the decimal
point. The precision of float is six or seven decimal digits, while double variables have a precision of
about 15 digits. Therefore, it is often safer to use double for most calculations - but note that it takes
up twice as much memory as float (8 bytes vs. 4 bytes).

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example

float f1 = 35e3;
double d1 = 12E4;
printf("%f\n", f1);
printf("%lf", d1);

Try it Yourself »

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("%f\n", myFloatNum); // Outputs 3.500000


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

Try it Yourself »

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("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits

Try it Yourself »

Get the Memory Size

We introduced in the data types chapter that the memory size of a variable varies depending on the
type:

Data Type Size

int 2 or 4 bytes

float 4 bytes

double 8 bytes

char 1 byte

The memory size refers to how much space a type occupies in the computer's memory.
To actually get the size (in bytes) of a data type or variable, use the sizeof operator:

Example

int myInt;
float myFloat;
double myDouble;
char myChar;

printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));

Try it Yourself »

Note that we use the %lu format specifer to print the result, instead of %d. It is because the compiler
expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some
computers it might work with %d, but it is safer to use %lu.

Why Should I Know the Size of Data Types?

Knowing the size of different data types is important because it says something about memory usage
and performance.

For example, the size of a char type is 1 byte. Which means if you have an array of 1000 char values,
it will occupy 1000 bytes (1 KB) of memory.

Using the right data type for the right purpose will save memory and improve the performance of
your program.

You will learn more about the sizeof operator later in this tutorial, and how to use it in different
scenarios.

Real-Life Example

Here's a real-life example of using different data types, to calculate and output the total cost of a
number of items:

Example

// Create variables of different data types


int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';

// Print variables
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);

Try it Yourself »
Type Conversion

Sometimes, you have to convert the value of one data type to another type. This is known as type
conversion.

For example, if you try to divide two integers, 5 by 2, you would expect the result to be 2.5. But since
we are working with integers (and not floating-point values), the following example will just output 2:

Example

int x = 5;
int y = 2;
int sum = 5 / 2;

printf("%d", sum); // Outputs 2

Try it Yourself »

To get the right result, you need to know how type conversion works.

There are two types of conversion in C:

 Implicit Conversion (automatically)

 Explicit Conversion (manually)

Implicit Conversion

Implicit conversion is done automatically by the compiler when you assign a value of one type to
another.

For example, if you assign an int value to a float type:

Example

// Automatic conversion: int to float


float myFloat = 9;

printf("%f", myFloat); // 9.000000

Try it Yourself »

As you can see, the compiler automatically converts the int value 9 to a float value of 9.000000.

This can be risky, as you might lose control over specific values in certain situations.

Especially if it was the other way around - the following example automatically converts the float
value 9.99 to an int value of 9:

Example

// Automatic conversion: float to int


int myInt = 9.99;

printf("%d", myInt); // 9
Try it Yourself »

What happened to .99? We might want that data in our program! So be careful. It is important that
you know how the compiler work in these situations, to avoid unexpected results.

As another example, if you divide two integers: 5 by 2, you know that the sum is 2.5. And as you
know from the beginning of this page, if you store the sum as an integer, the result will only display
the number 2. Therefore, it would be better to store the sum as a float or a double, right?

Example

float sum = 5 / 2;

printf("%f", sum); // 2.000000

Try it Yourself »

Why is the result 2.00000 and not 2.5? Well, it is because 5 and 2 are still integers in the division. In
this case, you need to manually convert the integer values to floating-point values. (see below).

Explicit Conversion

Explicit conversion is done manually by placing the type in parentheses () in front of the value.

Considering our problem from the example above, we can now get the right result:

Example

// Manual conversion: int to float


float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000

Try it Yourself »

You can also place the type in front of a variable:

Example

int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000

Try it Yourself »

And since you learned about "decimal precision" in the previous chapter, you could make the output
even cleaner by removing the extra zeros (if you like):

Example

int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%.1f", sum); // 2.5

Try it Yourself »

Real-Life Example

Here's a real-life example of data types and type conversion where we create a program to calculate
the percentage of a user's score in relation to the maximum score in a game:

Example

// Set the maximum possible score in the game to 500


int maxScore = 500;

// The actual score of the user


int userScore = 423;

/* Calculate the percantage of the user's score in relation to the maximum available score.
Convert userScore to float to make sure that the division is accurate */
float percentage = (float) userScore / maxScore * 100.0;

// Print the percentage


printf("User's percentage is %.2f", percentage);

Try it Yourself »

Constants

If you don't want others (or yourself) to change existing variable values, you can use
the const keyword.

This will declare the variable as "constant", which means unchangeable and read-only:

Example

const int myNum = 15; // myNum will always be 15


myNum = 10; // error: assignment of read-only variable 'myNum'

Try it Yourself »

You should always declare the variable as constant when you have values that are unlikely to change:

Example

const int minutesPerHour = 60;

Try it Yourself »

Notes On Constants
When you declare a constant variable, it must be assigned with a value:

Example

Like this:

const int minutesPerHour = 60;

This however, will not work:

const int minutesPerHour;


minutesPerHour = 60; // error

Try it Yourself »

Good Practice

Another thing about constant variables, is that it is considered good practice to declare them with
uppercase.

It is not required, but useful for code readability and common for C programmers:

Example

const int BIRTHYEAR = 1980;

Try it Yourself »

Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

int myNum = 100 + 50;

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can
also be used to add together a variable and a value, or a variable and another variable:

Example

int sum1 = 100 + 50; // 150 (100 + 50)


int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Try it Yourself »

C divides the operators into the following groups:

 Arithmetic operators

 Assignment operators
 Comparison operators

 Logical operators

 Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description

+ Addition Adds together two values

- Subtraction Subtracts one value from another

* Multiplication Multiplies two values

/ Division Divides one value by another

% Modulus Returns the division remainder

++ Increment Increases the value of a variable by 1

-- Decrement Decreases the value of a variable by 1

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

Example

int x = 10;

Try it Yourself »

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;
x += 5;

Try it Yourself »
A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are
known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example

int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3

Try it Yourself »

A list of all comparison operators:


Operator Name Example Description

== Equal to x == y Returns 1 if the values are equal

!= Not equal x != y Returns 1 if the values are not equal

> Greater than x>y Returns 1 if the first value is greater t

< Less than x<y Returns 1 if the first value is less than

>= Greater than or equal to x >= y Returns 1 if the first value is greater t
value

<= Less than or equal to x <= y Returns 1 if the first value is less than
value

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values, by combining multiple
conditions:

Operator Name Example Description

&& AND x < 5 && x < 10 Returns 1 if both statements are tru

|| OR x < 5 || x < 4 Returns 1 if one of the statements is

! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the re

Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

 YES / NO

 ON / OFF

 TRUE / FALSE

For this, C has a bool data type, which is known as booleans.

Booleans represent values that are either true or false.


Boolean Variables

In C, the bool type is not a built-in data type, like int or char.

It was introduced in C99, and you must import the following header file to use it:

#include <stdbool.h>

A boolean variable is declared with the bool keyword and can take the values true or false:

bool isProgrammingFun = true;


bool isFishTasty = false;

Before trying to print the boolean variables, you should know that boolean values are returned
as integers:

 1 (or any other number that is not 0) represents true

 0 represents false

Therefore, you must use the %d format specifier to print a boolean value:

Example

// Create boolean variables


bool isProgrammingFun = true;
bool isFishTasty = false;

// Return boolean values


printf("%d", isProgrammingFun); // Returns 1 (true)
printf("%d", isFishTasty); // Returns 0 (false)

Try it Yourself »

However, it is more common to return a boolean value by comparing values and variables.

Comparing Values and Variables

Comparing values are useful in programming, because it helps us to find answers and make
decisions.

For example, you can use a comparison operator, such as the greater than (>) operator, to compare
two values:

Example

printf("%d", 10 > 9); // Returns 1 (true) because 10 is greater than 9

Try it Yourself »

From the example above, you can see that the return value is a boolean value (1).

You can also compare two variables:


Example

int x = 10;
int y = 9;
printf("%d", x > y);

Try it Yourself »

In the example below, we use the equal to (==) operator to compare different values:

Example

printf("%d", 10 == 10); // Returns 1 (true), because 10 is equal to 10


printf("%d", 10 == 15); // Returns 0 (false), because 10 is not equal to 15
printf("%d", 5 == 55); // Returns 0 (false) because 5 is not equal to 55

Try it Yourself »

You are not limited to only compare numbers. You can also compare boolean variables, or even
special structures, like arrays (which you will learn more about in a later chapter):

Example

bool isHamburgerTasty = true;


bool isPizzaTasty = true;

// Find out if both hamburger and pizza is tasty


printf("%d", isHamburgerTasty == isPizzaTasty);

Try it Yourself »

Remember to include the <stdbool.h> header file when working with bool variables.

Real Life Example

Let's think of a "real life example" where we need to find out if a person is old enough to vote.

In the example below, we use the >= comparison operator to find out if the age (25) is greater
than OR equal to the voting age limit, which is set to 18:

Example

int myAge = 25;


int votingAge = 18;

printf("%d", myAge >= votingAge); // Returns 1 (true), meaning 25 year olds are allowed to vote!

Try it Yourself »

Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above
in an if...else statement, so we can perform different actions depending on the result:

Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old
enough to vote.":

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}

Try it Yourself »

Booleans are the basis for all comparisons and conditions.

You will learn more about conditions (if...else) in the next chapter.

You might also like