ics124 session 10 creating a c program from flowcharts & pseudocode 1
TRANSCRIPT
ICS124
Session 10
Creating a C program from Flowcharts & Pseudocode
1
By the end of this section, the student will be able to:
Appreciate the value of pseudocode as an interim step between flowcharts and a 3GL language
Translate a flowchart into psuedocode Describe the 5 steps of the compile process Use the compiler on Phobos to compile a simple program Recognize a preprocessor directive Incorporate the stdio.h header file into a program through the use of a
preprocessor directive Construct the "main" function of a C program Identify comments within a C program Write comments in a C program List the two symbols that define the beginning and ending of a block of code List the two components of a variable declaration Declare variables in a C program, and assign values to them List the two parts of a printf() function Use the printf() function to display text and values of variables List the two parts of the scanf() function Use the scanf() function to read integers and float variable types List the 6 relational operators Correctly use the relational operators in a C program Determine the numeric and logical result of a relational expression Translate psuedocode to C code
2
Flowcharting, review
ReviewFlowcharts are a means to plan when things are done in a program. They can be thought of as a 'roadmap' to the solution. The symbols we have seen are:
Does Something(I/O, Process)
Makes a decision(Based on some information: do I
perform this or that set of steps, do I continue to loop?)
The thread that holds the flowchart together
3
Pseudocode
4
Pseudocode
PseudocodePseudocode (pseudo = fake, code = computer language), a fake computer language (3GL)
Throughout these discussions we have been using the PDC to move from a high level, general analysis of a problem to a more specific solutionThe IPO Chart gave us a brief description of the inputs, the outputs and a list of processes for transforming the inputs into the outputsThe Flowchart gave us, diagrammatically, the sequence or order in which processes and decisions are made to solve the problem
Pseudocode is a hybrid between the structured computer languages (C, Pascal, BASIC...) and EnglishThe control structures we defined in Flowcharting are represented hereBecause pseudocode is not a real computer language and it has loose rules for implementation, it can be used to develop an algorithm for any structured computer languageFrom the pseudocode (after testing the algorithm) the program can be coded by translating the statements in pseudocode to statements in the programming language (C in our case).
5
Pseudocode
Pseudocode, continuedThere is no real standard for pseudocode, however it must have the following characteristics:
Statements are written in simple EnglishEach instruction is written on a separate lineKeywords and indentation are used to signify control structuresEach set of instructions is written from top to bottom, with only one entry point and one exit point
6
Pseudocode
Pseudocode, continuedAgain the three basic structures are represented:
simple sequencesimple decisioniteration
7
Pseudocode- Simple Sequence, continued
Simple sequence - Assigning Variables
This is where variables are manipulated within your algorithmThe New Webster's Computer Terms dictionary definition:
A variable is a symbolic name representing a value that changes during the program's execution
Back to Secondary School algebra, remember these?
5 = 5x + 4y0 = 5(x + y) - 3x + 5
Solve for x and y.
x and y are the variables.
8
Pseudocode- Simple Sequence, continued
Simple sequence - Assigning Variables, continued
When creating a name for a variable, make it meaningfulDon't make it too long (you will end up with writer's ramp now and carpal tunnel syndrome later)
custName may be not as meaningful ascustomers_first_and_last_name but it is easier to write and probably conveys enough information about how the variable is being used. The other extreme cn is obviously meaningless.
Use your judgement. Ask yourself: If I had to re-read this in another year, would the variable name be meaningful?
9
Pseudocode- Simple Sequence, continued
Simple sequence - Assigning Variables, continued
There are two types of variable assignments:When you are initializing a variableAs a result of some processing
It will be considered BAD FORM not to initialize a variable before using it
Verbs used: INITIALIZESET
INITIALIZE counters to zeroSET recordSize to 500
10
Pseudocode- Simple Sequence, continued
Simple sequence - Assigning Variables, continued
As a result of processing:
Expect to use the symbol "="
totalPrice = basePrice + salesTax
You can use this form for initializing variables as well
counterA = 0counterB = 0recordSize = 500
11
Pseudocode- Simple Sequence, continued
Simple sequence - Assigning Variables, continued
Flowchart to Pseudocode:
counterA = 0
SET recordSize to 500
counterA = 0
SET recordSizeto 500
12
Pseudocode- Simple Sequence, continued
Simple sequence - Input of Data
Verbs used: READGET
READ usually refers to data being read from a file
GET usually refers to data being entered by the user at a keyboard
READ address FROM customerFileGET newAddress
13
Pseudocode- Simple Sequence, continued
Simple sequence - Input of Data, continued
Flowchart to Pseudocode
READ address FROM customerFile
GET newAddress
Read addressFROM
customerFile
Get newAddress
14
Pseudocode- Simple Sequence, continued
Simple sequence - Output of Data
Verbs used: PRINTWRITEOUTPUTDISPLAY
PRINT usually refers to data being sent to a printer
WRITE usually refers to data being sent to a file
OUTPUT and DISPLAY usually refer to data being sent to a monitor.
15
Pseudocode- Simple Sequence, continued
Simple sequence - Output of Data, continued
Example:PRINT "Program Completed"WRITE newAddress TO customerFileOUTPUT name, address, postalCodeDISPLAY "End of Data Reached"
Note that any phrase that is to be output EXACTLY as written is enclosed in quotes
this helps to differentiate between a literal string and a variable name.
16
Pseudocode- Simple Sequence, continued
Simple sequence - Output of Data, continued
Flowchart to Pseudocode
WRITE address TO customerFile
DISPLAY newAddress
Write addressTO
customerFile
Display newAddress
17
Pseudocode- Simple Sequence, continued
Simple sequence - Computation
Some verbs used: ADDCOMPUTECALCULATEMULTIPLYDIVIDESUBTRACT
ADD 1 TO counterCOMPUTE tax = price x 0.15degreesC = (degreesF - 32) x (5/9)
18
Pseudocode- Simple Sequence, continued
Simple sequence - Computation, continued
Flowchart to Pseudocode
ADD 1 TO counter
degreesC = (degreesF - 32) x (5/9)
Add 1 to counter
degreesC =(degreesF - 32)
x (5/9)
19
Pseudocode- Selection
Simple Selection
The basic form looks like:
IF condition THENstatement(s)
ELSEstatement(s)
ENDIF
If the condition is TRUE, then the statements immediately following the THEN keyword are executed, until the ELSE clause. At which point the program resumes after the ENDIF keywordIf the condition is FALSE, then the statements immediately following the ELSE keyword are executedNote the indentation that is being used
Makes it easier to see the components of the selectionProvides for readability
20
Pseudocode- Selection, continued
Simple Selection, continued
Flowchart to Pseudocode
IF a > b THENc = e + f
ELSEc = t x q
ENDIFa > b c = e + f
c = t x q
TRUE
FALSE
21
Pseudocode- Selection, continued
Simple Selection, continued
Flowchart to Pseudocode:
IF condition THENstatementAstatementBstatementC
ELSEstatementDstatementE
ENDIF
If condition StatementAStatementDTRUEFALSE
StatementB
StatementC
StatementE
22
Pseudocode- Selection, continued
Simple Selection, continued
An example of no indentation: with indentation:
IF a = b THEN IF a = b THENDISPLAY "A equals B" DISPLAY "A equals B"c = (23 - d) / 2 c = (23 - d) / 2lifeUniverseEverything = 42 lifeUniverseEverything = 42ELSE ELSEDISPLAY "A does not equal B" DISPLAY "A does not equal B"vogons = 1 vogons = 1earth = 0 earth = 0ENDIF ENDIF
23
Pseudocode- Selection, continued
Simple Selection, continued
What if you don't need an ELSE clause?
IF avg < 50 THENDISPLAY "Low average"
END IF
avg < 50DISPLAY
"Low Average"TRUE
FALSE
24
Pseudocode- Iteration
Iteration: Pre-test loop
The basic form looks like:
DOWHILE conditionstatement(s)
ENDWHILE
25
Pseudocode- Iteration, continued
Iteration: Pre-test loop, continued
Flowchart to Pseudocode:
DOWHILE i < 10b = b x c;i = i + 1
ENDWHILE
b = b x c
False
True
i < 10
i = i + 1
26
Pseudocode, continued
Exercise Convert the following flowchart into pseudocode
hi = 101 resp != 'C'
27
Start
lo = 1
DISPLAY"Choose a number"
DISPLAY"I Guess", guess,
"is it Hi, Lo or Correct?"
resp = 'N'
guess =(hi + lo) / 2
GET resp
resp = 'L'
resp = 'H'
hi = guess
lo = guess
A
A
B
B
C
C
Stop
DISPLAY"I found your number",
guess
TRUE
TRUE
TRUEFALSE
FALSE
FALSE
The C Language
A C ProgramA Program, and its flowchart that does nothing:
int main(void){ ;}
The Language C is case-sensitivecase-sensitive. If you use a lower-case character instead of an upper-case character, the compiler will treat the two words DIFFERENTLY!
I will use both flowcharts and pseudocode to define the C language.
Start
Stop
29
The C Language, continued
C Program structureWhat about the structure of that useless program?
{};
A block of statements that are to be executed together are surrounded by the { and } characters.
For example: All the statements and structures in an IF-THEN-ELSE. All the statements and structures in a DOWHILE.
The semi-colon (;) is used to show the end of a statement.
A semi-colon by itself is a statement that does nothing. Not much use, nor very interesting
30
The C Language, continued
C Program structure, continuedIn the C language (as in most languages) there is a means to imbed comments. Comments are a form of documentation and are a way to leaves notes to yourself or other programmers as to what is happening in your program.
All comments begin with '/*' and end with '*/'
/* this is a comment */
/* this is also a comment */
/***************************************\* ** Is this a comment ? ** *\***************************************/
31
The C Language, continued
C Program structure, continuedHere is another program that is perhaps a little more interesting:
#include <stdio.h>int main(void){ printf("A program is born.\n");}
What is that #include <stdio.h>, and what about that printf()
Recall the compile process...
Start
Display "Aprogram is
born."”
Stop
32
The C Language, continued
C Program structure, continued
That #include <stdio.h> is a preprocessor directive
It tells the compiler that there is a file called stdio.h that contains additional information that needs to be INCLUDED in your program.
header files have an extension of .hsource code files have an extension of .c
Source file
Library files (for O/S)
Object filePreprocessor and translator
Executable file
Linker
33
The C Language, continued
PreprocessorAnatomy of the "include" preprocessor directive:
#include <stdio.h>
These angle brackets tell the preprocessor to look in the system library directory This preprocessor directive is used to include other files into your file
All preprocessor directives begin with a '#'
When you write your own header files, you will use the " and " characters around the filename.
stdio.h is the Standard-Input-Output library file. It is THE most common header file.
34
The C Language, continued
printf() statementNow about the printf() statement:
This is the equivalent of the DISPLAY statement in pseudocode.
Whatever formatted data is output by the printf() statement is sent to the standard output device of the computer - in our case the monitor.
35
The C Language, continued
printf() statement, continuedAnatomy of a simple printf() statement:
printf("A program is born.\n");
An "escape sequence" that is used to tell the computer you want to go to a NEWLINE
The beginning of a string of data to be printed EXACTLY as written
The library function being called
36
The C Language, continued
printf() statement, continuedAnother, slightly more interesting program:
#include <stdio.h>int main(void){ printf("A program is born.\n"); printf("\nOh, sure you think it's cute and cuddly now\n"); printf("but just wait!\nAs it grows up it will become a "); printf("monster before you know it!\n");}
What is the output of this program?
37
The C Language, continued
VariablesWe talked briefly about variables when discussing flowcharts and pseudocode. When using variables in C, there are rules that are followed.
When defining a variable to be used by the program, there are two parts: data type variable name
39
The C Language, continued
Variables, data typesWe listed the data types for C in an early class when discussing data representation. Here they are again, with their typical sizes:
char 0 ... 255 (the numbers are usually used to represent ASCII or EBCDIC characters)
short int -32,768 ... 32,767int -2,147,483,648 ... 2,147,483,647long int -9,223,372,036,854,775,808 ... 9,223,372,036,854,775,807float 0.11754943508222875x10-39 ... 0.34028234663852886x10+39
double 0.2225073858507201x10-309 ... 0.17976931348623158x10+309
Any of the integer data types cannot store fractional information. To assign the calculation "5/2" to an integer would result in '2' being stored, not '2.5'.
40
The C Language, continued
Variables, namingHere are some rules for picking variable names:
first character must be an alphabetic character (a-z A-Z) or an underscore (_)Must contain ONLY alphabetic characters, digits (0 - 9) and the underscoreOnly the first 31 characters are significant- the compiler only looks at the first 31 characters and ignores the rest
abcdefghijklmnopqrstuvwxyz01234467890 abcdefghijklmnopqrstuvwxyz01234567890 Are considered the same
variableCannot be the same as a 'reserved' word - those words that are known to the compiler (like "if" or "while")
41
The C Language, continued
Variables, declaring Variables are declared at the beginning of the main() function (after the first
'{')
To declare a variable, the format is:
dataType variable1 [=value] [,variable2 [=value]]... ;
For example:
int counter;
int counter, classCount, courseCount;
int x = 0;
int x = 1, y = 2, z = 3;
42
The C Language, continued
printf() funtion revisitedNow that we have defined variables in our C program, how do we display their contents?
There are two parts to the printf() function: The format string, which contains:
literal text to be output exactly as written
special control characters (such as the \n)
field specifications
A list of variables that correspond the field specifications in the format string
The format string is like a template, showing you where the text is (and what the text is) as well as where within the text the values of the variables are to be inserted
43
The C Language, continued
printf() funtion revisited
printf("Total = %d Average = %f\n", ttl, avg);
The field specifications are "place holders" for the variable data that the program is calculating
Where-ever you place a field specification, the compiler will look for a corresponding variable in the list of variables
The first field specification refers to the first variable in the list, the second field specification refers the second variable in the list and so on...
44
The C Language, continued
printf() funtion revisitedThe field specifications that correspond to the data types we will use in this course:
%c - char
%d - int (probably used 'd' for decimal or digits)
%f - float (by default 6 digits are shown to right of the decimal point)
45
The C Language, continued
Mathematical operatorsThe following symbols are used for mathematical operations in the C language:
+ Addition
- Subtraction
* Multiplication
/ Division
%Modulo
= Assignment
46
The C Language, continued
PracticeConvert the following flowchart into C:
Start
num = 5
num2 = 5
num3 =num x num2
Display "the productof ", num, "and”,num2, "is”, num3
Stop
47
The C Language, continued
PracticeWhat would the print statement required to get this output:
Hi H0, H1 Ho, its off to work I go (at $1.500000 per day)
assuming the following C statements precede your printf() function
char dwarf;int valueA;int valueB;float wage;
dwarf = 'H' /* to be used in the 'Hi' and 'H1' words only */valueA = 0; /* hint: the second word needs this */valueB = 1; /* to be used in the third word */wage = 1.5;
49
The C Language, continued
ExampleDevelop a program to take three numbers, add them together, then print their total and average (the numbers are 10, 20 and 40, and are initialized within the program).
51
The C Language, continued
scanf() statementA computer program is fairly limited if it cannot get input data from a user as it is executing
There exists a function that is very similar to the printf() function that is used for formatted input
Anatomy of the scanf() statement:
scanf("format string", v1, v2, ...);
A list of variables that are referenced in theformat string. Each variable of type char, int or float is proceeded by a '&' character
A list of field specifications for the data being read
The function being called
53
The C Language, continued
scanf() statement, continued
There is one major difference with the scanf() function when dealing with the variables:
scanf("%d", &i);
Notice the "&" symbol before the variable name
This is called the "address-of" operator
For now, it means that when you place the value read from the user into the variable, you can only store the data if you know the address of the variable within the computer's memory
54
The C Language, continued
scanf() statement, continued
Due to the way that the scanf() function operates, include the following statements after every scanf() statement:
fflush(stdin);
This will tell the operating system to flush any characters that are in the input queue.
55
The C Language, continued
Relational operatorsA decision structure within a programming language is fairly useless without a means to compare two or more variables
There are only a few types of Relational Operators
When a relation is expressed in C, the result is either TRUE or FALSE
A relation is also referred to as an Expression
These Expressions can be used in the decision structure- specifically the IF-THEN-ELSE and DOWHILE that we have seen in pseudocode
In C any non-zero value is considered TRUE, zero is considered FALSE
56
The C Language, continued
Relational operators, continuedThe Relational Operators are:
Equal == (NOT "=" by itself)
Not Equal != (NOT "!==")
Less than <
Greater than >
Less than or equal <=
Greater than or equal >=
57
The C Language, continued
Relational operators, continuedExample Expressions based on a relation:
a < b5 > t7 < 0(a + b) > (g - f)
When evaluating expressions that contain relational operators, a TRUE condition is represented by the value 1, a FALSE condition is represented by the value 0
For example:
The expression (7 > 8) would be represented by 0
The expression (7 < 8) would be represented by 1
58
The C Language, continued
Relational operators, continuedWhat is the result of these expressions, and are they TRUE or FALSE?
7 - 2
5 < 3
i = 25
i = 0
((5 >= 3) + 2) < 3
59
The C Language, continued
Relational operators, continuedWe have, in some of our examples, used such words as AND and OR when writing the condition in a Decision Box (for Selection as well as Iteration)
These are referred to as Logical Operators or Boolean operators
In C the AND logical operator is represented by &&In C the OR logical operator is represented by || (two vertical bars)In C the NOT logical operator is represented by !
Example:
PseudocodeIF a > b AND c < d OR g = k THEN
C
if (a > b && c < d || g == k)...
61
Selection
62
The C Language, continued
SelectionFlowcharts and Pseudocode:
expressionDo true
stmt
Do falsestmt
T
F
IF expression THEN true statementELSE false statementENDIF
63
Selection
A couple of things to note: There is no THEN keyword The expression is enclosed in parenthesis There is no ENDIF keyword Only ONE statement is associated with each part of the IF statement
The C Language, continued
IF expression THEN true statementELSE false statementENDIF
if (expression) trueStatement;else falseStatement;
64
Selection, continuedIn the previous example there was only one statement in each the true branch and one statement in the false branch
How do you create a block of statements in C?
The C Language, continued
65
Selection, continuedHow do you create a block of statements in C?
Use the { and } symbols:
if (expression){ statement1; statement2; statement3;}else{ statement4; statement5;}
Note that there is NO semicolon after the closing brace }
The C Language, continued
66
Selection, continuedAs in pseudocode and flowcharts, the ELSE clause can be omitted:
if (expression) IF expression THEN statement1; statement1 ENDIF
if (expression) IF expression THEN{ statement2 statement2; statement3 statement3; statement4 statement4; ENDIF}
The C Language, continued
67
Selection, continuedAs you might surmise, it may be confusing when reading code that might contain braces for multiple statements or no braces for a single statement:
if (a > b) printf("a is greater than b\n"); if (a > c) printf("a is also greater than c\n");else printf("a is less than or equal to b\n");
Athough it looks OK, in reality it is nothing more than a badly indented version of:
if (a > b) printf("a is greater than b\n");
if (a > c) printf("a is also greater than c\n");else printf("a is less than or equal to b\n");
Be on the lookout for this pitfall- what is the correct code?
The C Language, continued
68
Selection, continued
if (a > b) printf("a is greater than b\n”); if (a > c) printf("a is also greater than c\n”);else printf("a is less than or equal to b\n”);
Should be:
if (a > b){ printf("a is greater than b\n”); if (a > c) printf("a is also greater than c\n”);}else printf("a is less than or equal to b\n”);
The C Language, continued
69
Iteration
70
Iteration
We discussed loops previously: pre-test loops
The C Language, continued
71
Iteration, continued
Flowcharts and Pseudocode:
The C Language, continued
DOWHILE expression repeated expression update statementENDWHILE
expression
repeatedexpression
updatestatement
True
False
72
Iteration, continued
A couple of things to note: The expression is enclosed in parenthesis, just like the if There is no ENDWHILE keyword Only ONE statement is associated with the loop, just like the if
The C Language, continued
DOWHILE expression repeated expressionENDWHILE
while (expression) repeatedExpression;
73
Iteration, continuedHow do you create a block of statements in C?
Use the { and } symbols:
while (expression){ statement1; statement2; statement3;}
The C Language, continued
74
Iteration, continuedA comparative example, pseudocode versus C:
The C Language, continued
SET i = 0WHILE i <= 10 DISPLAY "i = ", i i = i + 1ENDWHILE
DISPLAY "Done Count"”
#include <stdio.h>int main (void){ int i;
i = 0; while (i <= 10) { printf("i = %d\n", i); i = i + 1; } printf("Done Count\n");}
75
Exercise
Write a C program that will prompt the user for three pieces of data. The program will add them together and print the result. The prompts and output formats are your choice. After the result has been printed, ask the user for another set of three numbers. Keep repeating until the user enters zero for all three numbers.
The C Language, continued
76