Using variables

The Program

/* File: wreck.c ----------------- Author: Sue Bogar Date written: 9/2/95 A program that prints the depth of the wreck of the Hesperus using 3 different units of measure: fathoms, feet, and inches. */ #include <stdio.h> main() { /* Declare variables */ int inches, feet, fathoms; /* Assign fathoms the depth of the wreck */ fathoms = 7; /* Do conversions into feet or inches */ feet = 6 * fathoms; inches = 12 * feet; /* Print out the depths */ printf ("\nIts depth at sea: \n"); printf (" %d fathoms \n", fathoms); printf (" %d feet \n", feet); printf (" %d inches \n", inches); }

The Output

lassie% cc wreck.c lassie% a.out Its depth at sea: 7 fathoms 42 feet 504 inches


Declaring variables

At the line:

int inches, feet, fathoms;

3 blocks of memory are allocated, each big enough to hold an integer. The name inches is associated with the first block, feet the second and fathoms the third. The blocks of memory contain garbage and will contain grabage until you change the value of the variable.


Basic Data Types

Predefined types in C:


Constants

Examples of integer constants

0 77

These are not good integer constants

1234567890 /* Legal, but might be too large */ 0123 /* Legal, but in octal (base 8) */ 123.0 /* A floating point constant */


What is an "integer expression"?

An "expression" is either a constant, variable, or the result of operators involving expressions. So, an integer expression is an integer constant, an integer variable, or the result of an integer-producing set of operations on expressions.

Examples of floating point constants

3.14159 314.159e-2

These are not good floating point constants

3,141.59 /* No commas allowed */ 314159 /* This is an integer constant */

Examples of character constants

'a' '3'

Examples of string constants

"Hello World" "Charlie Brown and Snoopy" "" /* the empty string */ " " /* string of spaces */ /* "This is a comment" */


An example showing assignment to different data types

The Program

/* File: example.c Assigning constants to different data types. */ #include <stdio.h> main() { /*Declare variables */ int i; double x; char c; /* Assign values to a variable of type int */ /* and print them */ i = 345; printf("The variable i contains: %d\n", i); i = 678; printf("The variable i contains: %d\n", i); i = 123.74; printf("The variable i contains: %d\n\n", i); /* Assign a value to a variable of type */ /* double and print it */ x = 314.159e-2; printf("The variable x contains: %f\n", x); x = 12; printf("The variable x contains: %f\n\n", x); /* Assign a value to a variable of type */ /* char and print it */ c = 'a'; printf("The variable c is %c character.\n", c); }

The Output

lassie% cc example.c lassie% a.out The variable i contains: 345 The variable i contains: 678 The variable i contains: 123 The variable x contains: 3.141590 The variable x contains: 12.000000 The variable c is a character. lassie%