[**Note**: This is a continuation of previous post Getting to know C ]

### Variables

So, the previous example showed you how to compile and run a C program. The example we used above was intentionally kept simple to allow you to focus on learning about compilation. Let’s take a look into the `hello.c`

program again. If you look closely, you will see that it has a fundamental limitation, the only thing it can print is `Hello, World!`

; not all that interesting, right. What if we wanted `printf`

to print some other thing, the answer to this is variables. And that’s what we are going to learn now. Let’s write another program, this time we are going to declare some variables.

```
/*********************************
variable.c
My second C program
Created by Swastik on Nov 2, 2017
Copyright (C) 2017 Swastik Nath
*********************************/
#include <stdio.h>
int main()
{
/*code goes here*/
int days_in_a_week = 7;
float cm_to_in = 2.54;
char the_w;
the_w = ‘w’;
printf(“%d days in a week.\n”, days_in_a_week);
printf(“%f centimeter per inch.\n”, cm_to_in);
printf(“The %c is a cool word.\n”, the_w);
return 0;
}
```

ou can see that here we have created three fundamental C variables - an integer variable *days_in_a_week* (`int days_in_a_week = 7;`

), a floating point variable *cm_to_in* (`float cm_to_in = 2.54;`

), and a single alpha-numeric (alpha-numeric means a letter or a number) character variable *the_w* (`char the_w;`

). You can see that we have also initialised the first two variables to a value, *days_in_a_week* is assigned **7** and *cm_to_in* is assigned **2.54**. (Alternatively you can also declare and initialise a variable in separate lines if you wish.) We have done that with the char variable *the_w* by declaring first and then assigning it a character value **w**. These are three different variable types.

A variable is a name given to a computer memory location that a computer program can manipulate. Programs store, retrieve, and modify variables. Variables are the fundamental construct a computer program manipulates to perform its tasks. The variable type determines how variables are stored, their memory structure and layout.

You can also see that we have also written three `printf`

statements, replacing the single line, *Hello, World!* to print these three variables along with some strings. So this shows an example of using variables and print statements together. For each call to the `printf`

function, we pass a variable as a parameter to the function `printf`

uses the location of the format characters to determine where in the string to insert the associated formatted version of the variable. The formatted variable is substituted for the formatting character. We use special formatting letters within the string to print the variables in appropriate ways - `%d`

is for `int`

s, `%f`

is for `float`

s, `%c`

is for `char`

s. These formatting letters have numerous variations that enable significant formatting customizations, but that's not really our focus right now.

#### Code Challenge

Create a `float`

variable named '*radius*' with the value '**14.5**'. and add a `printf`

statement to print the radius variable. Here is how your output should look like: `A ball with radius 14.5 inches`

.

#### Answer

```
#include<stdio.h>
int main()
{
float radius = 14.5;
printf("A ball with a radius of %f inches.", radius);
return 0;
}
```

### Array

We have learned about the 3 fundamental variable types in C - `int`

, `float`

, and `char`

. These types are fine for dealing with a single letter - `char`

, or number of days in the week - `int`

, or some physics constant - `float`

. But think about it for a moment. That is one heck of a limitation. How would we represent a list of names the days in a week? Or months in a year? For that we need arrays. Let's take a look.

Now, you may wish to create a subfolder called “arrays”. Go into that folder and copy our previous `.c`

source file and edit it so that it looks like the following:

```
/*********************************
array_1.c
My third C program
Created by Swastik on Nov 2, 2017
Copyright (C) 2017 Swastik Nath
*********************************/
#include <stdio.h>
int main()
{
/*code goes here*/
float numbers_we_love[3];
numbers_we_love[0] = 3.1415;
numbers_we_love[1] = 1.6180;
numbers_we_love[2] = 1.4142;
printf(“PI is %f \n”, numbers_we_love[0]);
printf(“Golden Ratio is %f \n”, numbers_we_love[1]);
printf(“Square root of 2 is %f \n”, numbers_we_love[0]);
return 0;
}
```

An array in c is a mechanism for storing multiple values of the same data type. The values are indexed for easy access. The index always starts at zero.

We have declared an array of floating point variables named *numbers_we_love*. We've made it large enough to hold 3 floating point numbers. We indicate that by `[3]`

. We have then loaded this array with 3 floating point numbers. We have done that by accessing our array at different indices or indexes. In C the first item in an array is the zeroth item, not the first item,( `numbers_we_love[0]`

instead of `numbers_we_love[1]`

). The first item in our *numbers_we_love* array will be *pi*. We have done that by `numbers_we_love[0] = 3.1415;`

. The second number will be a *golden ratio*. The second number will be stored at the second index, which you indicate by **1**. ( `numbers_we_love[1] = 1.6180;`

) We'll add a third number at the third index, which we indicate by 2. This will be the square root of 2. ( `numbers_we_love[2] = 1.4142;`

)

The reason arrays are zero-based is as follows -- an array in C, specifically the variable name, is a pointer to a physical computer memory address. Wait! Don't freak out. You'll learn all about pointers later in this course. When we access an array, or index into an array in jargon-speak, we are selecting an offset from the computer memory address pointed to by the name of the array. Here, the name of the array is numbers_we_love. The first array item in that array is at a memory address offset of 0. So, going back to our array we see the first item is at 0, the second is at one, etc.

We also have written statements for printing our numbers, by writing our friend the print statement, and the first number we'll print is pi. `printf(“PI is %f \n”, numbers_we_love[0]);`

. We have used the formatting symbol (`%f`

) for a floating point number. And we have accessed the first number in the array. (so, by doing `numbers_we_love[0] = 3.1415;`

we loaded the first item we loaded it into 0. Now, we're retrieving the first item so again we use 0.) Similarly we have included the print statements for second and third index of array by `numbers_we_love[1] = 1.6180;`

and `numbers_we_love[2] = 1.4142;`

consecutively.

So now we've seen a floating point number stored in a floating point array. Let's do something slightly different -- we'll look at integers. We'll make an int array called primes, for prime numbers along with the float array called *numbers_we_love*.

```
/**********************************
array_2.c
My fourth C program
Created by Swastik on Nov 2, 2017
Copyright (C) 2017 Swastik Nath
**********************************/
#include <stdio.h>
int main()
{
/*code goes here*/
float numbers_we_love[3];
numbers_we_love[0] = 3.1415;
numbers_we_love[1] = 1.6180;
numbers_we_love[2] = 1.4142;
printf(“PI is %f \n”, numbers_we_love[0]);
printf(“Golden Ratio is %f \n”, numbers_we_love[1]);
printf(“Square root of 2 is %f \n”, numbers_we_love[0]);
int primes[] = {2, 3, 5, 7};
printf("the first 4 prime numbers are %d ", primes[0]);
printf("%d %d %d \n", primes[1], primes[2], primes[3]);
return 0;
}
```

The syntax array primes has an open square bracket, followed by curly braces, and in the curly braces, we've inserted the numbers we want in our integer array. These will be the first prime numbers **2**, **3**, **5**, **7**. Look closely here, notice we didn't have to insert an number for the size of the array where we're initializing the array for the first time. Now, we’ve printed the first four prime numbers with the print statement `printf("the first 4 prime numbers are %d %d %d %d\n", primes[0], primes[1], primes[2], primes[3]);`

. Here we’ve used the integer formatting symbol indicated by `%d`

. We’ve used four formatting symbols for the four numbers that are in the array. Again, the first number in our array starts at `0`

, the second is `1`

, the third is `2`

, the fourth is `3`

.

In the above source code here we’ve used two print statements, however, you can merge them into one if you wish e.g. `printf("the first 4 prime numbers are %d %d %d %d\n", primes[0], primes[1], primes[2], primes[3]);`

Using this approach where we declare our array and initialize it at the same time is often very convenient and makes our code more compact and more readable. Let's go back and change *numbers_we_love* to do it the same way we did primes.

```
/*********************************
array_3.c
My fourth C program
Created by Swastik on Nov 2, 2017
Copyright (C) 2017 Swastik Nath
*********************************/
#include <stdio.h>
int main()
{
/*code goes here*/
float numbers_we_love[] = {3.1415, 1.6180, 1.4142};
printf(“PI is %f \n”, numbers_we_love[0]);
printf(“Golden Ratio is %f \n”, numbers_we_love[1]);
printf(“Square root of 2 is %f \n”, numbers_we_love[0]);
int primes[] = {2, 3, 5, 7};
printf("the first 4 prime numbers are %d ", primes[0]);
printf("%d %d %d \n", primes[1], primes[2], primes[3]);
return 0;
}
```

You can now compile and run the code on your own. Now you have a feel for the use of arrays in C.

#### Code Challenge

Declare an array of type float named *math_constants*. The array should be big enough to hold two numbers. Assign the numbers **2.71828**, **1.41421** to the array *math_constants*. Print the values of the first and second index in the *math_constants* array. Your output should look like this:

`Euler's number = 2.71828 Square root of 2 = 1.41421`

.

Now write it in compact form. (do yourself)

#### Answer

```
#include<stdio.h>
int main()
{
float math_constants[2];
math_constants[0] = 2.71828
math_constants[1] = 1.41421
printf(“Euler's number = %f\n”, math_constants[0]);
printf(“Square root of 2 = %f\n”, math_constants[1])
return 0;
}
```

### Operators and Expressions

You now know that variables are the basic data objects manipulated in a C program. I now want to discuss about the movers and shakers of those variables – The operators and expressions. Operators specify how your variables are manipulated. Expressions combine variables to produce new values. C supports the typical binary operators we're all familiar with -- *addition*, *subtraction*, *multiplication*, and *division*. C adds additional unary operators (The unary operators operate on a single operand and following are the examples of Unary operators: The increment `++`

and decrement `--`

operators. The unary minus - operator. The logical not `!`

operator.), as well. Operators and expressions are fundamental to programming. Let's take a closer look at operators and expressions in C.

Now, you may wish to create a subfolder called “operators_and_expressions”. Into that folder copy our previous .c source file and edit it so that it looks like the following:

```
/*********************************
Operators_and_expressions.c
My fifth C program
Created by Swastik on Nov 2, 2017
Copyright (C) 2017 Swastik Nath
*********************************/
#include <stdio.h>
int main()
{
int a = 9;
printf("a = %d\n", a);
int c = a++;
printf("c = %d a = %d\n", c, a);
int d = a--;
printf("d = %d a = %d\n", d, a);
int b = a % 4;
printf("b = %d a = %d\n", b, a);
float fa = 5.0 / .5;
printf("fa = %f\n", fa);
fa *= 10;
printf("fa = %f\n", fa);
return 0;
}
```

Here, `=`

is the assignment operator, we assign the unsigned variable 'a' a value of **9**. The unary operator `a++`

is translated to `a+1`

. Placing the plus pluses (`++`

) behind the a, makes this statement mean assign a to c and afterwards, increment a by 1. The unary operator `a--`

is translated to `a-1`

. Placing the minus minuses (`--`

) behind the a, makes this statement mean assign a to c and afterwards, decrement a by 1. Both of them retain the original value of a. In contrary if we would have used `++a`

and `--a`

, then it would have first increased or decreased the value of a by 1 i.e. `a = a+1`

and then `c = a`

for `c = ++a`

similarly `c = --a`

would have translated to `a= a-1`

and `c = a`

, replacing the original values of a (which may be unwanted in some cases, however this might be right thing to do in other cases; we’ll discuss about them later).

We have also used another operator called modulo. We'll declare a new variable `b`

, and call it a *modulo 4*. I know you're thinking - What's a modulo? The modulo operator returns the remainder after division of one number by another. a is currently **9**. **9** divided by **4** goes in **2**, leaving **1**; that is the remainder; the remainder is assigned to be. The value of a remains unchanged at **9**. C, of course, has all the typical binary operators we've become familiar with, such as addition, subtraction, multiplication and division. C also provides a compact version of addition, subtraction, multiplication, and division. Here we've used the compact form of multiplication. `fa *= 10`

; what this means is take the original value of `fa`

, multiply it by **10**, and assign it back to `fa`

; all in one line of code. This is a shortcut for the long way, which would be `fa = fa * 10`

. This compact form can be used by all the binary operators - multiplication, division, addition, and subtraction.

#### Code Challenge

- How would you declare an integer variable named
`unstable`

and initialize it to*25*? - After declaring and initializing unstable perform
`unstable -= 5;`

What would be the final answer? - Auto increment the variable named unstable. What is the syntax?
- Auto decrement the variable named unstable. What is the syntax?
- Use the compact form of division to divide unstable by 3. (Hint: The compact form of division is very similar to the compact form of multiplication we have previously used.)

#### Answers

`int unstable = 25;`

`unstable -= 5;`

will leave`unstable`

at*20*`unstable++;`

`unstable--;`

`unstable /= 3;`