Tuesday, November 4, 2008

what r variables ??

Variables
C has the following simple data types:
integer,float & character.






NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.


Unsigned can be used with all char and int types.


To declare a variable in C, do:

var_type list variables;


e.g. int i,j,k;
float x,y,z;
char ch;


Defining Global Variables
Global variables are defined above main() in the following way:-



short number,sum;
int bignumber,bigsum;
char letter;

main()
{

}

It is also possible to pre-initialise global variables using the = operator for assignment.


NOTE: The = operator is the same as := is Pascal.


For example:-



float sum=0.0;
int bigsum=0;
char letter=`A';

main()
{

}

This is the same as:-



float sum;
int bigsum;
char letter;

main()
{

sum=0.0;
bigsum=0;
letter=`A';

}

...but is more efficient.


C also allows multiple assignment statements using =, for example:



a=b=c=d=3;

...which is the same as, but more efficient than:



a=3;
b=3;
c=3;
d=3;

This kind of assignment is only possible if all the variable types in the statement are the same.

You can define your own types use typedef. This will have greater relevance later in the course when we learn how to create more complex data structures.

As an example of a simple use let us consider how we may define two new types real and letter. These new types can then be used in the same way as the pre-defined C types:



typedef real float;
typedef letter char;

Variables declared:
real sum=0.0;
letter nextletter;


Printing Out and Inputting Variables
C uses formatted output. The printf function has a special formatting character (%) -- a character following this defines a certain format for a variable:


%c -- characters
%d -- integers
%f -- floats

e.g. printf(``%c %d %f'',ch,i,x);


NOTE: Format statement enclosed in ``...'', variables follow after. Make sure order of format and variable data types match up.


scanf() is the function for inputting values to a data structure: Its format is similar to printf:


i.e. scanf(``%c %d %f'',&ch,&i,&x);


NOTE: & before variables. Please accept this for now and remember to include it. It is to do with pointers which we will meet later (Section 17.4.1).

0 Comments: