Outline:

Venit on-line stuff
History
Spiral Development Model
Outline of course
Memory, variable declaration and initialization
Basic program development order
Order of Operations
Raptor
For loops

Arrays 1
Arrays 2
Module vs Function
Function Practice
Functions and classes
Combinations
Syntax of some popular languages
Student class example
Respond
Forward
08/09/2013 10:48PM

Venit on-line stuff

Note # 10
by Nick Duchon

http://www.aw-bc.com/cssupport/

Respond
Forward
08/09/2013 10:48PM

History

Note # 14
by Nick Duchon

CMIS 102 HW - History

Problem 1 - People

Fill in the following table.

Last Name First Name Dates Key Achievement Algorithms
Theory
HardWare?
Aiken Howard      
Allen Paul      
Archimedes        
Atanasoff John      
Babbage Charles      
Bardeen John      
Berry Clifford      
Boole George      
Brattain Walter      
Burroughs William      
Bush Vannevar      
Cray Seymour      
de Forest Lee      
De Morgan Augustus      
Eccles W. H.      
Eckert John      
Euclid        
Faraday Michael      
Fleming John      
Gates Bill      
Glidden Carlos      
Godel Kurt      
Gunter Edmond      
Herzstark Curt      
Hilbert David      
Jacquard Joseph Marie      
Jahnz Edwin      
Jordan F. W.      
Kay Alan      
Kilburn Tom      
Kilby Jack      
Leibniz Gottfried      
Lovelace Ada Byron      
Mauchly John      
Moggridge William      
Monroe Jay      
Moore Gordon      
Napier John      
Newton Isaac      
Pascal Blaise      
Quevedo Leonardo Torres y      
Rechnitzer Richard      
Shannon Claude      
Shockley William      
Sholes Christopher      
Soule Samuel      
Stibitz George      
Turing Alan      
Vera Ramon      
von Neumann John      
Wilkes Maurice      
Williams Frederic      
Wynn-Williams C. E.      

Problem 2 - Programming Language

Select a computer programming language and tell us a little about it. Use 8 sentences, 2 paragraphs, to talk about its development, history, why it was developed, its popularity, a few key features of the language, and anything else that you think is most important about the language you have chosen. There are over 2000 such languages, and a google search on the following terms gives a lot of sites: "computer language list".

Problem 3 - Ethical issues - A Tycho Discussion.

Present your answer to this problem in the Tycho Work Conference H1 - History The Course Modules, Module 1, Section III, describes a number of issues related to computer ethics. Take one of those issues and describe a situation where that ethical issue should be addressed in guiding one's behavior. You may make up a scenario, or take one from your own experiences, or one that you have read about.

Respond
Forward
08/09/2013 10:48PM

Spiral Development Model

Note # 9
by Nick Duchon

I very much prefer the Spiral Development model of software development. 

I'm lost!

This seems to be a common reaction by beginners when confronted by a programming problem.

This is not good.

So is there an approach to get us moving? Well, yes. Spiral Development.

Spiral Development Model

Note how soon we get to a Test Plan. This is a detailed description of exactly what we EXPECT the code to do. 

If we cannot come with a detailed test plan (a few test cases, at least) we have a red flag warning that we have not understood the problem.

After that, nearly all programs have 3 basic phases:

  1. Input
  2. Processing
  3. Output

Complicated programs may do this over and over again, and output from one part becomes the input of other parts, but the IPO (input-process-output) view is where nearly all programming starts.

An Example

So let's try this on a simple example problem: get 3 numbers from the user and compute their average.

Many of you have already remarked on the variety of numerical types, but in this class, we will concentrate on only two:

So, first question, will we work with real numbers or integers? Let's consider a specific case and see if we can gain insight. How about 1 and 2. The average should be 1.5, which is a real number. 

Conclusion: seems like this program should work with real numbers, they come about naturally when computing averages.

Note that we almost have a test case. Let's develop a few. 

Test Plan

EMPHASIS: these are not just "try some numbers", these are exact numbers with exact expected results. 

Also, we have not done ANY coding yet. We are just trying to figure out what the program is SUPPOSED to do.

 

Input Expected Output
1, 1, 2 1.333
2, 2, 5 3
-5, -10, -15 -10

 

User's Guide

Since we now have a good idea what the program is supposed to do, we can write a User's Guide, explaining to a user how to interact with the program, what prompts to expect from the program, and a user can expect as output. We can describe this as a scenario example.

After you start the program, you will be prompted to enter 3 numbers (they may be real), separated by spaces. After that, the program will display the average of the 3 numbers and indicate that it is done by saying "bye...". 

For example, the program types the stuff in black, you would type the stuff in red:

run MyAverage
Enter 3 real numbers: 2 2 5
The average of those numbers is: 3
bye...

Design

This is pretty simple here:

  1. Declare required variables - the specific ones are still to be determined.
  2. Prompt the user for input.
  3. Get input from the user.
  4. Compute.
  5. Display the results to the user.
  6. End.

Almost all programs will follow this basic design pattern!

Coding

Were should we start? Most beginners think the way to start a program is at the top, but my experience really suggests that the best way to write code is FROM THE END!

Consider the following phased development:

Phase 1 - write bye:

MAIN
 write "bye..."
END MAIN

Phase 2 - display output:

MAIN
 write "The average of those numbers is: " + average
 write "bye..."
END MAIN

We need a variable called average, and we need to give it a value before we get to this line. On the other hand, this line WILL give the desired output!

Phase 3 - compute the average:

MAIN
 average = (n1 + n2 + n3) / 3.0

 write "The average of those numbers is: " + average
 write "bye..."
END MAIN

This will now compute the average of three numbers. We will eventually have to declare n1, n2 and n3, with the right types, but that is to come. Also, note that we are dividing by a real number (3.0), rather than the integer (3).

Phase 4 - get the input from the user:

MAIN
 input n1, n2, n3

 average = (n1 + n2 + n3) / 3.0
 write "The average of those numbers is: " + average
 write "bye..."
END MAIN

Well, this does give n1, n2 and n3 values. And we now know that average will actually be given a value based on those inputs.

Phase 5 - prompt the user:

MAIN
 write "Enter 3 real numbers: "

 input n1, n2, n3
 average = (n1 + n2 + n3) / 3.0
 write "The average of those numbers is: " + average
 write "bye..."
END MAIN

This is from the User's Guide!

Phase 6 - declare the variables:

MAIN
 REAL n1, n2, n3, average

 write "Enter 3 real numbers: "
 input n1, n2, n3
 aveage = (n1 + n2 + n3) / 3.0
 write "The average of those numbers is: " + average
 write "bye..."
END MAIN

Not just any variables. And we KNOW we need these variables to get this code to work. We are not guessing. We are not hoping that we will not need more or fewer variables.

It is now time to test this program against our test cases. I leave it to you to show that the test cases actually work as advertised.

Respond
Forward
08/09/2013 10:48PM

Outline of course

Note # 1
  1. Data types (C++ types)
    1. integer (int)
    2. real (double)
    3. character (char)
    4. String (none)
    5. boolean (int)
  2. Operations:
    1. Arithmetic: +, -, *, /, %
      1. promotion of int with real to real
      2. integer version of /
    2. Boolean: AND, OR, NOT
    3. String: + or & (concatenation)
    4. Assignment: =
  3. Input/output:
    1. input = read (cin >>)
    2. output = write (cout <<)
    3. files
  4. Flow:
    1. Sequential
    2. Branching
      1. if/else/endif
      2. switch/case/default/break
    3. Loops
      1. pretest: while (cond) / endwhile
      2. posttest: do / while (cond)
      3. for (i; c; u) b
    4. function call / return
  1. Data structures = arrays
    1. declaring, type and size
    2. base: C/C++/Java use 0-based indexing
    3. element access by index
    4. initializing
  2. Comments
    1. C-style: // or /* to */
    2. Basic style: ;
    3. header comment block;
  3. Functions
    1. [in], [out], [in/out] parameters
    2. declaration:
      1. return type, possibly void
      2. name
      3. parameter list
        1. type
        2. name
        3. by value vs reference
    3. body
    4. return (optional if return type is void)
    5. calling a function
    6. handling return value 

Program outline:


// library stuff

// functions
// main program

main

  variable declarations

  menu loop

    input

    algorithms

    output

  end menu loop

end main

Simple for loop flow
            chart

Respond
Forward
08/09/2013 10:48PM

Memory, variable declaration and initialization

Note # 3
by Nick Duchon

Here's some pictures about memory that might help you visualize the concepts of declaring and initializing variables, and giving variables values.

Here's a view of memory as a lot of empty, unlabelled boxes. Think of this as the memory that the operating system is giving your program.

Memory as post office boxes

The following is what happens after the following code is executed:

Code Comments
1  Declare b boolean
2  b = True
3  Declare n1 as integer
4  n1 = 13
5  Declare f1 as float
6  f1 = 3.25
7  Declare n2 as integer
  1. I have colored this box green, to show that only a boolean value (T or F) will be allowed here
  2. This puts the value T into this box.
  3. This box is red, note the label and type, only an integer value will be allowed here.
  4. This puts a value, 13, into this box.
  5. This box is colored yellow, only a float value will be ok here.
  6. This line puts the value 3.25 into this box.
  7. This box is colored red, but it has no value yet!

Memory with types and data

Respond
Forward
08/09/2013 10:48PM

Basic program development order

Note # 4
by Nick Duchon

// input 5 numbers and compute their average
// Can use MS Visual Studio
Main
  declare average as float                // 2 - declare the variable I needed
  declare n1,n2,n3,n4,n5 as float         // 4 - declare these variable used in 3
  write "Input 5 numbers: "               // 6 - be nice to user, prompt
  input n1, n2, n3, n4, n5                // 5 - initialize values from user input
  average = (n1 + n2 + n3 + n4 + n5) / 5  // 3 - give average a value
  write "The average is: ", average       // 1 - variable needed because we will compute this
end main

Respond
Forward
08/09/2013 10:48PM

Order of Operations

Note # 11
by Nick Duchon

Here's a graphic showing the impact of order of operations.

The figure compares two expressions:

The evaluation of these trees starts at the bottom and works its way to the top. 

Thus, in the first expression, we start by evaluating 45/3 giving 15, then 15*5 = 75, finally 100-75 = 25

In the second expression, we again start at the bottom: 3*5 = 15, then 45/15 = 3, finally 100 - 3 = 97.

We can see very clearly the difference between the two expressions, and how important it is to write an expression exactly the way one wants it to be evaluated!

 

100 - 45 / 3 * 5 100 - 45 / (3 * 5)

 

Also, you can see from these trees that an evaluation tree makes it very clear exactly what the order of evaluation will be. In classes such as CS 2, you will explore evaluation trees along with other ways to represent expressions, such as prefix and postfix notations.

Respond
Forward
08/09/2013 10:48PM

Raptor

Note # 7
by Nick Duchon

I have also attached a Raptor zip file which you can download and run without installing the product if your computer has security limitations.

Here's a link I have made about creating Raptor functions:

Here's the links to a very nice YouTube introduction to Raptor:

  1. Raptor 01 - Introduction - http://www.youtube.com/watch?v=ZcAALK3movs&feature=mfu_in_order&list=UL
  2. Raptor 02 - Variables - http://www.youtube.com/watch?v=eEoxssLPvkQ&feature=mfu_in_order&list=UL
  3. Raptor 03 - Files and Strings - http://www.youtube.com/watch?v=8Qx2w2CDKrk&feature=mfu_in_order&list=UL
  4. Raptor 04 - Graphics - http://www.youtube.com/watch?v=TW1rNIFzV-8&feature=mfu_in_order&list=UL
  5. Raptor 05 - Selection - http://www.youtube.com/watch?v=vt7nyzxxylY&feature=mfu_in_order&list=UL
  6. Raptor 06 - Loops - http://www.youtube.com/watch?v=_BTRJjFZY2Y&feature=mfu_in_order&list=UL
  7. Raptor 07 - Subcharts - http://www.youtube.com/watch?v=TR2vm7XGL0o&feature=mfu_in_order&list=UL
  8. Raptor 08 - Animation - http://www.youtube.com/watch?v=zCqZZkNDE9o&feature=mfu_in_order&list=UL
  9. Raptor 09 - Arrays - http://www.youtube.com/watch?v=d2qlLvM4ijo&feature=mfu_in_order&list=UL

ND.

 

Respond
Forward
09/16/2013 05:20PM

For loops

Note # 17
by Nick Duchon

 For loops

Respond
Forward

Arrays 1

Respond
Forward
08/09/2013 10:48PM

Arrays 2

Note # 15
by Nick Duchon

Some array algorithms

Respond
Forward
08/09/2013 10:48PM

Module vs Function

Note # 2
by Nick Duchon

Shohn - 

This is so important for everyone that I will post the question and reply in the Musings Conference for everyone.

You should ask this question in the Work Conference, I am sure everyone else will be interested in the answer also.

So, the module representation Venit uses earlier in the text is a simplified version of the functions we defined last night. 

The modules have a name, would not have a parameter list, and would not not have a return type. The assumption is that the variables used in main are shared with the module. We will talk about sharing variables vs passing parameters next class - the distinction is subtle, but can be very important.

For the moment, let's just assume all the code you have written is ok.

The one change I would make is to label the module with the keyword module, as I have highlighted below.

ND.


From: Shohn Martin
Subject: HW4 Code... Please Review?
Sent: Fri Feb 22 2013 01:45:00 GMT-0500 (Eastern Standard Time)

Would you mind reviewing this? I'm also unsure on how to represent functions within the hierarchy chart since they're not modules

MAIN
    /* Declare global variables. */
    DECLARE lenRect, widRect, areaRect, perimRect AS FLOAT

    /* Display welcome message. */   
    WRITE “Welcome to Rectangulation, v1.0!”
    WRITE “”
    WRITE “This program will calculate the surface area and perimeter of a
          rectangle.”
    WRITE “”

    /* Call modules */
    CALL INPUT
     CALL OUTPUT

     /* Display exit message. */
     WRITE “Thank you for using Rectangulation!”
     WRITE “”
END MAIN

MODULE INPUT
/* The user is prompted for the dimensions of the rectangle. Or enters zero
to exit. */

    WRITE “Please enter the dimensions of the rectangle.”

    WRITE “Length: “
         INPUT lenRect
         WRITE “”

    WRITE “Width: “
         INPUT widRect
         WRITE “”
END INPUT

MODULE OUTPUT
/* Display the results of the calculations. */

    /* Display the dimensions of the rectangle. */
    WRITE “The dimensions of the rectangle are “ + lenRect + “ x ” +
          widRect + “ (L x W).”
    WRITE “”

    /* Display function results. */
    WRITE “Surface Area: “ + areaFormula(lenRect, widRect)
    WRITE “Perimeter:   “ + perimFormula(lenRect, widRect)
    WRITE “”
END OUTPUT

FLOAT areaFormula(FLOAT l, FLOAT w)
    SET areaRect = l * w
    RETURN areaRect
END FUNCTION

FLOAT perimFormula(FLOAT l, FLOAT w)
    SET perimRect = 2*(l + w)
    RETURN perimRect
END FUNCTION

Respond
Forward
08/09/2013 10:48PM

Function Practice

Note # 5
by Nick Duchon

Here are a bunch of problems to help you practice functions:

Here are some more notes about functions and how they differ in the various environments we are using in CMIS 102 (Venit, C++, Raptor). The differences are actually rather annoying, but there we are.

Respond
Forward
08/09/2013 10:48PM

Functions and classes

Note # 6
by Nick Duchon

Here are a series of presentations on formatting pseudo-code using functions.

Outline:

The first starts with a block of code that is using functions to organize a project. This presentation also inserts a main function to organize the subroutine calls.

The third presentation will address the use of local variables, parameters, including the use of reference parameters, also known as [in/out] parameters.

And the fourth presentation will show how one can use classes effectively in this application.


Respond
Forward
08/09/2013 10:48PM

Combinations

Note # 12
by Nick Duchon

A variety of algorithms to calculate nCk.


// File: combinations.cpp
// Date: Nov 18, 2009
// Author: Nicholas Duchon
// Purpose: Algorithms to calculate nCk

#include < iostream >

using namespace std ;

// prints the elements of an integer array
// a = array, len = number of elements to print
void printm (int a [], int len) {
for (int i = 0; i < len; i++)
cout << a[i] << " ";
cout << endl;
} // end printm


// creating pascal's triangle
// combination of n things taken k at a time
// returns n choose k, nCk, C(n, k)
// Algorithm: create Pascal's triangle using ping-pong rows
// final answer selected from k-th element in row n
// printing: complete triangle as it is built
int cArr (int n, int k) {
if (n < k) return 0;
int * a, * b, * t, * s; // C++ wants this syntax to reference pointers to arrays
a = new int [n+1]; // size ping-pong arrays a and b
b = new int [n+1];
// r is row number
// i is column number in row
for (int r = 0; r <= n; r++) {
// ping-pong selection: a --> b or b --> a
if ((r%2) == 0) {s = b; t = a;}
else {s = a; t = b;}
t[0] = t[r] = 1; // init first and last element in row
// fill in rest of row
for (int c = 1; c < r; c++) t[c] = s[c] + s[c-1];
printm (t, r+1); // print the row
} // end for each row
cout << endl; // space after table
int value = t[k]; // get the target value in final row
delete [] a; delete [] b; // release the memory
return value; // return the target value
} // end cArr


// recursive approach
int combRec (int n, int k) {
if (n < k) return 0;
if (n == 0) return 1;
if (n == k) return 1;
if (k == 0) return 1;
return combRec(n-1, k-1) + combRec(n-1, k);
} // end function combRec


// factorial approach
int combFact (int n, int k) {
int den = 1, num = 1;
for (int i = n; i >= n-k+1; i--) num = num * i;
for (int i = 1; i <= k ; i++) den = den * i;
return num/den;
} // end function combFact


bool menu () {
int n, k;
cout << "n, k (n < 0 to quit): ";
cin >> n;
if (n < 0) return false;
cin >> k;
cout << "n, k: " << n << " " << k << endl;
cout << "Using Pascal's Triangle: " << cArr (n, k) << endl;
cout << "Using recusion : " << combRec (n, k) << endl;
cout << "Using factorials : " << combFact (n, k) << endl;
cout << endl;
return true;
} // end menu


int main()
{
while (menu());
} // end main
Respond
Forward
08/09/2013 10:48PM

Syntax of some popular languages

Note # 13
by Nick Duchon

A comparison of popular programming languages. The following is a great site to compare them:
http://www.tiobe.com/tpci.htm

The top languages currently are:

Let's compare some of their key features:

Langauge Compiled Keywords Operators
Arithmetic Logic Assignment Bit Other
Java Yes
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
+,-,*,/,%
++
--
&& - and
|| - or
?: - if/else

==
!=
>
>=
<
<=
=
+=
-=
/=
*=
%=
&=
^=
|=
<<=
>>=
>>>=
~
<<
>>
>>>
&
^
|
.
a()
(type)a
,
a[]
C Yes
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
as Java as Java as Java as Java a()
*a
&
->
(type)a
,
C++ Yes As C, plus:
and, bitand, and_eq, or, bitor, or_eq, xor, xor_eq, not, not_eq, compl
new, delete, sizeof, typeid
as Java as Java as Java as Java As C, plus:
.
::
->*
.*
VB No

AddHandler

AddressOf

Alias

And

AndAlso

As

Boolean

ByRef

Byte

ByVal

Call

Case

Catch

CBool

CByte

CChar

CDate

CDec

CDbl

Char

CInt

Class

CLng

CObj

Const

Continue

CSByte

CShort

CSng

CStr

CType

CUInt

CULng

CUShort

Date

Decimal

Declare

Default

Delegate

Dim

DirectCast

Do

Double

Each

Else

ElseIf

End

EndIf

Enum

Erase

Error

Event

Exit

False

Finally

For

Friend

Function

Get

GetType

Global

GoSub

GoTo

Handles

If

Implements

Imports

In

Inherits

Integer

Interface

Is

IsNot

Let

Lib

Like

Long

Loop

Me

Mod

Module

MustInherit

MustOverride

MyBase

MyClass

Namespace

Narrowing

New

Next

Not

Nothing

NotInheritable

NotOverridable

Object

Of

On

Operator

Option

Optional

Or

OrElse

Overloads

Overridable

Overrides

ParamArray

Partial

Private

Property

Protected

Public

RaiseEvent

ReadOnly

ReDim

REM

RemoveHandler

Resume

Return

SByte

Select

Set

Shadows

Shared

Short

Single

Static

Step

Stop

String

Structure

Sub

SyncLock

Then

Throw

To

True

Try

TryCast

TypeOf

Variant

Wend

UInteger

ULong

UShort

Using

When

While

Widening

With

WithEvents

WriteOnly

Xor

#Const

#Else

#ElseIf

#End

#If

+,-,*,/
^,mod
\ (int)
And
Not
Or
Xor
AndAlso
OrElse
IsFalse
IsTrue

<
<=
>
>=
=
<>
=
^=
*=
/=
\=
+=
-=
<<=
>>=
&=
<<
>>
Is
IsNot
Like
AddressOf
GetType
TypeOf

 

Respond
Forward
08/09/2013 10:48PM

Student class example

Note # 16
by Nick Duchon
#include < stdio.h>    // for printf
#include < iostream>   // for cin and cout
#include < string>     // C++ strings
using namespace std;

class Student {
public:
	string name;
	int grade1;
	int grade2;
	int grade3;
	double average;
}; // end class student

class MyArray {
public:
	Student * members;
	int max;
	double average;
}; // end class MyArray

void printSumSquares (MyArray ma) {
	double sum = 0;
	for (int i = 0; i < ma.max; i++)
		sum = sum + ma.members[i].average * ma.members[i].average;
	cout << "The sum of squares is: " << sum << endl;
} // end printSumSquares

void printAverage (MyArray ma) {
	double sum = 0;
	for (int i = 0; i < ma.max; i++) {
		sum = sum + ma.members[i].average;
	} // end for each student
	ma.average = 1.0 * sum / ma.max;
	cout << "The average is: " << ma.average << endl;
} // end printAverage

void printArray (MyArray ma) {
	cout << "Printing array, size: " << ma.max << endl;
	printf ("%10s  %5s %5s %5s %5s\n", "Name", "Gr 1", "Gr 2", "Gr 3", "Ave");
	for (int i = 0; i < ma.max; i++) {
		//cout << ma.members[i].name;
		printf ("%10s", ma.members[i].name.c_str());
		printf ("%5d ", ma.members[i].grade1);
		printf ("%5d ", ma.members[i].grade2);
		printf ("%5d ", ma.members[i].grade3);
		printf ("%8.2f", ma.members[i].average);
		cout << endl;
	} // complicated print
} // end printArray

MyArray makeArray () {
	MyArray ma;
	cin >> ma.max;
	ma.members = new Student [ma.max];
	for (int i = 0; i < ma.max; i++) {
		cin >> ma.members[i].name >> ma.members[i].grade1
		>> ma.members[i].grade2 >> ma.members[i].grade3;
		ma.members[i].average = (ma.members[i].grade1 + 
			ma.members[i].grade2 + ma.members[i].grade3)/3.0;
	} // end for each member
	return ma;
} // end makeArray

int main () {
	char x; 
	MyArray r; 
	while (true) {
		cout << "Enter [n,p,a,s,d,q]: ";
		cin >> x;
		switch (x) {
		case 'q':
		case 'Q':
			return 0;
		case 'n':
		case 'N':
			r = makeArray ();
			break;
		case 'p':
		case 'P':
			printArray (r);
			break;
		case 'a':
		case 'A':
			printAverage (r);
			break;
		case 's':
		case 'S':
			printSumSquares (r);
			break;
		} // end switch
	} // end while statement
} // end main