Introduction to Programming for Laymen
First, Flow and Functionality of a Program
The basic functionality of any program is - based on some input data - to create some result. That is:
Input (data in) -> |
Processing -> |
Results (data out) |
- Input can be your raw data from collecting survey results, measurements from an instrument, etc.
- Entered via fields in a form, in what we call graphical user interface (GUI) applications, like a web page, in Excel spreadsheet cell, etc.
- Provided as arguments to command line interface (CLI) tools, including batch files, do files, etc.
$ man gcc # show manual page for gcc command (*NIX, Mac)
$ tab v1 v2 # cross tabulate two categorical variables (Stata)
- Processing include decisions you make (ok, your program) and calculations on the data
- Is input data correct? (User entered a name but it must be a date, enter month must be within 1 and 12). If month is between 1 and 3, then handle first quarter type calculations, else ...
- And now you see the need for knowing Other Disciplines (in What Is a Language?):
- Decision-making involve logic, and
- Calculations involve mathematics.
- Output is the presentation of the results - like printing on a printer or terminal, creating a nice graphic, etc.
Programming Constructs
As we talked about in What Is a Language?, to learn a language you need to learn
- Words - 'basic building blocks'
- Grammar - rules for putting words together
- Semantics - the meaning of your 'sentences', your programming
In programming languages, we expand on those concepts (fine tune) and use some basic terminology to discuss different building blocks used in programs and programming, called programming constructs (google).
- Reserved Words - words with special meaning in the language
- For (e.g.) defining constants, variables and flow control.
|
- Some of JavaScript's
reserved words are:
|
break, case, continue, do, else, for,
function, if, in, new, return, switch,
this, typeof, var, while, with
|
- Constants - declare values, pieces of information, that should never change throughout the program (like a copyright notice, PI - the mathematical constant)
- Some languages doesn't have explicit constants (e.g. JavaScript...)
- In C, constants are declared with the reserved word
const
.
- Declare vs Define -
- Declare: say something exists, will exist
- Define: actually implement code to fully support its use, definite all parts/components, allocates memory, ...
http://www.cprogramming.com/declare_vs_define.html
- Variables - containers (keepers, holders) of values, results from calculations, etc
- Data Types - define what type of data a variable can hold (integers, strings, ...)
- Data types are important for declaring constants and variables and when using information in expressions. You need to know the data type of the information to get the result you want (need).
- In JavaScript:
a = 2; // type is an integer
b = "2"; // type is a string
aa = a + a; // put contents of the two variables together
bb = b + b; // put contents of the two variables together
document.writeln(aa); // prints 4 (2 + 2)
document.writeln(bb); // prints 22 ('2' + '2') |
- Some languages are stricter than other languages
with the data type of variables and constants
- For instance, C is strict:
int x; /* declare a variable of type int, integer) */
x = 3; /* Ok, 3 is an integer */
x = 3.14; /* Compilation error - illegal to assign value of wrong type
(float = floating point, decimals means not an integer) */ |
- Expressions - calculations or comparisons that returns - evaluates to - a result (e.g. a numeric value, a text, true or false, ...)
- Result from the evaluation can be assigned to a variable or used in a conditional statement:
annual_salary = monthly_salary * 12 ; // evaluates to a numeric value
if ( annual_salary > annual_expenses ) // evaluates to true or false
{
I_am_in_big_trouble_subroutine();
}
personalized_hello_text = "Hello " + "Bob"; // evaluates to a concatenated text |
- wikipedia.org/wiki/Expression (computer_science)
- wikipedia.org/wiki/Boolean_expression
- Operators - used in expressions (e.g. +, -, *, /, \, <, >, =, ==, ...)
- Note: operators can really be an area of bugs tricky to find, especially in a language like C where '=' and '==' can both be used but with different meaning (semantics), and both can be used in an expression...
a = b = c == d;
(example of really poor programming, but allowed in C)
- wikipedia.org/wiki/Operator (programming)
- Control Statements (a.k.a. Flow Control Statements, Control Flow Statements) - if - then - else, while, for, ... - to control the flow of your program
- As statement (e.g. C):
if ( condition ) // there is NO 'then' in C language
{
xxx; // statement(s) evaluated when condition evaluates to TRUE
}
// optionally, continue with an 'else' part:
else
{
yyy; // statement(s) evaluated when condition evaluates to FALSE
}
- As expression: some languages (e.g. C, JavaScript) also allows forms of conditional expressions:
x = condition ? xxx : yyy; // === as statement: if (condition) then x = xxx else x = yyy;
- wikipedia.org/wiki/Control_flow
- Comments
- Always make a habit of commenting your code! Even if you're using descriptive names for constants, variables, and functions, you should still add comments on reasoning behind logic, etc. Both for your own sake and other programmers for later maintenance, adding new features, and fixing bugs. You will NOT remember why you implemented a specific solution in the way you did six months from now. Hey, you will barely remember in two weeks...
- Research from 2008 showed average comment density of 1085 open source projects was around 19%. I.e. for every 5 lines of text in source code, one line was comments. [source; local copy]
- Comments can in many - but NOT all - programming languages be of two forms:
- Multiline - everything between specific start- and stop markers
- Single-line comment - everything from specific comment-marker to end of that line.
- Examples
- wikipedia.org/wiki/Comment_%28computer_programming%29
- google.com/search?q=comments+in+programming+languages
- Statements - smallest piece of complete code
that makes sense in the programming language.
- Statements, from C# Programming Guide:
"The actions that a program takes are expressed in statements. Common actions include declaring variables, assigning values, calling methods, looping through collections, and branching to one or another block of code, depending on a given condition. The order in which statements are executed in a program is called the flow of control or flow of execution. ...
A statement can consist of a single line of code that ends in a semicolon, or a series of single-line statements in a block." [src] |
- Like a sentence in a natural language like English: it must be gramatically complete (nouns, verbs, and so on), and properly end. Most common with a period (.) but could be other end markers (e.g. question mark - ? - and exclamation mark - '!').
- I'm your daddy. Who's your daddy? I'm your daddy!
- And the same goes for statements in programming languages - must be syntactically correct, make sense, and with proper ending.
- How to end a statement (of course) varies between programming languages. Some languages are strict - a good thing (like C) - whereas others are more flexible (can create difficult-to-find bugs).
- JavaScript is flexible and allows both ending statements with semicolon (';')
and simply by end-of-line.
// 'properly' ending each statement with ';'
a = 2;
b = "2";
// but this is also allow in JavaScript (relying on end-of-line):
a = 2
b = "2"
// btw, when using proper statement end marker, the following is also ok:
a = 2; b = "2"; |
- Recommendation is always using proper end-of-statement marker (';' in JavaScript).
- Unlike natural languages, you may actually have empty statements, which actually have their use.
void ProcessMessages()
{
while (ProcessMessage())
; // Statement needed here.
} |
- wikipedia.org/wiki/Statement (computer_science)
- Statement Blocks - the enclosing of one or more statements together, most often using '{' and '}' (e.g. C/C++, Java, JavaScript, Perl, PHP, ...).
- Very important especially when using if-then-else conditional statements and is another cause of difficult-to-find bugs.
Written code: |
How actually interpreted by interpreter or compiler: |
// Example 1:
if (moneyLeft >= 1000)
moneyLeft = moneyLeft - buy_shoes(300);
moneyLeft = moneyLeft - buy_toys(500);
// Example 2:
if (moneyLeft >= 1000)
{
moneyLeft = moneyLeft - buy_shoes(300);
moneyLeft = moneyLeft - buy_toys(500);
} |
// Example 1:
if (moneyLeft >= 1000)
moneyLeft = moneyLeft - buy_shoes(300);
moneyLeft = moneyLeft - buy_toys(500);
// Example 2:
if (moneyLeft >= 1000)
{
moneyLeft = moneyLeft - buy_shoes(300);
moneyLeft = moneyLeft - buy_toys(500);
} |
Improper indentation (spacing, tabs) can be very misleading - why you should make it a habit to ALWAYS use {} in conditional statements.
- Note that command processors - script languages - like sh (Bourne shell), bash (Bourne-again shell), and others are a bit different with use of do ... done. See also more on different shells at comgt.com/lib/shells.
- Subroutines (a.k.a. functions, methods, procedures, subprograms)
- To break up a program in smaller, more manageable portions, and/or for reuse code or functionality in multiple places in your program
- google.com/search?q=Subroutines
- Scope - whether a constant or variable is visible, it's content can be used or changed
- Scope is a very important concept when you start breaking up your development in functions, modules, libraries, ...
- White Space, Indentation, ... - how source code is read by interpreter or compiler (preprocessor).
Example: A Small Program
To exemplify a few of the constructs just discussed (e.g. comments, constants, variables, control statements, expressions, ...):
/* My small program to calculate the Circumference of a Circle
i.e. C = pi x D; where
C = the Circumference, and
D = is the diameter of the circle
*/
pi = 3.14159; // a Constant; and infinitely many more decimals...
/* Note: not a formal constant as JavaScript doesn't (currently) have that
construct. */
var diameter; // a Variable; user input
// Next, using an assignment operator, get user input to the variable
do {
diameter = prompt("Enter diameter (> 0)", 5);
} while (diameter <= 0);
result = diameter * pi; // calculating a result, using an expression
alert( "The circumference of a circle with diameter " + diameter + ' is ' + result );
Press here to run and test this small and simple program.
Now, try do the same (slightly simplified) by yourself. Select and copy the text below into Workbench 3L.
pi = 3.14159
var diameter
diameter = prompt('Enter diameter', 5);
results = diameter * pi
alert( "The circumference of a circle with diameter + diameter + ' is ' + result );
What happens? Nothing! Carefully read the code and see if you can find the problems (two different).
Hint 1: variable name
Hint 2: text strings
More Resources
Updated
2016-06-02