Introduction to Programming

X52.9239-003

Dr. Jean-Claude Franchitti

New York University

School of Continuing Education

 

Session 10 Class Notes

 

 

Goals and Topics:

Review from Previous Class

Structured design, structure charts, data flow diagrams, and data dictionary, files in C, the tabout.c program, databases, SQL, C functions, function arguments, and return types.

Course Review

  1. Computer architecture, bits and bytes, binary numbers
  2. Program execution, the CPU, machine language instructions
  3. Operating systems and utilities, C language edit/compile/link cycle
  4. Algorithms and DOS/Windows basics, flowcharts, branching and looping
  5. Programming languages, variables, data, and expressions
  6. Software engineering, testing and debugging, math operations in C
  7. C language lab, the Borland compiler, for and while statements, if - else and switch
  8. Data structures and arrays, array index
  9. Structured program design, files, and databases
  10. Case study, new technologies, next steps

Questions

Q. What is the "+" used for in the fopen mode "ab+"?

A. The "+" lets you read and write the file. Without the "+" you could only write to the file by appending onto the end of the file.

Case study: the Automatic Teller Machine

You get called into your boss' office early one morning.

"Good news" she says, "We got the ATM job. I need you to drop everything you are working on, and take over the project to develop the software for their new machine. There is a meeting in one hour to discuss their requirements. I'm counting on you, good luck."

Requirements Specification

In the meeting with clients you review the project requirements. You need to defined these issues in the specification:

System Architecture

Client/server

Central server processor

Network interface

Request protocol

Target platform - hardware, ROM disk

Number of clients connected to server

Hardware Interfaces

Receipt printer interface

Video display interface

Keypad interface

Card reader interface

Money dispenser interface

Application Design

Audit log

Transaction rollback

Configuration file to read on startup - contents, greetings, colors

Test routines, test modes

Unjam code

Time and date stamping

Turn machine on/off

Encryption of network traffic

Remote shutdown of machine

Remote status tally of machine from server

Gather statistics about machine usage?

User Interface Design

Main menu

Withdraw funds or balance inquiry

English/Spanish, other languages?

Display advertisements

Network down prompt

Out of cash prompt

Overall process, entry of PIN number

Overall process, addition of individual balance

20's, 10's, others

Limits on withdrawal per day

Print, display, both, balance

Transfer between accounts

Accept deposits? NO

Time out if money dispenser jams

Time out if customer fails to complete sequence

Screen colors

Touch screen

Screen layout

Project Management

Project management - project team

Project schedule

Alpha test, beta test, acceptance test, system integration test

Test plan

Prototype user interface

Try with naïve users (to test interface)

Test boundary conditions

Any others?

Project Stakeholders

In developing the specification and program design, we need to consider who the customers of the ATM machine will be. Beyond that, we need to analyze who are the stakeholders in the project. Who has an interest in the ATM machine, and how it works?

Bank customers, bank managers, bank tellers

Person who loads money into the machine

New York City - security issues, rules

Bank telecommunications department

People trying to steal money from the machine

FDIC, banking regulators

National and international protocol/standard agencies

Program Structure Chart

 

Flowchart of Operations

This flowchart shows the sequence of program operations for an ATM machine limited to two types of transactions: check balance and get cash:

Modular Top-Down Design

Here we determine the layout of the functions required to complete the processing, and the general layout of the program using pseudocode.

main waiting loop

display_welcome_prompt ( )

enter_account ( )

validate_account ( )

enter_pin ( )

validate_pin ( )

enter_transaction ( )

check account balance

get_cash ( )

validate account balance

validate machine balance

debit account

issue cash

Data Design and Data Structures

The data design depends to a large extent on the size and complexity of the program. For a real ATM client, we would be making requests over a computer network to a centralized account database at the bank.

To simplify processing for this program, data for account numbers, pin numbers, and account balances will be stored in arrays. Also, we will restrict account numbers and pin numbers to integer data, even though it may be better handle these numbers as string data.

The array data will be referenced based on using the same index in each array. For example, customer index zero would have an account number of 1000, a PIN number of 1234, and a balance of $500.00.

Account numbers: int account[8]

1000

2000

3000

4000

5000

6000

7000

8000

PIN numbers: int pint[8]

1234

2345

3456

4567

5678

6789

7890

8901

Account balances: float balance[8]

500.00

500.00

500.00

500.00

500.00

500.00

500.00

500.00

Machine balance: float machBalance 10000.00

Write the Code

Here are some highlights from the program.

 

/**************************************************************

* file name: atm.c

***************************************************************/

#include <stdio.h> /* standard I/O info */

#include <conio.h> /* for clrscr ( ) */

#include <stdlib.h> /* for exit ( ) */

/* ---- constant definitions ---- */

#define SIZE 8 /* size of arrays, number of accounts */

#define WELCOME_PROMPT_1 "Welcome to Megabank"

#define GOODBYE_PROMPT_1 "Thank you for using Megabank"

#define NOT_FOUND -1 /* error value from array search */

#define FOREVER 1 /* for _while_ loop */

/* ---- function prototypes ---- */

void display_account_balance (int account);

void display_diagnostic (void);

void display_goodbye_prompt (void);

void display_welcome_prompt (void);

void get_cash (int account);

int enter_account (void);

int enter_pin (void);

int enter_transaction (void);

int find_account_index (int account, int size);

void issue_cash (float amount);

void pause (void);

int validate_account (int account);

int validate_pin (int pin, int account);

/* ---- global variables ---- */

/* account [ ] is an integer array of valid account numbers */

int account [SIZE] = { 1000, 2000, 3000, 4000,

5000, 6000, 7000, 8000 };

/* pin [ ] is an integer array of PIN numbers for the respective accounts */

int pin [SIZE] = { 1234, 2345, 3456, 4567,

5678, 6789, 7890, 8901};

/* balance [ ] is a float array with the starting balance for each account */

float balance [SIZE] = { 500.00, 500.00, 500.00, 500.00,

500.00, 500.00, 500.00, 500.00 };

/* machineBalance is a float variable which gives the current amount */

/* of cash left in the machine */

/* ---- function definitions ---- */

int main (void)

{

….

}

Main program loop

while (FOREVER)

{

accountNumber = enter_account ( );

accountIndex = validate_account(accountNumber);

if (accountIndex != NOT_FOUND)

{ /* we have a valid account number */

pin = enter_pin ( ); /* get a pin number */

if (validate_pin (pin, accountIndex) == 1)

{

transaction = enter_transation ( );

while (transaction != 3)

{

switch (transaction)

{

case 1: /* display balance */

display_account_balance(accountIndex);

break;

case 2:

get_cash (accountIndex);

break;

}

transaction = enter_transaction ( );

}

display_goodbye_prompt ( );

}

}

}

Find account index

/* ------------------------------------------------------

* Find the index of an account number. If not found,

* return NOT_FOUND

* ------------------------------------------------------ */

int find_account_index(int acct, int size)

{

int i;

int foundIt = 0;

for ( i = 0; i < size; i++)

if (account[i] == acct)

{

foundIt = 1; /* found the account number */

break; /* break out of _for _ loop */

}

if (foundIT == 0)

i = NOT_FOUND;

return(i);

}

Password validation

/* ---------------------------------------------------------

* Validates the pin number for a given account. If the

* pin number matches the number in the pin [ ] array for

* this account index, then return a one, otherwise, return

* a zero.

* ---------------------------------------------------------*/

int validate_pin (int pinNo, int index)

{

int result; /* result of validation */

if (pinNo == pin[Index])

result = 1; /* pin number correct */

else result = 0; /* pin number incorrect */

return(result);

}

Withdrawal logic

/* ---------------------------------------------------------

* Get cash for withdrawal from the account.

* Prompt for an amount to withdraw, and allow the

* withdrawal if the amount is <= the account balance, and

* if the amount is <= the machine balance.

* ---------------------------------------------------------*/

void get_cash(int index)

{

float withdrawal; /* amount to withdraw */

printf("Please enter the amount to withdraw: ");

scanf("%f", &withdrawal);

if (withdrawal <= machineBalance &&

withdrawal <= balance[index])

{

/*

* sufficient funds to allow withdrawal.

*/

balance[index] = balance[index] - withdrawal;

machineBalance = machineBalance - withdrawal;

printf("Here is $%.2f\n", withdrawal);

}

/* give reason for not dispensing cash */

else if (withdrawal > balance[index])

{

printf("Unable to process request, "

"insufficient funds in your account.\n");

printf("You have $%.2f available for withdrawal.\n",

balance[index]);

}

else

{

printf("Insufficient cash in this machine to "

"process your request.\n");

printf("Only $%.2f available in this machine\n",

machineBalance);

}

return;

}

Object Oriented Design

Object Oriented Design (OOD) and Object Oriented Programming (OOP) is currently the favored design methodology for large programs.

Objects extend the concept of structured data types from procedural language to include subprograms within a self-contained module called an abstract data type. The abstract data type contains data and the functions which act on that data. The abstract data type provides encapsulation of the data and procedures, and information hiding, to protect the data from other modules.

In functions, we use local variables for data hiding. In C++ the data may be private (local) or public (global).

Abstract data types are called classes in C++, which are an extension of the structured data types in the C language. The functions contained within a class are called methods.

The reason companies are interested in OOP with C++ and other languages (Smalltalk) is for improved efficiency of program development. After the conversion from procedural programming to object oriented programming (over several projects), companies have achieved 30 to 40 percent improvement in programming development.

This improvement comes from these advantages of OOP:

Generation of reusable code and data

Code is easier to maintain

More portability across platforms

Object oriented language have the ability to derive new classes from existing classes, using inheritance. From a generic class object which models data and actions, you can inherit these characteristics into a new class which has some new characteristics you add.

C++ Language

The most popular object oriented language is C++. This language was developed as a superset of the C language, starting in 1980. A superset means that C++ has all the features of the C language, plus some additional capabilities to handle objects. The C language has thirty two reserved words (like for, while, and int). C++ adds sixteen more keywords to improve on the features of C, and add new features.

One new reserved word in C++ is class, which allows you to declare a structured data type variable, with its own set of self-contained functions. In a class, the functions are directly associated with their data. This is the mechanism C++ uses to create self-contained objects.

Here is a C++ program which uses stream input/output and the new C++ comment. In programming terms, a stream is an idealized continuous flow of characters into or out of the program. In C++, we can refer to the standard input of the program (usually the keyboard) with the term cin, and the standard output (usually the display) with the term cout. These terms, plus the stream insertion operator << and the stream extraction operator >> make it very easy to do input/output in C++ (without using printf and scanf).

C Language

#include <stdio.h> /* for standard input/output */

/* This program prompts the user for a number,

prints that number,

and its square */

main ( )

{

int val; /* comment */

printf ("Enter a number: ");

scanf ("%d", &val);

printf ("You entered the number %d.\n", val);

printf ("%d squared is %d.\n", val, val * val);

}

Program output

Enter a number: 5

You entered the number 5.

5 squared is 25.

C++ Version

#include <iostream.h> /* for stream input/output */

// This program prompts the user for a number,

// prints that number,

// and its square

int main (void)

{

int val; // comment

cout << "Enter a number: ";

cin >> val;

cout << "You entered the number " << val << ".\n";

cout << val << " squared is " << val * val;

return (0);

}

Program output

Enter a number: 5

You entered the number 5.

5 squared is 25

Notice these improvements in the C++ version of the program:

The single line comment // is quicker and safer to write.

We did not have to use conversion specifiers, or use the & operator in the input statement

cin << val;

We did not have to identify the data type and use conversion specifiers in the output

statement

cout << "You entered the number " << val;

Java Language

Java is an object oriented programming language derived from C++. Originally designed for embedded control applications, Java is now finding wide popularity as a language for developing applications for the World Wide Web.

Here are some of the characteristics of Java

Object oriented

Simpler and safer than C or C++ (no pointers)

Generate intermediate byte code for cross platform portability

Interpret on target machine

Designed to work over a network: secure, easily downloadable.

Here is an example of a short program in Java, the classic "hello world" program.

Class HelloWorld

{

static public void main (String args [ ])

{

System.out.println("Hello world!");

}

}

This should look somewhat familiar to what we did with functions in C. A class is a function-like object from C++ which has self-contained data and operations called methods which change the data or perform actions.

Here the method main calls the println method to send the next "Hello world" to the out object.

As compared to C and C++, the Java language does not have these features

Preprocessor actions like #define or #include, no header files

Structured data types - use class instead

Functions - use class and method instead

Goto statements - use more advanced break statement

Automatic conversion of data types - must use cast

Pointers - manages memory automatically

Visual Programming

Visual programming uses a drag and drop interface to rapidly design sophisticated windows programs. Visual programming techniques are used in Rapid Application Development (RAD), where a good deal of the program can be developed using existing objects of the visual programming environment, with a small amount of the program written as actual application code.

Some elements of a visual programming environment are:

Some examples of visual programming environments are Visual Basic, Visual C++, Delphi, and PowerBuilder.

Obtaining Grade Report

To receive your grade report, call the TorchTone voice response system at (212) 995-4723. You will be asked to enter your studentID (Social Security Number) and a PIN of the date of birth shown on your registration form as MMDDYY. On request through TorchTone, your grades will be mailed to you. For more information, look up TorchTone in the SCE Bulletin index.

X52-9232, C Part 1

C, Part I is a C language syntax course. It offers complete coverage of the C language in twelve classes. There are multiple sections of C Programming, Part I. Of these different sections, the last is a continuation of this class. Typical Syllabus for X52-9232, C Part I:

  1. The C environment, characteristics of the C language. Compiling C in DOS and UNIX.
  2. Data types and data ranges.
  3. Operators, expressions, statements, loops.
  4. Branching statements, the conditional operator, character I/O.
  5. Functions and memory, call by value, call by reference.
  6. Advanced functions, recursion, introduction to pointers.
  7. Arrays, multidimensional arrays.
  8. Pointers, the address operator, the indirection operator, pointer mathematics, arrays and pointers.
  9. String and character operations, string library functions, command line arguments.
  10. File input/output, variable storage class, program development.
  11. Structures, the structure pointer operator, bitwise operators.
  12. The preprocessor, the C library, advanced data representation, linked lists.

Text: New C Primer Plus, Second Edition, Waite, Mitchell, and Prata, Stephen, SAMS Publishing, 1993. ISBN 0-672-30339-6

New York Personal Computer Club (NYPC)

NYPC is a large computer club which holds monthly meeting related to software for PCs. In addition to the main meeting, there are numerous Special Interest Groups (SIGs) in individual topics, such as programming languages, or applications. Attending these meetings is a good way to keep up with PC programming and hear about new software developments.

Thanks and Good Luck

Thanks for all your hard work and attention during the course, and good luck with your future programming activities.