C Handout- Variables and Printing

 

Variables

There are four types of variables available in Interactive C.

  1. Character (char) - 1 byte, 8 bits. Used for single characters.
  2. Integer (int) - 2 bytes, 16 bits. Holds integers from -32768 to +32767.
  3. Long integer (long) - 4 bytes, 32 bits.From -2,147,483,648 to +2,147,483,647.
  4. Floating point (float) - 4 bytes, 32 bits. A real number from about 10-38 to 1038, accurate to about 1 part in 107.

Printing

The generic format for a print statement is given by:

printf(format-string, [arg-1] , ... , [arg-N] )

This is easiest to understand in terms of actual examples:

Printing Examples

Printing statement

LCD output

Notes:

printf("\nHello!");

Hello!

"\n" in the format string clears the screen.

printf("\nValue = %d",13);

Value = 13

"%d" in the format string tells print command to look for first argument and print it as decimal (integer base 10) number

int i;

i=13;

printf("\ni=%d",i);

i=13

"%d" in the format string tells print command to look for first argument and print it as decimal (integer base 10) number

int i;

i=13;

printf("\ni=%b",i);

i=00001101

"%b" prints as binary (only prints lower 8 bits)

int i;

i=13;

printf("\ni=%x",i);

i=000d

"%x" prints as hexadecimal

int i, j;

i=13, j=4;

printf("\ni=%d j=%d, i,j);

i=13 j=4

the first "%d" goes with first argument in the list, the second "%d" goes with the next, and so on.

float x;

x=3.14159;

printf("\nx=%f",x);

x=3.14159

"%f" prints a float (i.e., a real number with a decimal point in it).

Summary of printing

Format String

Variable Type

Format Description

%d

int

Prints as decimal (base 10 integer) number

%x

int

Prints as hexadecimal

%b

int(lower 8 bits only)

Prints as binary

%f

float

Prints a float (real number with a decimal point)

%c

int

Prints lower 8 bits as an ASCII character

%s

char array (string)

Prints a character string

 


Review Sheet, Variables and Printing

 

Start with 6 variables.

int i, j, k

float x, y, z

 

Do some math

i=5

j=3

k=i/j  k=______

k=j/i  k=______

k=(i/j)*j  k=______

k=i*j  k=______

 

k=i&j  k=_______

k=i|j   k=_______

k=i++  k=_______

k=++j  k=_______

 

x=5.0

y=3.0

z=x/y  z=_______

z=y/x  z=_______

z=(x/y)*y  z=_______

 

Print them out

i=5

j=3

k=i*j  k=______

 

printf("\nk=%d",k)   LCD shows_________________________

printf("\nk=%x",k)   LCD shows_________________________

printf("\nk=%b",k)   LCD shows_________________________

printf("\ni=%b",i)   LCD shows_________________________

printf("\nj=%b",j)   LCD shows_________________________

printf("\ni&j=%b",i&j)   LCD shows_________________________

printf("\nhello\ngoodbye")   LCD shows_________________________