CSCI 130 Chapter 3
Variables & Names Variable Declarations: –reserve a storage location in memory –identify the name of the variable –identify the type of the variable Ex: int a;
Naming rules for variables Only certain characters are legal –letters, digits, underscore ( _ ) First character must be a letter –underscore allowed but not advised Case sensitive –count, Count are two different variables Cannot use keywords
Variable Types Nonnumeric –character Numeric –signed, unsigned (signed is the default) –char, integer, floating point
Ranges / Memory Allocation Each type has a range of numbers How you use the variables in the program will determine what type you use –memory usage (efficiency) –magnitude of range Ex: open VarRanges.doc
Variable Declarations Variable declaration informs compiler of: –name of variable –type of variable Must be declared before being used Form: –typename varname;
Sample Variable Declarations int counter; char x; float salaryAccumulator; signed int z;
typedef Creates new name for existing data type Does not create new type, only creates a new name (synonym) Ex: –typedef int integer; –integer thisIsAnInteger; –int thisIsAnIntegerTo;
Numeric Variables Variables need to be initialized before being used Ex 1: –int x;Sets aside storage space for x –x = 3;Stores the value 3 in x Ex 2: –int x = 3;
Symbolic Constants Created in one of 2 ways: –#define –const keyword Cannot change value –compiler error
#define #define PI 3.14 –no equals sign –no semi-colon –no variable type PI cannot be changed in program PI is a symbolic constant –area = PI * radius * radius
const const int PI = 3.14; PI is a symbolic constant Can be used in formulas –area = PI * radius * radius
printf Will print information out to the screen –printf(“Hello world”); –printf(“Hello world\n”); prints Hello World and a carriage return –printf(“The area is %f”, area); prints: The area is xxx –xxx is the value held in the variable area
scanf Will accept information from the screen –scanf(“%d”, &area) –scanf(“%f%f”, &area, &diameter)