Skip to Main Content or Page Contents

C Programming Tutorial 3. Variables

Variables - Local, global, static - Declaration, Initialisation, Scope and naming conventions.

Results per page:

Match: any search words all search words

Page Contents

Variable Introduction

Variables are the names that refer to sections of memory into which data can be stored.

To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes.

  • In order to use a box to store data, the box must be given a name, this process is known as declaration.
    • It helps if you give a box a meaningful name that relates to the type of information en it is easier to find the data.
  • The boxes must be of the correct size for the data type you are going to put into it.
    • An integer number such as 2 requires a smaller box than a floating point number such as 1.9
  • Data is placed into a box by assigning the data to the box.
  • By using he name of the box you can retrieve the box contents, some kind of data.

Variable Naming Conventions

  • Variable names must start with a letter or underscore. By convention a lower case letter. The use of a leading underscore is NOT recommended.
  • Then letters, numbers and the underscore _ can be used.
  • Spaces are NOT allowed.
  • Do NOT use any of the C reserved keywords.
  • Case is significant, num is a different variable to Num
  • Only the first 31 characters are significant.

TIPS:

  • Names should be meaningful or descriptive.
    • E.g. studentAge or student_age is more meaninful than age, and much more meaniful than a single letter such as a.
  • Spaces
    • are either replaced by the underscore, e.g. account_name
    • or the space removed and the second name started with an uppercase letter e.g. accountName.
  • If you are attending further education or working as part of a team, then additional naming conventions may be required.

Variable Declaration

Before you can use a variable you must declare it. Decide what type of data is going to be stored in variable. The main categories of data are:

integers Whole numbers e.g. 0, 1, 99, 12345
floating point numbers Numbers that have a fractional part, they have a decimal point e.g. 12.543, 0.5, 1.00. Also referred too as real numbers.
characters A single character e.g. a, Z, 3, # etc. Note: Characters are stored as a number that is the ASCII code for that character. See ASCII codes
strings Strings can't be declared as a string. They are regarded as an array of characters, and are dealt with later.

Some of these data categories are split into more than one data type as per table 3.1 below.

'C' Numeric data types.

 

Table of Variable types.


Variable Type Keyword Range Storage in Bytes
Character char -127 to 127
1
Unsigned character unsigned char 0 to 255
1
 
Integer int -32,768 to 32,767
2
Unsigned integer unsigned int 0 to 65,535
2
 
Short integer short -32,768 to 32,767
2
Unsigned short integer unsigned short 0 to 65,535
2
 
Long integer long -2,147,483,648 to 2,147,483,647
4
Unsigned long integer unsigned long 0 to 4,294,967,295
4
 
Single precision floating point float 1.2E-38 to 3.4E38, approx. range precision = 7 digits.
4
Double precision floating point double 2.2E-308 to 1.8E308, approx. range precision = 19 digits.
8

The main variable types that you will use most are char, int, float.
If you wish to use larger numbers than those allowed in int and float then refer to this table for the type you should use.

h2>Variable Declaration Examples

Single declarations


int age;
float amountOfMoney;
char initial;

Multiple declarations


You can repeat the the declaration line with a different variable on each line e.g.
int age;
int houseNumber;
but the normal way is to separate the variables by a comma. Although not required the names are easier to read if a space follows the comma.
int age, houseNumber, quantity;
float distance, rateOfDiscount;
char firstInitial, secondInitial;

Variable Scope

The scope of a variable is

  • The area of the program where that variable is valid, i.e. the parts of the program that have access to that variable. This is determined by the location of the declaration.
  • The life span of that variable, i.e. the length of time that the variable remains in memory.

The scope of a variable depends on where it is declared.

Where do you DeclareVariables

Variables can be declared

  • Prior to the start of the main( ) function.
  • Within the main function, after the opening {
  • Within a function (Tutorial 8) , after the opening {
  • Within a block of code, after the {

Global or external variable


Declared before the start of the main( ) function

 

Scope: In the small programs that are used in these tutorials the scope is any where in the program, this includes main and all the other functions.
Life Span: While the program is running.
Global variables are automatically initialised to 0 (zero), but get into the practice of initialising ALL variables.
It is usually better to avoid the use of global variables.

static


When static is used with a global variable it indicates that the variable is local to the current file. This is more advanced and static global variables are not used in these beginners tutorials.

 

Local variable


Declared within a function including the main() function.

 

The declaration is placed after the { start brace of any function including main, and before any function statements.
Scope of a local variable is limited to the function it is declared in.
Life Span:Local variables are destroyed when a function is exited, and a new one is created when a function is visited again, they exist in memory on a temporary basis. This temporary basis can be made permanent by the use of the static keyword. See below

Example of declaring an integer variable named aVariable within the function someFunctionName
Local variables MUST be assigned a value to initialise the variable before they are used.

someFunctionName( )
{
       int aVariable;
      /* rest of function code */
} 

static


If the programmer would like the value of the variable to be remembered when the function is revisited then that variable must be declared as static. E.g. static int aVariable = 1;
In the example the initialisation to 1 occurs only on the first execution of this line of code, it is disregarded on further executions of the line.
static has a different meaning when used with global variables. See above.

 

Local, local variable


Declared within the { } braces of a block of code.

 

The declaration is placed after the { (start brace of the block of code) and before any statements in that block.
Scope: of a local local variable is limited to the braces of the portion of code it is declared in.
Life Span:Local local variables are destroyed when the end } brace is reached.

 

Assigning a value into a Variable

In the following
age = 24;
We are assigning the value of the expression, 24 in the example, on the right of the = (the assignment operator) into the variable on the left.

When you assign a value into a variable, the previous value in that variable is overwritten and therefore destroyed.

Variable Declaration and Initialising Examples

int age = 21, houseNumber = 0;
float amountOfMoney = 0.0;
char firstInitial = 'S', secondInitial = 72;

Note:

When initialising a variable, also known as assigning a value to a variable do not think of = (the assignment operator) being the same as a mathematical = (equals), because it is not.

 

Imagine that you wish to swap the values that are held in 2 variables named x and y after reading the above you will understand that the following will NOT work.
x = y;
y = x;

The result of the above is that both x and y will now contain the original value of y.
A way around this problem is to use a third temporary variable.
temp = x;
x = y;
y = temp;

Incrementing and decrementing a variable

When you remember how assignments are made makes it easier to understand this mathematically impossible, but very common code used in programming.
num = num + 1;

Code explanation


Looking at this in more detail let's add another line of code that assigns num the value 4.
num = 4;
num = num + 1;

The value that is being assigned into num is 5, i.e. the current value of num which is 4 and then 1 is added to it.

Simply put the above code increments the value of num.

The reverse of the above is to decrement num with this code
num = num - 1;

Shortcuts

Incrementing, decrementing and doing calculations on a variable is a very common programming task and C has quicker ways of writing the code. The code is rather cyptic in appearence

 

Operator Shorthand Equivalent more readable statement. Assume that num is assigned 7 before the execution of the code in any of the following lines. Then the value of num after execution of that line is
++ ++num num = num + 1 8
num++
-- --num num = num - 1 6
num--
+= num += 3 num = num + 3 10
-= num -= 3 num = num - 3 4
*= num *= 3 num = num * 3 21
/= num /= 3 num = num / 3 2
%= num %= 3 num = num % 3 1 Note the remainder of 7 / 3

 

Exercise 1a.
Do this exercise on paper not on the computer. Write a program that uses an integer variable named num1. The program should do the following in the stated order:

  1. Clear the screen
  2. Display the value of the variable num1, this line demonstrates the affect of not initialising num1
  3. Set the value of num1 to 4.
  4. Display the value of the variable num1.
  5. Increment the variable num1.
  6. Display the value of the variable num1.
  7. Increment the variable num1 by 22.
  8. Display the value of the variable num1.

You can check your paper answer as you complete the following computer exercises 1b - 1e.

Exercise 1b. Error Undefined symbol
When entering your paper solution into the computer you need only enter a section of the result and test it is working correctly. In this exercise you are going to enter in some code that is supposed to do section A and B. The code below contains 2 errors. The variable has not been 1). declared and 2). Initialised

void main()
{ 	
      clrscr();
      cprintf("value of variable num1 is %i\n\r",num1); 
}
  • Copy and paste this code into your editor.
  • Save as t03ex01.c
  • Compile, link and run the program

The following error message should appear. The path will display where the file is on your drive. The line number may be different.
Error \path\t03ex01.c 4: Undefined symbol 'num1' in function main.

Exercise 1b cont. incorrect results
Correct the error by declaring num1 as a local integer variable. But do not initialise the variable.
Local variables are declared immediately after the opening brace of a function.

  • Save the program
  • Compile, link and run the program.

If you have corrected the Undefined symbol error correctly then the program should run but because num1 has not been initialised the result of trying to display the contents of num1 may produce funny or incorrect results. The result will depend on whatever ''old data'' is in that memory location at the time of execution.

The result of running my program is
value of variable num1 is 2295
Imagine using this variable in a calculation, assuming that its current value has been initialised. Your result could be anything

See solution exercise 1b

Exercise 1c and d.

You could correct this by initialising the num1 variable in the declaration line to the required value of 4 (step C).
Or you could initialise num1 to 0 in the declaration line, then assign 4 to num1 where required in the program, but as this is in the next line the former method is better.

  • Correct the program now.
  • Save, compile, link and run the program.
  • The result should show that the value of num1 is 4.

See solution exercise 1cd

Exercise 1e and f.

  • Continue with steps E). and F).
  • Save, compile, link and run the program.

See solution exercise 1e and f

 

Exercise 1g Errors.

Replace the number used in the initialise with 32768, Note the program will execute OK but the result is wrong. 32768 is not within the allowable range.

Change to 32767 which is within the range will work.

 

Times Table Project

Continuation of the Times Table Project from tutorial 2

Open up file t01ex10d.c to obtain this code.

main()
 {
      clrscr();
 	    cprintf (" 7 times table\r\n\r\n");
	     cprintf (" 1 x 7 =  %i\r\n", 1 * 7) ; 
	     cprintf (" 2 x 7 = %i\r\n", 2 * 7) ; 
	     cprintf ("10 x 7 = %i\r\n", 10 * 7) ; 
}
If I wanted to write a times tableother than 7,I would have to rewrite the entire table for each times table I required. If I use a variable I would have to rewrite the program but to change from 7 times to any other number I would only have to make one change. Look at the above code and think of where you can use a variable to do this.

Exercise 2a.
Save as t03ex02a
Delete 2 lines so that the code is as follows

main()
{
     clrscr();
     cprintf (" 7 times table\r\n\r\n");
     cprintf (" 1 x 7 =  %i\r\n", 1 * 7) ; 
}

Declare an integer variable named number, and initialise it to 7. Look at the above code and think of where you can use this variable.

It's fairly obvious that you are going to use the variable in the 3 places that 7 appears in the above code.

The very last 7 is easy to do, you simply replace the 7 by number.

Do this now then save, compile, link and run.

Check that you get the correct result.

Go to solution 2a.

Exercise 2b.
To replace the 7 in
cprintf (" 7 times table\r\n\r\n");
requires a little more thought.

If you think you can do it, then have a go, or you may like to read the following clues first.

Clues:

  • The 7 is replaced by a place holder.
  • number is used after the closing " quote.
  • A , comma is required

Go to solution 2b.

Exercise 2c.
Replace the final 7, this is done in the same way as exercise 2b. Think about insertion point for , number

Go to solution 2c.

Exercise 2d.
Now change the initialise value to 8 and check the results are still correct for the 8 times table.

Exercise 2e.
Now think about how a times table is set out:

1 x 8 = 8
2 x 8 = 16
3 x 8 = 24
4 x 8 = 32

Note the first number in each row, the number is incremented by 1.

You can now use a second variable in place of 1,2,3 etc and increment this variable. Call this variable index.

You have a choice of initialising this variable to either 0 or 1. Depending on whether you select 0 or 1 will determine where you place the increment code in relation to the line.

      /* Possible position of the increment code */
	   cprintf (" 1 x %i =  %i\r\n" , number, 1 * number) ;
	   /*Alternative position of the increment code */
 

For this exercise you should

  • Declare index and initialise to 0.
  • Think which the correct position of the two positions is for the increment code, with index
  • Insert a place holder for index in the second cprint line.
  • Insert a comma and the variable index in the second cprint line.
  • Think if you require any additional changes.
  • Save as t03ex02e
  • Compile, link and run.
  • Correct any errors if required.
  • Check that the result is correct

Go to solution 2e.

If you did not change the 1 for index in the calculation, leave your answer as it is, you will see why you need to change this after completion of the next exercise.

Exercise 2f.
The increment code could have been placed in any line after the declaration / initialisation line and the line I have placed it in my solution. In order to do the next step ensure your solution is the same as mine, then.

Copy the 2 lines that contain the increment code and the cprintf code.
You can useualy copy by highlighting the required text, then use the combination of holding down the Ctrl key and c key down together.

Then paste (Ctrl v) the code say 4 times more

  • Save as t03ex02f
  • Compile, link and run.
  • Correct any errors if required.
  • Check that the result is correct

If you did not change the 1 in the calculation then the answer will be 8, ( 1 * 8 )in each line. Correct by changing the 1 to index in all the lines and check the result after execution.

To increase the size of the table all you need to do is to keep on copying the 2 lines of code. But in a later lesson you will learn how we can use a repeat structure that repeats the 2 lines of code

     index++ ;
	   cprintf (" %i x %i =  %i\r\n" , index, number, index * number) ; 
as many times as required, without having to copy and paste those lines time and time again as you have done in this exercise.

Go to solution 2f.

Solutions to Exercises

Solutions to Exercise 1b.
void main()
{ 	
      int num1;	
      clrscr();
      cprintf("value of variable num1 is %i\n\r",num1); 
}
Return to exercise 1b



Solutions to Exercise 1cd.
void main()
{ 	
      int num1 = 4 ;	
	    clrscr() ;
      cprintf("value of variable num1 is %i\n\r",num1) ;
	    num1++ ;
	    cprintf("value of variable num1 is %i\n\r",num1) ; 
}
Return to exercise 1cd.

Solutions to Exercise 1ef.
void main()
{ 	
	int num1 = 4 ;	
       clrscr() ;
	     cprintf("value of variable num1 is %i\n\r",num1) ; 
	     num1++ ;
	     cprintf("value of variable num1 is %i\n\r",num1) ; 
	     num1 += 22 ;
	    cprintf("value of variable num1 is %i\n\r",num1) ; 
}

Return to exercise 1ef.

Solutions to Exercise 2a.
main()
{
	int number = 7;
	clrscr();
 	cprintf (" 7 times table\r\n\r\n");
	cprintf (" 1 x 7 =  %i\r\n", 1 * number) ; 
}

Return to exercise 2a.

Solutions to Exercise 2b.
main()
{
	   int number = 7;
	   clrscr();
 	   cprintf (" %i times table\r\n\r\n",number);
	   cprintf (" 1 x 7 =  %i\r\n", 1 * number) ; 
}
Return to exercise 2b.

Solutions to Exercise 2c.
main()
{
	    int number = 7;
	   clrscr();
 	   cprintf (" %i times table\r\n\r\n",number);
	   cprintf (" 1 x %i =  %i\r\n" , number, 1 * number) ; 
}
Return to exercise 2c.

Solutions to Exercise 2ef.
main()
{
	   int number = 8, index = 0;
	   clrscr();
 	   cprintf (" %i times table\r\n\r\n",number);
	   index++ ;
	   cprintf (" %i x %i =  %i\r\n" , index, number, index * number) ; 
}
Return to exercise 2ef.

| Top of Page |

 

 

 


© tutorials4u.com
HTML Tutorial by John McGuinn.