Chapter 3: Variables & Assignments.

## Chapter 3: Variables & Assignments.

### Variables:

A variable is a named piece of data. I want you to remember that, so write it down, and repeat it to yourself a few times in the mirror. It is super important.

Somewhere in the binary that is your code, there is a small cut of 1s and 0s that have been allocated a meaning. The main ones you will use can be of the following data types:

### Variable Types:

##### Char:

A single character, such as those found on your keyboard. They do not have a value as with numbers, so if using as char a data type, it cannot be used in math functions unless used with a format specifier. Instead, this is reserved for holding letters and figures rather than actual meaning. In Binary, these are represented by the ASCII, abbreviated from American Standard Code for Information Interchange. Computer scientists allocated specific combinations of 1s and 0s in order to represent the letters of the alphabet. There are of course other natural language standards for other cultures but in the west. We use ASCII.
For Example
ASCII = 1100101 10000011 1100111 1110011 1110011 – each “chunk” of numbers represent the letters found within the abbreviation ASCII.

##### Int:

Integers and floats are two different kinds of numerical data.

An integer, or whole number, such as 1, 100, or 999, a number that is not a decimal. This can be used in math functions. An integer (more commonly called an int) is a number without a decimal point.

In binary, this can only count using simple 1s and 0s. This means, unlike our common counting method that uses bases of 10, because we have 10 fingers; ‘decimal’ or ‘hexadecimal’ which uses bases 16.

Computers use binary, so every time we use both a 1 and a 0, we have to move up 10.

For Example
0 = 0
1 = 1
10 = 2
11 = 3
100 = 4

##### Float:

A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.

For Example
3 . 1 4 1 5 9 2

Each of these numbers is represented in binary using their integer value, and the float is allocated through its data type, and the computer interprets that named area of data differently.

##### Double:

A double is a float with twice the amount of allocated memory, 14 decimal places.

For Example

3 . 1 4 1 5 9 2 6 5 3 5 8 9 7

##### Void:

A void is exactly as it sounds, it represents the absence of data.

### Assignments:

For a variable to have a value, it must be assigned one. For this, we use the ‘=’. The assignment operator! Though it may look like an equals sigh, do not be fooled by its disguise. For that in programming we use ‘==’. Just to keep you on your toes. For Example:

`int number = 10`

`char letter = "D" // Note, for a char we must use speech marks or quotes to denote that this is a char and not a value.`

Have a play around with these features and get used to the different coding!

### Output with Variables:

Once you have fully appreciated the oddity of mixing variable types and format specifiers. Let’s try another exercise with math this time.

There are several things in this code we have not yet covered, but I have included this exercise, just to give you an early introduction and exposure to these concepts to help you learn.

This code is a simple little guessing game, it uses a while loop, retrieves input ‘scanf()’ and give output, and a random function ‘srand()’. Both ready-built into the C library and include a second header file called time.h you have also not yet been introduced to. Do not worry, I do not expect you to fully understand everything. But continue to write the following code and its comments, execute and try to understand how this program works. What is key, is that it demonstrates a more practical use of variables.

You will learn about scanf() in the next episode, and functions in-depth a little later.

### Exercise One:

Write the following code into your compiler and run it, do not copy and paste anything, you will only be cheating yourself.

``````#include <stdio.h>

int main()
{
int num1              = 123          ;
float decimal         = 8.30427      ;
double doubleFloat    = 1.12456784   ;
char character        = 'D'          ;

//Values
printf("the value of the memory allocated to num1 is: \n%c as a character\n%0.5f as a float to 5dp\n%d as an int \n\n", num1               ) ;
printf("the value of the memory allocated to decimal is: \n%c as a character\n%0.5f as a float to 5dp\n%d as an int \n\n", decimal         ) ;
printf("the value of the memory allocated to doubleFloat is: \n%c as a character\n%0.5f as a float to 5dp\n%d as an int \n\n", doubleFloat ) ;
a

//Math
printf("num1 + character =  %d\n", num1 + character)            ;
printf("decimal + character = %f\n", decimal + character)       ;
printf("doubleFloat + decimal = %f\n", doubleFloat + decimal)   ;
printf("num1 + decimal = %f\n", num1 + decimal)                 ;

return 0;
}``````

### Exercise Two:

``````#include <time.h>    //Use the internal clock of the system to generate a random number
#include <stdlib.h>

void main ()
{
//Declare Variables
int  range                             ;
int  guess                             ;

//Initialization of the random function
srand(time(NULL))                      ;

//Prompt Input of range
printf("Hello, I guess numbers! Can you give me a range?\n")  ;

while(answer != 'y')//While loop to keep running, and keep guessing
{
//Get a range from the user
scanf("%d", &range)                                       ;

// Returns a pseudo-random integer between 0 and range
int guess = rand() %  range                               ;

//Prompt user if guess was right
printf("I guess %d, am I right? y || n \n", guess)        ;
}

printf("Yay! I got it right! :) \n")   ; //Brag Correct Answer
return     ``````

### Exercise Three:

Fix the following broken code, two issues will be caught by the compiler, and the debugger on code-blocks should bring them to your attention, the last, however, you will have to think for yourself to solve.

Why might the computer think x + y + z == 0 ?

Why are we seeing this semantic error?

``````#include <stdio.h>
#include <stdlib.h>

int main()
{
int x;
int y;
float z
x=10;
y=12;
z=127.5;

printf("x= %d"x);
printf("\n");

printf("y=%d",y);
printf("\n");

printf("z=%3.1f",z);
printf("\n");

printf("%d\n", x + z + y);
return 0;
}
``````

This is an example of a real world problem solving you will need to become accustomed to. Please try your best to solve this problem on your own, before revealing the answer.

C programming is a sequential language. This means that the code executed one line at a time. Because of this behavior, if we assign the variable ‘a’ the value of ‘x + y + z’ before we have assigned them a value, they will default to 0, or some random number that happens to be held in that ‘Named area of data’.

The second error, was when we used the wrong ‘format specifier’ while printing the answer. Because we added a float to an int, we required the answer to also be printed in float format.

``````//Home Work - Task 2

#include <stdio.h>
#include <stdlib.h>

int main()
{
float a                            ;
int x                              ;
int y                              ;
float z                            ;

a = x + y + z                      ;  //C is sequential.

x = 10                             ;
y = 12                             ;
z = 127.5                          ;

printf("x= %d",x)   ;printf ("\n")  ;
printf("y=%d",y)    ;printf("\n")   ;
printf("z=%.3f",z)  ;printf("\n")   ;

printf("value of a : %.3f \n", a)   ; //Format Specifiers

return (0)                            ;
}
``````

Congratulations for completing this lesson!

This course is provided for free, as we at Devoke believe all education should be. However, if you enjoy the course, we are always grateful for support and donations to Patreon to ensure we can continue providing resources for free.

https://www.patreon.com/DevokeStudio/posts