Variables and Memory

For Complete YouTube Video: Click Here

In this class, we will try to understand Variables and Memory. The objective of this class is to know how the values assigned to the variables will be stored in the memory.

Previous Memory Visualization

The image below is how we have visualized memory to store the values in our previous class.

Memory after Assigning Values to the Variables
Memory Visualization Previously

Practically values are not stored as shown above because the computer does not know how to hold the decimal numbers.

How a computer stores the values of the variables?

The values of the variables are stored in binary format.

The computer understands only two symbols, 1 and 0.

The image below shows the representation of decimal numbers in binary.

Decimal to Binary Representation
Decimal to Binary Representation

Understanding the conversion of decimal to binary and binary to decimal is beyond the scope of this course.

It is not required to understand those representations and conversions.

From the above image, how many decimal numbers are represented by using only 1 bit.

Using 1 bit, you can represent decimal number 0 and 1.

Similarly, how many decimal numbers are represented by using 2 bits.

Using 2 bit, you can represent four decimal number 0, 1, 2 and 3.

Similarly, how many decimal numbers are represented by using 3 bits.

The binary representation of decimal number 1 is 1. Adding zero’s to the right [00001] does not change its value.

Using 3 bit, you can represent eight decimal number 0, 1, 2, 3, 4, 5, 6 and 7.

With n bits, we can represent 2n decimal numbers.

For example, with n = 4, you can represent 16 decimal numbers.

The range of number that you can represent with n = 4 is 0 to 2n – 1.

Memory with Bits

In the image below is the new way of memory visualization.

Memory with Bits
Memory with Bits

In the image above, each block has eight dashes.

Each dash can store a bit of data.

A group of eight bits is called a byte.

Each block is of 1-byte capacity.

Variables and Memory

For example, consider the line of code given below.

int a = 14;

Variable a is allocated with the memory location 3.

Now with the new way of memory visualization, how 14 can be stored.

The binary equivalent of the decimal number 14 is 1110.

As each block of memory has 8 bits, pad an extra four zero’s to the right of the binary number [00001110].

The image below shows how 14 will be stored in the memory.

Memory with Variable Value