This document was last modified
Programming Languages
statements similar to English and mathematical notation
for (count=0; count<=NUM; count=count+1)
Interpreter -- executes each statement in program language at "run time"
Compiler -- inputs programming language (source code), outputs machine language (object code) that is used at "run time"
Data Types and Program Structure
Standard Data Types
Pre-defined, built-in...
Integer Data Type (int)
about 10-11 digits
positive and negative
Floating Point Data Type (float)
[+|-] int.int
323.725
-18.62
+6.05
Character Data Type (char)
American Standard Code for Information Interchange (ASCII) character set
'q' = 113
Can sometimes perform some arithmetic operations on characters
'C' < 'H' because 67 < 72
String = collection (array) of characters
"Super Bowl"
Identifiers
Identifier -- name of variable, function, data file, etc.
Usually letters and digits, but may allow some special characters like _, $, @, %, #
Usually begin with letter
index
first_name
shipping_rate
total
Case usually matters ...
sum, Sum, SUM
All different, but DON'T use more than one
No length restriction
5-10 characters is usually about right
Use mnemonic identifiers
total_charges
is much better than
x
Variables
Variable can take on different values
Usually declared "at top" of program or function
<type> <identifier> = <value>;
<type> <identifier>;
Define one variable per line and comment it
// typically introduces a comment
float voltage; // voltage in kv
int current; // current in amps
float sum = 0.0; // total pay amount
char group; // group is A-E
char name [20]; // employee's name
char day [10] = "Monday"; // day of the week
Input and Output
Standard input is accomplished via some statement like...
Standard output is accomplished via some statement like...
Standard Operations and Functions
Arithmetic Operations
add +
subtract -
multiply *
divide /
remainder %
force = mass * accel; average = total / size; r = x + y*z - q/h; 11 / 3 is 3 11.0 / 3 is 3.6667
/ usually returns integer if both parameters are integer, and float if either parameter is type float
11 % 3 is 2
Operation Order
Within parentheses
*, /, % left-to-right
+, - left-to-right
Good rule of thumb: Use Parentheses!
s = t / (a + s * (x-z)) + q;
Increment and Decrement Operators
increment ++
decrement --
++count; // count = count + 1; --drop; // drop = drop - 1; ++x ... pre-increment x++ ... post-increment Suppose x=7, y=5... a = ++x; // x=8, a=8 b = y++; // y=6, b=5
Pre/post-decrement work same way
Assignment Operators
= simple assignment
+= addition assignment
slug += zig*zag; // slug = slug + zig*zag;
-= subtraction assignment
drop -= few; // drop = drop - few;
*= multiplication assignment
/= division assignment
Boolean Operators
Boolean Operators result in
true
false
== or eq ... equal to
(sum == size)
result is true if sum equal size
result is false if sum not equal size
!= or ne ... not equal to
(sum != size)
< or lt ... less than
(sum < size)
<= or le ... less than or equal to
> or gt ... greater than
>= or ge ... greater than or equal to
Control Structures
Sequence -- one statement after another
Selection -- take one path or another
if if...else switch
Iteration -- loop
while do...while for
if (Decision) Statements
if statement
if (expression) { statement-1; statement-2; ... statement-n; }
expression usually must be in parentheses
braces on separate lines
indent 3-4 spaces
if expression is true, execute block
if expression is false, skip block
if (sum == size) { result = total / size; write result; }
What if only 1 statement in block?
OK ---
if (sum == size) result = total / size;
Preferred ---
if (sum == size) { result = total / size; }
if/else statement
if (expression) { statement-1; ... statement-m; } else { statement-1; ... statement-n; }
if expression is true, execute 1st block, skip 2nd
if expression is false, skip 1st block, execute 2nd
if (sum == size) { result = total / size; write result; } else { total += voltage; sum++; }
Again, still use {...} if only one statement in either block
switch statement
if statement has one branch
if/else statement has two branches
switch statement has multiple branches
Case statement
Selector variable
Compared to set of possible matches
switch (selector variable) { case value-1: statement-1; ... break; case value-2: statement-1; ... break; ... case value-n: statement-1; ... break; }
Here is an example:
switch (size) { case 5: x = s - z; break; case 10: x = s * z; --y; break; case 15: x = s + z; break; }
Do you need the last break statement? Not really. But what if you add a new case???
Several values can go to same set of statements
switch (size) { case 3: case 5: x = s - z; break; case 8: case 10: case 13: x = s * z; --y; break; case 15: x = s + z; break; }
What if selector variable matches two cases? Normally goes to first match.
What if selector variable does not match any cases? Skips all statements.
default may be used if no other matches
switch (size) { case 5: x = s - z; break; case 10: x = s * z; --y; case 15: x = s + z; break; default: write "Incorrect size."; break; }
put default last because it matches anything
Loops
Pretest -- test a condition each time BEFORE the loop is executed (while)
Posttest -- test a condition each time AFTER the loop is executed (do...while)
Fixed Repetition -- execute the loop a pre-determined number of times (for)
The while loop
while (expression) { statement-1; statement-2; ... statement-n; }
if expression is true, execute block and return to while statement
if expression is false, skip block
If expression false first time encountered, statement block not executed even once
while (melt < final_score) { read plenum; melt += plenum; discrep = mass * accel; }
The do/while loop
do { statement-1; statement-2; ... statement-n; } while (expression);
If expression false first time encountered, statement block still executed once
if expression is true, execute block again and return to while statement
if expression is false, do not execute block again
do { pay = base - deduct + overtime; hours -= base_hours; } while (hours > 0);
The for loop
for (initialization; expression; increment) { statement-1; statement-2; ... statement-n; }
Initialization -- give initial value to variable
Expression -- test variable against some limit
Increment -- Add (or subtract) something (usually 1) to (from) variable
for (count = 1; count <= 12; ++count) { read temp; write "The temperature at ", count; write ":00 is ", temp; }
Loop variable (count) can be used in loop, but probably should not be altered...
// Caution - this does not do what you want... for (count = 1; count <= 12; ++count) { read temp; write "The temperature at ", count; write ":00 is ", temp; count = count +1; }
for (count = 0; count <= table_size; count = count + 5) {...}
Suppose table_size is -9. Loop statements will not be executed even once (pretest loop).
for (count = 25; count > 0; --count) {...}
for (count = 25; count; --count) {...}
Nested Loops
for (hours = 0; hours < 24; ++hours) { for (mins = 0; mins < 60; ++mins) { for (secs = 0; secs < 60; ++secs) { ... } } }
While and do...while loops can be nested as well
break statement -- immediately terminates loop
Usually used with if statement within loop to terminate if some condition develops
while (radiation > lowest) { ... if (radiation > highest) break; ... }
Some loops are un-ending on purpose...
char code; char stop = 'q'; ... while (true) { read code; if (code == stop) break; ... }
continue statement -- skips this iteration
Usually used with if statement within loop to avoid some problems but to continue the looping mechanism
while (input_flag == more_data) { ... if (group_size == 0) continue; average = sum / group_size; ... }
Functions
Function is block of statements to perform specific task
Functions eliminate need for duplicate statements -- same function can be invoked from multiple locations
Use of functions also enhances program readability
Function Format
return_type function_name ([parameter_list]) { // declare local variables statement-1; ... statement-n; return [(return_value)]; }
void main () { ... s = max (y, z); ... if (max (a,b) > ROOF) {...} ... }
int max (int num1, int num2) { int part; part = num1; if (num2 > num1) { part = num2; } return (part); }
Function Header is first line
return_type function_name ([parameter_list])
May have none, one, or more arguments (parameters)
Actual arguments and function parameters should be same number and types
int max (int num1, int num2) {...} int a; int b; int c; float d; char e; ... a = max (b,c); //OK a = max (a,b,c); // wrong number a = max (c,d); //wrong type d = max (a,b); //OK
Return statement should be last statement of function
Arrays
Array is indexed data structure used to store data elements
Can have arrays of ints, floats, chars, ...
Zero-based arrays -- indices are 0,1,2,....
Array of ints (age)
5 11 7 4 0 21 6 2 14 7 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
age[5]
array name is age
array index is 5
array element is 21
All elements in array must usually be same type
Declaring Arrays
data_type array_name [number_elements]; int age [10]; float temp [24]; char name [20];
Array of characters is usually "character string"
Accessing Arrays
age [i] = 24; weight [i] = pounds; name [k] = 'B';
Arrays and Loops
for (i=0; i<10; ++i) { weight [i] = 0.0; } for (i=0; i<10; ++i) { read weight [i]; } warm = 0.0; for (time=0; time<24; ++time) { write temp [time]; warm += temp [time]; }
Classes and Objects
Class is a way of providing additional data types
Class defines data members (Fields), constructor functions (Constructors), and associated functions (Methods)
public class Button { // Fields public String label; public Color shade; // Constructors public Button (); public Button (String label); public Button (String label, Color shade); // Methods public void setLabel (String label); public String getLabel (); public void setColor (Color shade); public Color getColor (); }
String and Color are also classes. A Button has two Fields -- a label (which is a character String) and a shade (which is a Color).
// public Button (); // creates a button with no label // and a standard gray shade Button pushme = new Button ();
// public Button (String label); // creates a button with the indicated label // and a standard gray shade Button pushme = new Button ("Press here to reset");
// public Button (String label, Color shade); // creates a button with the indicated label // and the indicated shade Button pushme = new Button ("Press here to reset", red);
// public void setLabel (String label); // changes the label to the one indicated pushme.setLabel ("Push to reset"); // the button's label is now "Push to reset
// public String getLabel (); // returns the label on the button String whatsay = pushme.getLabel (); // the String whatsay is now "Push to reset
// public void setColor (Color shade); // changes the shade to the one indicated pushme.setColor (green); // the button's label shade is now green
// public Color getColor (); // returns the shade on the button Color whathue = pushme.getColor (); // the Color whathue is now green