You are on page 1of 104

ACS 168

Structured Problem
Solving
Using the Computer

by
Lynne Koenecke
In tro d u c t i o n t o M i c ro c om p ute r s

Components of a Computer
Hardware components of a Computer

Central
Processing
Unit

Input Output

Main Memory
(Primary Storage)
RAM

Secondary
Storage
Input -
Keyboard, Scanner, Mouse, Light Pen, Digitizing Tablet

Output -
Monitor, Laser Printer, Dot-matrix Printer, Ink Jet Printer, Plotter,
Sound

Secondary Storage -
Floppy Disk, CD-ROM, Hard Disk, Magnetic Tape

Central Processing Unit (CPU)


Performs the Actual processing of information stored in memory. The
part of a computer that controls all the other parts. The CPU fetches
instructions from memory and decodes them.

Main Memory
Random Access Memory - volatile memory that holds instructions to
be processed by the CPU and data ready to be used. All types of
information are stored in main memory.
• Data and instructions are stored sequentially.
• Each memory cell has a unique address associated with it.
• The information stored in a memory location is called its
contents.
• Every memory cell always contains some information.
Address Contents
0 -27.2
1 354
2 0.005
3 -785
4 H
. .
. .
98 OH
99 65.78

Lynne Koenecke 3
Illinois State University, ACS
Software

System Software - controls the execution of other programs


interacting with the computer.
Examples:
• command line interpreter
• window system
• assemblers
• compilers
• linkers
• interpreters

Application Software - complete program that performs a specific


function or functions for a user.
Examples of Packaged (off the shelf) Software:
•Microsoft Word
•Lotus 123
•Adobe Photoshop
•Quicken
•CAD
•Eudora
•Netscape

Application software is also custom written for the user. In this class
you will be writing customized software application programs in C.
Software includes both source code written by humans and executable
machine code produced by assemblers or compilers.

Lynne Koenecke 4
Illinois State University, ACS
P ro g r amm in g L a n g u a g e s

Machine Language
The "native tongue" of a particular kind of computer. Written in binary
numbers (0s and 1s).
0010 0000 0000 0100
0100 0000 0000 0101
0011 0000 0000 0110

Assembly Language
Uses descriptive names to reference data.
LOAD value
ADD delta
STORE value
The result of assembly instructions is Machine Language.

High-Level Language
• Easier to understand
• Portable - can be used on many different types of computers
with few modifications.
• Allow programmers to write instructions with statements that
resemble English.

Examples of High Level Programming Languages


BASIC, COBOL, Fortran, C, Ada, Lisp, PL/I

High level programs are coded into machine language by compilers.


The programming statements (called source code) are checked and
processed by a compiler and then coded into 0s and 1s.

Lynne Koenecke 5
Illinois State University, ACS
P ro c e s s in g a H i g h -L e v e l L a n g u a g e P ro g r am
Programmer enters high-level
programming statements into and
editor and saves it as a source file.

Source file Revised


on disk Source
File

Compiler attempts to
translate the program Programmer corrects syntax errors
Failure
Success List of errors

New
Object
File Other
Object
Files

Linker links the new object


file ith other object files

Load
file

Loader places the


load file into memory

Executable program
in memory

Lynne Koenecke 6
Illinois State University, ACS
Source Preprocessed Object Executable
Code Source Code Code Code

Editor Preprocessor Compiler Linker

External
Items
E r ro r s i n P ro g r amm in g

Programs rarely run correctly the first time they are compiled.
Programming errors are known as “bugs”. The process of correcting
errors in programs is called debugging a program.

Types of Errors
Syntax Errors
They are also called compilation errors. Syntax errors are detected by
the compiler as it tries to translate the program statement. Syntax
errors are the result of incorrect usage of the programming language's
rules of syntax.

Run-time Errors
Run-time errors are detected by the computer as a program is
executing. These errors stop the execution of the program and an error
message is displayed.

Logic Errors
Logic errors become evident in programs that are syntactically correct
and do not have run-time errors, yet the program produces an incorrect
answer. It is very important that you test your program with hand
calculated answers to be sure that your program works as intended.

Lynne Koenecke 7
Illinois State University, ACS
H o w P ro g r am s R e c e i v e In p u t

Interactive and Batch Input


As programs execute, they usually receive some kind of input data to
process. The program can receive data in two modes, interactive and
batch.

Interactive mode - the user interacts with the program by using an


input device to enter data into the computer while the program is
running. Programs designed for interactive mode display messages
called prompts on the screen to tell the user what data is needed at a
particular point in the program.

Batch mode - all of the data provided to the program is gathered in


advance. The user does not interact with a program written for batch
mode. A data file is prepared before the program is executed.

D a t a vs . In f o rm a t i o n
Data - raw facts given to a computer during the input operation
which is used to process information.

Information - Data that has been processed into a form that has
meaning and is useful.

3 pieces of data Average: 80


90
70
80

Lynne Koenecke 8
Illinois State University, ACS
Wh a t C omp ute r s C a n D o

Five basic computer operations

Computers can:
1. Receive data
 from an input device (keyboard,
mouse, etc.)
 from a file

2. Display/write information
 to the display device (monitor)
 to a printer

3. Perform arithmetic
addition, subtraction, multiplication, division

4. Compare two pieces of data and select one of two actions


5 > 6 is False 10 = 10 is True A < B is True

5. Repeat a group of actions

Lynne Koenecke 9
Illinois State University, ACS
P ro b l em S o lv i n g a n d S o ft w a re D ev e l o pm e nt

Top-Down Design
Most programming problems are too complex to solve all at once.
Turning a problem into a program requires a programmer to create
smaller problems that fit together to solve the large, complex problem.
This is referred to as top-down design, because the design process
starts at the top, with the main ideas, and works down to the details.

The result of top-down design is an algorithm - a set of step-by-step


instructions that solves the original problem.

Characteristics of Algorithms
Algorithms must . . .
1. be precise and unambiguous
2. be the correct solution in all cases
3. eventually end

Pseudocode
Programmers typically write algorithms in a form called pseudocode.
Pseudocode is a cross between a computer language and plain English.
The pseudocode is translated into a computer language after the
algorithm has been tested for correctness.

Characteristics of Pseudocode
• Statements written in simple English
• Each instruction written on a separate line
• Keywords and indentation are used to signify control

Lynne Koenecke 10
Illinois State University, ACS
St e p s t o S o lv i n g a P ro b l em

Design
1. Defining the problem
2. Outline the solution
3. Develop the outline into an algorithm
4. Test the algorithm for correctness

Implementation
5. Code the algorithm into a specific programming language
6. Run the program on the computer
7. Document and maintain the program
art
sk ithm Ch

n t &
De or re

7. De de

tai en
Do bug
k
4. Alg ctu

Co
2. IPO

ain m
ec

M cu
3. Stru

Ch

5.
1.

6.

Design Implementation

Lynne Koenecke 11
Illinois State University, ACS
1. Defining the Problem:
Divide the problem into three components: inputs, processing, and
outputs.
We use an IPO chart to illustrate this step.

I P O

1. List the inputs


 data items that are entered into the program from the keyboard
or a file
 nouns
 examples: name, number, test_score, price, score

2. List the outputs


 information that has been processed by the program and/or
will be output by the program
 nouns
 examples: total, sum, balance, average
(outputs are sometimes the same as inputs)

3. List the processing steps


 steps needed during execution to solve the problem
 verbs (actions)
 examples: Read data, Calculate total, Determine rate,
Accumulate total revenue, Print heading, Print detail

Lynne Koenecke 12
Illinois State University, ACS
Example 1
Outline a solution for a program that will read 3 numbers and print the
average.

I P O
number1 get numbers average
number2 add numbers
number3 calculate average
print average

Example 2
Outline a solution for a program that will read 3 numbers and print the
numbers and the average.

I P O
number1 get numbers number1
number2 add numbers number2
number3 calculate average number3
print average average

Lynne Koenecke 13
Illinois State University, ACS
3. Converting the IPO into an Algorithm

Example 1

Average 3 numbers
get number1
get number2
get number3
total = number1 + number2 + number3
average = number1 + number2 + number3/3
print “Average: “ average
End Average 3 numbers

4. Desk Checking the Algorithm for Correctness


1. Choose appropriate test data.
2. Choose simple test data.
3. Check all cases.

Test Data: 5, 10, 15 Predicted Output: 10

number1 number2 number3 Output


5 10 15 20

Oops! We need to revise our algorithm.

The following line should have read:


average = (number1 + number2 + number3)/3
or better yet:
average = total / 3

Lynne Koenecke 14
Illinois State University, ACS
P ro g r am C o n t ro l S tr u c tu re s

Sequence

Selection

Repetition

Sequence
Execution of one processing step after another in order.

Task A
Task B
Task C

Selection - if . . . then . . . else


Evaluation of a condition to true or false to determine a path of action.

True False
Is 1>2?

Print “Yes” Print “No”

if 1 is greater than 2 then


Print “Yes”
else
Print “No”

Lynne Koenecke 15
Illinois State University, ACS
Repetition (looping)
Repeating a group of
instructions as long as a False
condition is true or until a
condition is false. ?

True
Pre-test loop

DO WHILE condition
statement
statement
statement
END WHILE

The statements in the DO


WHILE structure repeat as long as the condition is true.

Post-test loop Counter-controlled loop


DO DO loop_index = initial-value to final_value
statement statement
statement statement
statement statement
UNTIL condition END DO

The statements in the Used when a loop must execute a


DO structure repeat as specified number of times.
long as the condition is
false.

Lynne Koenecke 16
Illinois State University, ACS
A c t i o n D i a g r am s
Action Diagrams add an additional visual element to algorithms to indicate
sequence, selection, and repetition. (Refer to the Action Diagrams section
in the Appendix of your Lab Manual).

Sequence
Indicates start of algorithm Algorithm Name
statement
statement
statement
statement
Indicates end of algorithm End Algorithm Name
Statements are followed in order from the start of the algorithm to the end
of the algorithm.

Selection (IF . . . THEN)


Indicates start of algorithm Algorithm Name
statement
IF condition THEN
statement if condition is true
ELSE
statement if condition is false
END IF
End Algorithm Name
Indicates end of algorithm
As the statements in the algorithm are executed, a choice is made by
evaluating the condition of the IF .. . THEN control structure. The
dividing line indicates that only one of the statements executes based on
the TRUE or FALSE evaluation of the condition.

Lynne Koenecke 17
Illinois State University, ACS
Selection (CASE structure)
Indicates start of algorithm Algorithm Name
statement
CASE of final_grade
90 - 100: letter_grade = ‘A’
80 - 89: letter_grade = ‘B’
70 - 79: letter_grade = ‘C’
60 - 69: letter_grade = ‘D’
other: letter_grade = ‘F’
END CASE
Indicates end of algorithm End Algorithm Name
As the statements in the algorithm are executed, a choice is made by
evaluating the value of final_grade and using a CASE control structure.
Only one assignment is made based on the evaluation of final_grade..

Repetition
Indicates start of algorithm Algorithm Name
statement
DO WHILE condition
statement
statement
statement
END WHILE
End Algorithm Name
Indicates end of algorithm
As the statements in the algorithm are executed, a group of statements are
repeated withing the DO WHILE control structure until the condition is
evaluated to FALSE. The double line indicates repetition.

Lynne Koenecke 18
Illinois State University, ACS
Va r i a b l e s
As mentioned earlier, computers use main memory (RAM) to hold
instructions and data for processing. High-level programs allow programmers
to assign a name to a memory cell. When program statements are written, the
memory cell is referred to as the name the programmer gave it.

Variable Memory Locations


 Temporarily hold a value
 Can only hold one value at a time
 If a new value is placed in a memory loation, the old one is gone
forever
 Values are placed in locations by assignment statements
 Counters and accumulators must be initially assigned a value of
zero

Assignment Statement:
value1 = number + variable1

Original Values After Assignment Statement


Address Name Contents Address Name Contents
0 number 10 0 number 10
1 value1 20 1 value1 15
2 variable1 5 2 variable1 5
3 sum 0 3 sum 0
4 count 0 4 count 0
. . . .
. . . .
98 OH 98 OH
99 65.78 99 65.78

Lynne Koenecke 19
Illinois State University, ACS
C on t ro l St r u c tu re E x amp l e s
Predict what the output would be for each of the following Selection Control
Structures:

Example 1:
num1 = 10 Output
num2 = 20
IF num1 < num2 THEN
Print “num1 is less than num2”
ELSE
Print “num2 is less than num1”
ENDIF

Example 2:
variable1 = 100 Output
variable2 = 101
IF variable1 > variable2 THEN
Print “variable1 is greater than variable2”
ELSE
Print “variable 2 is greater than variable1”
ENDIF

Lynne Koenecke 20
Illinois State University, ACS
Predict the output of the following Repetition Control Structures:

value = 1 Output
DO WHILE value < 3
Print value
value = value + 1
END WHILE
Print “The last number is” value

value = 4 Output
DO WHILE value < 6
Print value
value = value + 1
END WHILE
Print “The Last number is” value

value = 4 Output
DO WHILE value > 0
Print value
value = value - 1
END WHILE

Lynne Koenecke 21
Illinois State University, ACS
Jessica
A g e n t l e r In t ro d u c t i o n to P ro g r amm in g

Why use Jessica? Jessica is an application program written for introductory


programmers that allows practice with logic and program flow using a simple
language who’s syntax can be learned quickly. Please read the section about
Jessica in the back of your lab manual for the specifics about Jessica and the
Jessica language.

Jessica’s World
• Jessica lives on Santong Island
• Jessica’s home position is in the extreme Northwest corner
• Jessica cannot swim
• She knows direction: North, South, East, and West
• She moves by hopping one space at a time
• She picks flowers (*)
• She gets killed by nets (#)
• She can detect nets one space ahead, on her left, and on her
right
• She can disable a net by tossing a flower on it

Lynne Koenecke 22
Illinois State University, ACS
Jessica’s Island

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .#. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .*. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . # . . . . . . . . . ##### . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .#. . . . . . . . . . . . . . * . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Lynne Koenecke 23
Illinois State University, ACS
C o n d it i o n s

Jessica can make decisions that affect selection and repetition control
structures. These decisions are based on simple conditions and NOT simple
conditions.

The exact phrase listed below is placed in parentheses as the condition to


check for true or false.

Simple Conditions NOT Simple Conditions


AT_FLOWER NOT AT_FLOWER
OUT_OF_FLOWERS NOT OUT_OF_FLOWERS
NET_AHEAD NOT NET_AHEAD
NET_ON_LEFT NOT NET_ON_LEFT
NET_ON_RIGHT NOT NET_ON_RIGHT
WATER_AHEAD NOT WATER_AHEAD
FACING_NORTH NOT FACING_NORTH
FACING_SOUTH NOT FACING_SOUTH
FACING_EAST NOT FACING_EAST
FACING_WEST NOT FACING_WEST

(see p. 6 of the Jessica section of your lab manual for an explanation of each of these conditions)

Lynne Koenecke 24
Illinois State University, ACS
S e l e c t i o n C o n tro l S tr u c tu re s
IF (condition) THEN
instruction block
END IF;

IF (condition) THEN
instruction block
ELSE
instruction block
END IF;

R e p e t it i o n C o n tro l S tr u c tu re s
WHILE (condition)
instruction block
END WHILE;

Legal, but not acceptable!

Do (number) TIMES
instruction block
END DO;

This code does not always work correctly in this environment.

*Notice that there are no semicolons after the IF line, ELSE line, and WHILE line.
There would be appropriate semicolons after each instruction block line.

Lynne Koenecke 25
Illinois State University, ACS
IP O C h a r t fo r J e s s i c a
Jessica does not have any variables. Therefore, there are no inputs and no
outputs.

I P O
turn to face north
hop to north beach
turn left
hop to west beach
go to home position

Lynne Koenecke 26
Illinois State University, ACS
P re - c on d i t i o n s a n d P o st-c o n d it i o n s
By looking at individual statements or a group of statements in a control
structure, a program can be tested for accuracy. Test data must be selected
carefully to determine if the statements (or group of statements) work in all
cases. (Refer to the section “Program Verification-Using Preconditions
and Postconditions” in the Appendix of your lab manual.)

Pre-condition:
-what is true or known before the statement (or group of statements) is
executed

Post-condition:
-what is true or known after the statement (or group of statements) is
executed

Example
number = 100
Pre-condition: number has no assigned value
Post-condition: number has been assigned the value 100

Example
read balance
IF balance > 200
balance = balance * 1.05
ELSE
balance = balance - 5
Pre-condition: balance has a value
(We don’t know the specific value. It is dependent on what is read in.)
Post-condition: Either balance has been increased by 5% or $5 has been
subtracted from balance

Lynne Koenecke 27
Illinois State University, ACS
Example
LEFT;
Pre-condition: Jessica is in her home position at the NW corner of the island
facing east.
Post-condition: Jessica is facing North.

Example
Jessica is in her home position and there is no net immediately in front of her.
WHILE (NOT NET_AHEAD)
HOP;
END WHILE;
Pre-condition: Jessica is in her home position at the NW corner of the island
facing east and there is no net immediately in front of her.
Post-condition: Jessica is facing East. Jessica has hopped at least one space
to the East. She may have hopped more than one space. There is a net in the
next space to the east.

Exercises:
Indicate whether the following statements are true or false given the
preconditions and postconditions as stated. If it is false, indicate why it is
false.

Precondition: var1 is an even integer

Statement: var1 = var1 + 1

Postcondition: var1 is an odd integer

Precondition: number is a positive integer

Lynne Koenecke 28
Illinois State University, ACS
Statement: DOWHILE (number is positive)
number = number - 1
ENDDO

Postcondition: number is a negative integer

Precondition: X < Y, X and Y are positive integers

Statement: IF X = Y THEN
X=X-Y
ELSE
Y=Y+X
ENDIF

Postcondition: X>Y

Preconditions: Jessica is facing North. There is a net an undetermined


number of spaces ahead of her.

Statement: WHILE (NOT NET_AHEAD)


HOP;
END WHILE;

Postcondition: NET_AHEAD is true; Jessica is facing North

Lynne Koenecke 29
Illinois State University, ACS
Members of Big R Video’s VIP Rental Club receive a 20% discount on
rentals. Regular rental rates are $2 per night.

Algorithm with Action Diagram:

Determine Rental Rate


Get member_status
Get num_movies
IF member_status = ‘y’ THEN
rate = 2*.8
ELSE
rate = 2
END IF
cost = rate * num_movies
Display rate
End Determine

Test Cases:

Member Status Num Movies Output


y 2 3.60
n 3 6.00

Lynne Koenecke 30
Illinois State University, ACS
N e ste d I F C o n t ro l St r u c tu re s

Example
Determine a student’s final grade based on a 90,80,70,60 scale.

IF grade > = 90 THEN


letter_grade = ‘A’
ELSE
IF grade > = 80 THEN
letter_grade = ‘B’
ELSE
IF grade > = 70 THEN
letter_grade = ‘C’
ELSE
IF grade > = 60 THEN
letter_grade = ‘D’
ELSE
letter_grade = ‘F’
END IF
END IF
END IF
END IF

Lynne Koenecke 31
Illinois State University, ACS
Trace the following algorithm and answer the question below.

num = 0
DO index = 1 to 4
num = num + index + 3
Print index, number
ENDDO

Number Index Output

Trace the following algorithm and answer the question below.

num = 0
DO index = 1 to 4
num = num + index + 3
ENDDO
Print index, number

Number Index Output

Lynne Koenecke 32
Illinois State University, ACS
Modularization

art
sk ithm Ch

n t&
De or re

7. De de

tai en
M ocu ug
k
4. Alg ctu

6. Co
2. IPO

ain m
ec

D b
3. Stru

Ch

5.
1.

Design Implementation

2. :Outline the solution (Structure Chart)


Larger problems require breaking the solution down into major tasks. If we
take the next step from the IPO, we groups similar processing tasks into
program modules and diagram it by using a structure chart.

Level 0
Example

Level 1

Task A Task B Task C

The main program is the driver program. It controls the program flow of the
entire program. The main program asks a module to perform its task. When
this occurs, control is temporarily given to that module. When the module
finishes its task, control is given back to the main program.

Lynne Koenecke 33
Illinois State University, ACS
Steeplechase

Run to Jump
Steeple Steeple

Jump Jump Jump


Up Over Down

Run Steeple Race

Run to Steeple

Jump Steeple

Pick Flower

End Steeple Race

Run to Steeple and Jump Steeple will each have their own
algorithms. The algorithms would be written based on their pre
conditions, post conditions and the task they are asked to
perform.

Lynne Koenecke 34
Illinois State University, ACS
In tro d u c t i o n t o C P ro g r amm in g
 C is portable
• portability is the ability to transfer a written program from one
computer to another with few or no changes
 C is fast and efficient
 C is flexible
• high-level language, but allows manipulation of the inner
workings of the computer

Ex am p l e C C o d e
Line
No.
1 /* Program to prompt for and print two numbers.*/
2 #include <stdio.h>
3 int num_1, num_2;
4 int main (void)
5 {
6 /*Input the first number*/
7 printf ("Enter a number between 1 and 100: ");
8 scanf ("%d", &num_1);
9 /*Input the second number*/
10 printf ("\nEnter another number between 1 and 100: ");
11 scanf ("%d", &num_2);
12 /*Print both numbers */
13 printf ("\n\nYou entered %d and %d.", num_1, num_2);
14 return(0);
15 }
(Line numbers are not entered in the C editor as part of the code. They are used here for reference
only.)

Lynne Koenecke 35
Illinois State University, ACS
S am p le o u tp u t:
Enter a number between 1 and 100: 25
Enter another number between 1 and 100: 50

You entered 25 and 50.

T h e P ro g r am C omp o n e n ts
a n d D e f i n it i o n s
main ( ) function - (lines 5 - 15) The main is the only component that is
required in every C program. Usually program execution starts at the first
statement in the main and ends at the last statement in the main.

What is a function? A function is a section of code that is


independent, performs a task, and has been given a name. When
you reference a function's name, program control is sent to that
function, the code is executed, and control returns to the calling
function.
Types of functions:
• Library functions - part of the C compiler
software package
• User-defined functions - code written by the
programmer
Braces ({ }) (lines 5 and 15) Line 5 is an open brace and line 15 is a close
brace. Every function must begin with an open brace and end with a closed
brace. The group of statements between the braces is called a block.

#include Directive -(line 2) instructs the C compiler to add the included file
to your program during compilation. Also called header files. Header files
define operations, symbols, values. Most C programs require the use of one
or more include files. The sample program includes stdio.h, the header file
which contains the standard input/output functions used in C.

Lynne Koenecke 36
Illinois State University, ACS
Variable Definition (line 3) a variable is a name that is assigned to a storage
location in memory. In C, you must define a variable before you can use it.
The definition tells the compiler the name of the storage location and the type
of data that will be stored there. You must follow specific C rules for naming
variables.

Comments - (lines 1, 6, 9, and 12) internal documentation of a program for


the programmer (useful for the original programmer, but especially useful for
the maintenance programmer months or years later). These statements are
ignored by the compiler. In C the delimiters are the
/* (to begin the comment) and */ (to end the comment)

/* A single line comment */


int num_1, num_2; /* A partial line comment */
/* a
multiple
line comment */

Statements - (lines 7, 8, 10, 11, 13) instruction to the computer.


Collectively, statements make up a program. Statements display information
on the screen, accept input from the keyboard, perform logical and/or
mathematical operations, read files, call functions, etc.

printf() - library function that displays information on the screen. It


can display a simple message or combine literal text with the contents
of variables.

scanf() - library function that reads data from the keyboard and assigns
it to one or more program variables.

Lynne Koenecke 37
Illinois State University, ACS
Va r i a b l e s
A variable is a named storage location in the computer's random access memory (RAM).

Variables have a name, a type and a value.

Variable Names - you must follow the rules of C for naming variables.
• The name can contain letters, digits, and underscores ( _ ).
• The first character of a variable must be a letter. (the underscore is
legal, but shouldn't be used as a first letter)
• C is case sensitive (uppercase and lowercase letters are different to
the C compiler) Num1 is not the same as num1. C looks at these
two variable names as referring to two different storage locations.
• C keywords cannot be used as variable names.
• Variables can be 1 - 31 characters in length.

Reserved words in C
asm 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

Suggestions:
• Make variable names meaningful
• Don't make them too long (leaves more room for typing errors)
• Don't use single character variables except for counters
• Use lowercase letters with underscores to separate words

Lynne Koenecke 38
Illinois State University, ACS
Va r i a b l e D e c l a r a t i o n
Before a variable can be used in C, it must be declared. Declaring a variable
lets the compiler know that it needs to set aside a portion of main memory for
use during the execution of your program. It tells the compiler the name that
you are going to refer to the memory location as and the type of data that will
be stored there.
typename varname;
int score_1;
int count, number, start; /* declares three integer variables on one line */
float total_amount, percent; /*declares two float variables */

Variable Values - declaring a variable tells the compiler to set aside


memory space. The value in that space (the value of the variable you just
named) is not defined. You only defined the name of the variable and the
type of data to be stored. You must initialize the value to a known value by
an assignment statement or initialize it at the declaration statement.

If you do not initialize a variable by either of the above methods, you variable
could contain "garbage".

1. Initializing numeric variables as you declare


int count = 0;
float percent = .05, taxrate = 37.2;

2. Initializing numeric variables with assignment statements


percent = 12.3;
amount = 43.25;
number = 4;
(Remember, these variables were declared before the assignment statements.)

Lynne Koenecke 39
Illinois State University, ACS
Numeric Variable Types - C has several different types of variables
for numeric data because different numeric values require different storage
requirements in main memory. Using the correct data types ensures that your
program runs as efficiently as possible.

Integer variables
• whole numbers (have no fractional parts)
• -1, 0, 10, -12, 354

Floating-point variables
• real numbers (have a fractional part)
• -5.64, 0.564, 6.445, 7.2, -12.01

Within each of the two categories are more specific data types that deal with
different memory requirements based on the size of the values.
Variable Type Keyword Bytes Range
Required
character char 1 -128 to 127
integer int 2 -32768 to 32767
short integer short 2 -32768 to 32767
long integer long 4 -2,147,483,648 to
2,147,438,647
unsigned character unsigned char 1 0 to 255
unsigned integer unsigned int 2 0 to 65535
unsigned short integer unsigned short 2 0 to 65535
unsigned long integer unsigned long 4 0 to 4,294,967,295
single-precision floating- float 4 1.2E-38 to 3.4E38
point
double-precision floating double 8 2.2E-308 to 1.8E308
point
Table showing amount of bytes required to store different types of numeric variables on a 16-bit
architecture PC.

Lynne Koenecke 40
Illinois State University, ACS
C o n st a n ts
Another method of assignment is defining a constant value with the #define
directive which is one of C's preprocessor directives.

#define PI 3.14159 /* notice that there is no semi-colon */

The statement above defines PI as 3.14159 for the entire execution of the
program. Anywhere in the program where PI is used, it is substituted for the
value of 3.14159.

When using #define the name of the constant is written in all


caps.

Lynne Koenecke 41
Illinois State University, ACS
Up p e rc a s e a n d L o w e rc a s e L e tte r s
Great care must be taken when using case in letters. Num1, num1, and
NUM1 are viewed as different identifiers by the C compiler.
 All reserved words in C are lowercase.
 #define preprocessor directives are all uppercase.

P ro g r am S ty l e
Guidelines from improving readability of programs
 Use meaningful variable names.
 Use an underscore to separate words in a variable name
lbls_per-sq_inch is much easier to read than
lblspersqinch

Using white space in your programs


What is white space? Why use it? Does the compiler care?
• blank lines and spaces
• use it to improve readability and appearance of your program
• the compiler ignores it

Ex e c u t a b l e S t a tem e n ts
Operations of a program are specified by executable statements that appear in
the body of a program, following variable declarations.

Each executable statement is translated by the C compiler into one or more


machine language instructions that are copied to the object file and later
executed.

Lynne Koenecke 42
Illinois State University, ACS
O r d e r o f C P ro g r am C omp o n e n ts
/************************************************************* main
comment block SEE the Comment Specifics in the back
* of your Lab Manual!!!!!
************************************************************/
Preprocessor Directives (#include, #define)
Function Prototypes
int main (void)
{ /* open brace which starts the function block*/
/*variable declarations*/

/*executable statements*/

return (0);

}/*end of main program*/

/************************************************************
* user - defined function comment block
************************************************************/
function definition
{
/*variable declarations -if needed*/

/*executable statements*/

Lynne Koenecke 43
Illinois State University, ACS
D e ve l o p in g a C p ro g r am

1. Use an editor to type in and save your C source code. We will be using
the editor in Turbo C++. The source code will be saved as filename.c.
2. Compile the program using a C compiler. If no errors occur then an object
file is produced by the C compiler - filename.obj. If errors occur, they
are displayed for you. Correct them, and try to compile again.
3. Link the program. If no errors are detected, then an executable file is
created - filename.exe.
4. Execute the program. Here you should test to make sure that your
program is free of logic errors and works exactly as how you intended it
to. If there are errors, go back to step 1, revise the code and proceed
through steps 2-4 again.

Source Preprocessed Object Executable


Code Source Code Code Code

Editor Preprocessor Compiler Linker

External
Items

Lynne Koenecke 44
Illinois State University, ACS
Ass i g nm en t St a t em en ts
The = sign is used in C to place values into variables. The form is as follows:
variable = constant; or variable = expression;
Ex:
counter = 0; /* puts a value of 0 into the variable named counter */
Visually, in memory, the space allocated for counter now has a value of zero.
counter
0
The value 0 is a constant.

Expressions:
When an expression is on the right side of the equal sign (=), the expression
is first evaluated and then the value of that expression is assigned to the
variable which is named on the left side of the equal sign (=).

Ex: The variables number_1 and number_2 have been declared and
assigned values of 5 and 6 respectively.
number_1 number_2 sum
5 6

sum = number_1 + number_2;

After the statement executes, the stored values are:


number_1 number_2 sum
5 6 11

Lynne Koenecke 45
Illinois State University, ACS
S om e A r i thm et i c Op e r a t o r s
Arithmetic Meaning
Operator
+ addition
- subtraction or negation
* multiplication
/ division

In p ut / Ou tp u t Op e r a t i o n s

C Input - scanf ();

To get values into your program, the scanf function is used. The scanf
function has two arguments. The first is the format control string and the
second is the variable name preceded by an ampersand (&) which is the
address of operator in C.

Ex:
scanf ("%d", &number_1);
When this statement is executed, the cursor waits until the user enters a
number and the enter key to proceed. After the enter key is pressed, the
statement is completed. This example statement gets a decimal integer from
the keyboard and assigns it to the address of number_1.

scanf ("%d%f", &num_1, &average);


/* accepts two integers separated by a space*/

Lynne Koenecke 46
Illinois State University, ACS
Prompting for scanf
You should prompt the user to let them know what they are to enter before
using the scanf function.
printf ("Enter the first and second scores separated by a space: ");
scanf ("%d%d", &score_1, &score_2);

C onv e r s i o n s Sp e c s f o r sc a n f ( );
The format strings should match the data type for scanf.
Data type scanf ( ) placeholder
char %c
int %d
float %f
double %lf

C Output: printf ( );

The printf function is used for C output to the screen. The following
statement prints a line of text to the screen:
printf ("This is my first C program.");

The output is:


This is my first C program.

Lynne Koenecke 47
Illinois State University, ACS
You can add a backslash (\), called an escape character, plus another
character to indicate that printf should do something besides print the line of
text.

printf ("This is my first C program.\n");


printf ("A newline escape sequence was used.");

The output is:


This is my first C program.
A newline escape sequence was used.

Common escape sequences


Escape sequence Description
\n Newline. Positions the cursor at the beginning of the next line.
\t Horizontal tab. Moves the cursor to the next tab stop.
\r Carriage return. Positions the cursor to the beginning of the current
line; does not advance to the next line.
\\ Backslash. Prints a backslash character in a printf statement.
\" Double quote. Print a double quote character in a printf statement.

C on ve r s i o n s S p e c s f o r p r i n t f ( );
The format strings should match the data type for printf.
Data type printf ( ) placeholder
char %c
int %d
float %f
double %lf

Lynne Koenecke 48
Illinois State University, ACS
P r in t i n g Va r i a b l e s
/* Addition program */
#include <stdio.h>

int main(void)
{
int integer1, integer2, sum; /* variable declarations */

printf ("Enter first integer\n"); /* prompts user */


scanf ("%d", &integer1); /* reads an integer */
printf ("Enter second integer\n") /* prompts user */
scanf ("%d", &integer2); /* reads an integer */
sum = integer1 + integer2; /* assignment of sum */
printf ("sum is %d\n", sum); /* print sum */

return (0); /* indicate that program ended successfully */


}

Program output

Enter first integer


45
Enter second integer
40
Sum is 117

Lynne Koenecke 49
Illinois State University, ACS
Algorithm:
calculate_double
get value to num_to_double
double = num_to_double * 2
Print message with num_to_double and double
End of calculate_double

C Program: (Use the comments to be sure you include all necessary components.)
/* include statement(s) */
#include <stdio.h>
int main (void)
{
/* variable declarations */
int num_to_double;
int double;

/* executable statements - the translation of the algorithm */


clrscr();
printf (“Please enter a number to double “);
scanf (“%d”, &num_to_double);
double = num_to_double * 2;
printf (“\n%d doubled is %d”, num_to_double, double);
getch(); /* to hold the output on the screen */
return (0);
} /* end of program */

Lynne Koenecke 50
Illinois State University, ACS
S im p le C o n t ro l S tr u c tu re s
The if structure and if - else structure

if (expression) if (expression)
statement if true; statement if true;
else
statement if false;

A compound statement or block in C must be surrounded with braces.

if (expression) if (expression)
{ {
statement; statement;
....... .......
statement; statement;
} }
else
{
statement;
.......
statement;
}

Lynne Koenecke 51
Illinois State University, ACS
Nested If

if (expression) if (expression)
statement if true; statement;
else else if (expression)
if (expression) statement;
statement if true; else
else statement;
statement if false;

R e p e t it i o n C o n t ro l St r u c tu re

Counter-Controlled Loop - the for loop

for (initial; condition; increment)


statement;

or
for (initial; condition; increment)
{
statement;
statement;
......
statement;
}

for (k=1; k<=10;k++)


{
....
}

Lynne Koenecke 52
Illinois State University, ACS
Graphics

See the back of your ACS 168 lab manual for the graphics functions and
explanations.

Graphics have two modes:


1 Text
• must use #include <conio.h>
2 Graphics
• must use #include <graphics.h>

Check your lab manual for code to include in every graphics program as well
as how to change the Turbo C++ settings and change to the bgi directory.

Lynne Koenecke 53
Illinois State University, ACS
M a th in C

C operation Arithmetic Algebraic C expression


Operator expression

Addition + a+8 a+8


Subtraction - q-1 q-1
Multiplication * kr k*r
Division / x/y or x/y or x÷y x/y
Modulus % r mod y r%y

Integer Division
C evaluates the expression 8 / 3 to have the value of 2. Both 8 and 3 are
integers and the result will also be an integer. C divides and drops the
fractional part of the answer.

9/7 = 1 10/3 = 12/5 = 61/2 =

Modulus
Gives the remainder after integer division.
5%2=1
How did we get that answer? 5/2 = 2 R 1 1 is the modulus

12 % 2 = 14 % 2 = 16 % 3 25 % 6 =

Lynne Koenecke 54
Illinois State University, ACS
O r d e r o f Op e r a t i o n s
When C evaluates expressions, it follows rules of operator precedence.
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses 1st to be evaluated. If there are parentheses
inside parentheses (nested parentheses), the
inner most parentheses are evaluated first, then
continue out to the outermost parentheses.
+, -, ! (not) unary 2nd to be evaluated.
*, /, or % Multiplication 3rd to be evaluated. If there is more than one
Division of these operators, C evaluates from left to
right.
Modulus
+ or - Addition Last. If there is more than one of these
Subtraction operators, C evaluates from left to right.

x = q - 8 * y / 4 + 16
Order of operation 3 1 2 4

x = 4 - 8 * 2 / 4 + 16
4 - 16 / 4 + 16
4 - 4 + 16
0 + 16
16

Lynne Koenecke 55
Illinois State University, ACS
Ty p e C o n v e r s i o n s

All of C's data objects have a specific type. The logic of programs sometimes
requires that different types be combined in expressions and statements.
Sometimes C automatically handles these different types. At other times, the
conversion must be made by the programmer.

Automatic type conversions - performed automatically by the C


compiler.
• When a C expression is evaluated, the resulting value has a particular data
type.
sum = integer_1 + integer_2;
*if integer_1 and integer_2 are typed int, then sum will be int

result = number + average;


*if number is an integer and average is a float, then the result is a float
because of the following:

When the above is evaluated the result has the same type as its most
comprehensive component.

char int long float double


Least comprehensive Most comprehensive

int = int + int;


float = float + float;
float = int + float;

example: x/y if x is an int and y is a float, evaluating the expression


causes a copy of x to be promoted to float before it is evaluted

Lynne Koenecke 56
Illinois State University, ACS
Explicit type conversions - occurs when the programmer instructs the
computer to convert a value from one type to another.

Using typecasts -
A typecast uses the cast operator explicitly to control type conversions in a
program. A typecast consists of a type name, in parentheses, placed before
an expression.

Example:
int integer;/*integer is declared*/

(float) integer; /*typecasts integer to float*/

Variable Data Type Value


test1 int 90
test2 int 75
total int 4
a int 3
b int 5

Lynne Koenecke 57
Illinois State University, ACS
Problems- evaluate as the C compiler would.

1. What is the product of 5 and 7 divided by 2?


Answer Data type

2. total = a2 + b2
Answer Data type of total

3. average = (test1 + test2)/2


Answer Data type of average

4. percentage_of_difference = (test1 - average) / average * 100


Answer Data type of percentage of difference

Lynne Koenecke 58
Illinois State University, ACS
S w i t c h (M u lt ip l e -S e l e c t i o n S tr u c tu re )

switch (controlling expression)


{
case c1:
any number of statements;
break;
case c2:
any number of statements;
break;

default:
any number of statements;
}

• Use when the selection is based on a single variable or simple expression


(controlling expression).
• The value of the controlling expression should evaluate to int or char, not
double.
• Maximum of 10 cases
• The controlling expression is evaluated, then the list of case labels is
searched until one label that matches the value of the controlling
expression is found.
• Statements the follow the matching case label are executed until a break
statement is encountered. The break causes an exit from the switch
statement.
• If no match is found, execution is transferred to the statement following
the optional default label.
• If no match is found and there is no default label, execution passes to the
first statement following the switch statement's closing brace.

Lynne Koenecke 59
Illinois State University, ACS
/* Demonstrates the switch statement */
#include <stdio.h>
void main ()
{
int reply;
printf ("Enter a number between 1 and 5: ");
scanf ("%d", &reply);
switch (reply)
{
case 1:
printf ("You entered 1.");
break;
case 2:
printf ("You entered 2.");
break;
case 3:
printf ("You entered 3.");
break;
case 4:
printf ("You entered 4.");
break;
case 5:
printf ("You entered 5.");
break;
default:
printf ("Out of range, try again.");
}
}

Lynne Koenecke 60
Illinois State University, ACS
Switch is used quite often to process menu choices that a user makes.

gotoxy (____ , ____) is used to position text on the screen

The screen measures as follows in text mode:

80 columns (x value)

24 rows
(y value)

/**************************************************
* Function to print a menu using gotoxy
**************************************************/
void print_menu (void)
{
gotoxy (38,7); printf ("Menu Choices");
gotoxy (32,9); printf ("1. Enter Data");
gotoxy (32,10); printf ("2. Process Information");
gotoxy (32,11); printf ("3. Exit");
gotoxy (32, 15); printf ("Enter your choice: ");
}

Lynne Koenecke 61
Illinois State University, ACS
Ch a r a c t e r D a t a
Another standard data type in C is type char. Variables of type Char can be
used to store any single character value.

Variable declaration
char letter_1, letter_2, letter_3;

scanf (“%c%c%c”, &letter_1, &letter_2, &letter_3);


/* User enters Bob and presses return*/

letter_1 letter_2 letter_3


B o b

Character data is frequently used to get a user choice in from a menu.


char choice;
choice = getch();

We have previously used getch() to hold the screen for viewing output . If
you assign getch(); to a character variable, the key that was hit by the user is
stored.
The enter key is stored as ‘/n’

getche(); /* The e echoes (repeats) the user’s choice to the screen.

Screen Design
Be sure to read the guidelines for screen design for Lab 10. Materials are on
reserve in the Library under your instructor’s name.

Lynne Koenecke 62
Illinois State University, ACS
Functions

Programmer-defined functions are blocks of code that perform a specific task


and may return values to the calling program. In C, functions are the same as
modules. Functions allow the programmer to modularize the program.

Why use functions?


• Software reusability - the same code can be utilized more than once in a
program.
• Makes programs more manageable, easier to understand, debug, and test.

Parts of a function:
• Function prototype
• Function call
• Function definition

All functions must have all three parts.

Lynne Koenecke 63
Illinois State University, ACS
Function prototype tells the compiler:
• type of data returned by the function
• number of arguments the function expects to receive
• data types of the arguments
• order in which the arguments are expected

placed before the main function as follows:


return-value-type function_name (argument list, . . .);
argument list consists of data types in order,
variable names are optional
Default return-type is int, if nothing is
to be returned, void is used.

Function call invokes the function:

printf ("Half of %d is %d.", x, half_of(x));


/*function call with argument of x, nothing is returned*/

y=half_of(x);
/*function call with argument of x, 1 value is returned and placed in y*/

print_half (y);
/*function call with argument of y, nothing is returned*/

print_header ( );
/*function call with no argument(s), nothing is returned*/

Lynne Koenecke 64
Illinois State University, ACS
Function definition tells the compiler:
• type of data to be received by the function
• number of parameters the function expects to receive
• name of parameter(s) the function receives
• data types of the parameters
• order in which the parameters are expected

placed as a header before the function's lines of code as follows:


return-value-type function_name (parameter list, . . .)
parameter list consists of data types in order,
and variable names
Default return-type is int, if nothing is
to be returned, void is used.

Also, notice that there is no semi-colon at the end of the line just as in the main.

The format of a function is:


return-value-type function_name (parameter list, . . .)
{
declarations

statements
}

Lynne Koenecke 65
Illinois State University, ACS
/* A programmer-defined square function */
#include <stdio.h>

int square (int); /*function prototype*/

int main (void)


{
int x;

for (x = 1; x <=10; x++);


printf ("%d ", square (x)); /*calls the function*/
return (0);
}

/* Function definition */
int square (int y)
{
return y * y;
}

Lynne Koenecke 66
Illinois State University, ACS
P a ss i n g A r gum en ts
You can pass arguments two ways. 1. By Value or 2. By Address

Passing by Value
• The value of the variable is passed through the argument list to the
receiving function.
• Passing a variable by value protects it's content.

/*passing a variable by value */


#include <stdio.h> Program output:
Please enter a number: 24
void half (int); Your value halved is 12.
In main ( ), j is still 24.
int main (void)
{
int j;

printf ("Please enter a number: ");


scanf ("%d", &j);

half (j); /*function call passes a copy of the contents of j to half */


printf ("In main ( ), j is still %d.\n", j);

return (0);
} /*end main */

void half (int j)


{
j = j/2;
printf ("Your value halved is %d.\n", j);
} /*end half*/

Lynne Koenecke 67
Illinois State University, ACS
Passing by Address
• The memory address of the variable is passed to the receiving function
from the calling function.
• If the value of the variable is changed in the receiving function, it is also
changed in the calling function.
To pass a variable by address, you must:
• put an & operator in from of the variable name in the argument list
of the calling function
• put an * (dereferencing) operator in front of the variable everywhere
it is referenced in the receiving function

/*passing a variable by address */


#include <stdio.h> Program output:
Please enter a number: 24
void half (int *); Your value halved is 12.
In main ( ), j is now 12.
int main (void)
{
int j;
printf ("Please enter a number: ");
scanf ("%d", &j);
half (&j); /*function call passes the address j to half */
printf ("In main ( ), j is still %d.\n", j);
return (0);
} /*end main */

void half (int *j)


{
*j = *j/2;
printf ("Your value halved is %d.\n", *j);
} /*end half*/

Lynne Koenecke 68
Illinois State University, ACS
E x amp l e s o f P os s ib l e F o rm s F u n c ti o n s C a n Take

Returns No Result
void print_header (); /* function prototype */

print_header(); /*function call*/

/******************************
*This function displays a header
******************************/
void print_header(void) print_header
{
printf ("Report title");
}

With Arguments
void print_summary (int, int); /* function prototype */

print_summary(count, total); /*function call*/

/****************************** count
*This function displays a summary total
******************************/
void print_summary (int count, int total)
{
double average; print_summary
average = (float) count/total;
printf ("The count is: %d\n", count);
printf ("The total is: %d\n", total);
printf ("The average is: %d\n, average);
}

Lynne Koenecke 69
Illinois State University, ACS
Returns a Single Result
int sum (int, int); /* function prototype */

answer = sum(number1, number2); /*function call*/

/****************************** number1
answer
*This function adds 2 numbers number2
******************************/
int sum (int num1, int num2)
{
sum
int total;
total = num1 + num2;
return (total);
}

Returns Multiple Results


void calculate_total (double, double, double*, double*, double* ); /* function prototype */

calculate_total (item1, item2, &subtotal, &tax, &total); /*function call*/

/***************************************
*This function calculates subtotal, tax, and total
***************************************/
subtotal
void calculate_total (double item1, double item2, item1 tax
double *subtotal, double *tax,
item2 total
double *total )
{
*subtotal = item1 + item2; calculate_total
*tax = *subtotal * .07
*total = *subtotal + *tax;
}

Lynne Koenecke 70
Illinois State University, ACS
C omp ou n d Ex p re ss i o n s & N e ste d I f s

Logical Operators

Sometimes, you must ask more than one question to evaluate an expression.

For example, "If it is 7:00 a.m. and a weekday and not a vacation day, ring
the alarm."

In C, you must use a combination of logical operators to ask multiple


questions.

Operator Symbol Example


AND && expression1 && expression2
OR || expression1 | | expression2
NOT ! !expression1

Expression Evaluates As
(exp1 && exp2) True (1) only if both exp1 and exp2 are
true; false (0) otherwise.
(exp1 | | exp2) True (1) if either exp1 or exp2 is true;
false (0) only if both are false.
(!expr1) False (0) if exp1 is true; true (1) if exp1 is
false

Lynne Koenecke 71
Illinois State University, ACS
Expression Evaluates As
(5 = = 5 ) && (6 != 2) True (1) because both operands are true
(5 > 1) | | (6 < 1) True (1) because one operand is true
(2 = = 1) && ( 5 = = 5) False (0) because one operand is false
!(5 = = 4) True (1) because the operand is false

Precedence of Logical Operators

() highest
! - (unary)
* / %
+ - (binary)
< <= > >=
= = !=
&&
||
= lowest

Lynne Koenecke 72
Illinois State University, ACS
Truth Tables (T = true, F = false)

x y x && y
F F F
F T F
T F F
T T T

x y x||y
F F F
F T T
T F T
T T T

x !x
F T
T F

Lynne Koenecke 73
Illinois State University, ACS
F o rm a tti n g Num e r i c a l Ou tp u t

int
• %d prints the value exactly as it is
• the field width, placed between the % and the d indicates the number of
columns to be displayed.
• default is right justified
• use a - to left justify
• a negative sign is counted in the field width
• the field expands as needed

Examples:
printf("%d%d\n",254,842);
printf("%1d%2d\n",254,842);
printf("%3d%4d\n",254,842);
printf("%4d%5d\n",254,842);
printf("%-4d%-5d\n",254,842);
printf("%-6d%-7d%d\n",254,842, 324);

Output (b = blank space)

254842
254842
254b842
b254bb842
254b842bb
254bbb842bbbb324

Lynne Koenecke 74
Illinois State University, ACS
float, double
• %f always prints with 6 decimal place
• format: %n.mf
• n is the total field width
• m is the number of decimal places

n=6

• the decimal point and negative sign are counted in the total width
• if there is no whole number, a 0 always prints
• fractional parts are rounded if the field is smaller than the assigned number
• if the format %.mf is used, it will print with no leading blanks
• a number is right-justified unless a minus sign is placed immediately after the %

Examples:
printf("%f%f\n",254.0,842.0);
printf("%6.4f%8.4f\n",254.0,842.0);
printf("%.2f%.4f\n",254.0,842.0);
printf("%3.2f%6.2f\n",254.0,842.0);
printf("%-15.4f%-9.4f\n",254.0,842.0);
printf("%-8.0f%-9.0f\n",254.0,842.0);

Output (b = blank space)


254.000000842.000000
254.0000842.0000
254.00842.0000
254.00842.00
254.0000bbbbbbb842.0000
254bbbbb842bbbbbb

Lynne Koenecke 75
Illinois State University, ACS
Arrays

Data Structure - grouping of related data items in memory. Using a data


structure, you can process data individually or as a whole.

Array - data structure used for storage of a group of related items that are of
the same data type.

Declaring Array structures in C


❏ Assign one name to a group of items. These items will be stored in
adjacent memory locations.
❏ Declare the data type, name and number of memory locations to be used

float score [5];

*Many times a #define is used to assign the size of an array making


modifications much easier if the array size changes.
#define SIZE 5
float score [SIZE];

Referencing Arrays: subscripts or indexes are used to reference individual


items of an array called elements. C starts referencing arrays with 0.

score [0]
score [1]
score [2]
score [3]
score [4]

Lynne Koenecke 76
Illinois State University, ACS
Getting Values into Array Elements
There are 3 ways to assign values to the elements of an array
1. Initializing arrays in the variable declaration statement.
2. Reading input values into the array from the keyboard or file.
3. Assignment statements.

Initialization
float score [SIZE] = {90, 84, 76, 100, 64};
score [0] 90
score [1] 84
score [2] 76
score [3] 100
score [4] 64

Reading input values in via keyboard


for (j = 0; j<5;j++)
{
printf ("Please enter a score ");
scanf ("%f", &score[j]);
}

Assignment Statements
difference [1] = score [1] - average;

/*The average has been found by adding up all of the array elements and
dividing by the number of elements.*/

Lynne Koenecke 77
Illinois State University, ACS
Advantages of Using Arrays
❏ You can reference many items by one name. This reduces the number of
different variable names that you need for your program.
❏ You can use the same code to reference different memory locations by
changing the array subscript by using a variable name for the subscript.
❏ You can store multiple data items for use later in the program.

#define SIZE 25;


int main ( );
{ score [0] 90
int j; score [1] 84
sum = 0; score [2] 76
float average; score [3] 100

float score [SIZE] = {90, 84, 76, 100, 64}; score [4] 64

float difference [SIZE];

for (j = 0; j<5; j++) sum 90


174
{
250
sum = sum + score [j];
350
} 414

average = sum / 5; average 82.8

for (j = 0; j<5; j++) difference [0] 7.2


{ difference [1] 1.6
difference [j] = score [j] - average; difference [2] -6.8

} difference [3] 17.2

}/*end main*/ difference [4] 18.8

Lynne Koenecke 78
Illinois State University, ACS
Passing Arrays
❏ Arrays cannot be used in the return of the function.
❏ Arrays are passed by address by default.
❏ To override this, use the word const in front of the declaration in the
parameter list.

Function prototype
void function_a (int [ ]);

Function call
fuction_a (score);

Function definition
void function_a (int score [ ])
{
.
.
}

Lynne Koenecke 79
Illinois State University, ACS
S o r t i n g A r r a y E l em en ts

There are times when the elements of an array need to be sorted. Numbers or
names may need to be put in ascending or descending order so that they can
be searched or printed in order. There are several sorting methods. We will
discuss the bubble sort and selection sort.

Bubble Sort
1. Decide if the array should be sorted in ascending or descending order.
2. Compare adjacent elements in an array and exchange the values when they
are out of order.
3. One complete time through all array elements is referred to as a pass
through the array. At the end of the first pass, the largest value is in the
last element of the array (if you are sorting in ascending order).
4. The maximum number of passes through an array to sort the elements is
the number of elements minus 1. The minimum number of passes is 1.

Selection Sort
1. Find the smallest element in the array. Exchange that element with the one
in the first position (this is for ascending order).
2. Starting from the second element, find the smallest element in the array
and exchange that element with the element in the second position.

Continue until the array is sorted.

Lynne Koenecke 80
Illinois State University, ACS
Bubble Sort Example
Original unsorted array score:
score [0] 80
score [1] 70
score [2] 50
score [3] 90
score [4] 60

Before pass Swapping During Pass After pass

score [0] 80 80 score [0] 70


score [1] 70 70 80 score [1] 50
score [2] 50 Swap 50 80 score [2] 80
score [3] 90 Swap 90 90 score [3] 60
score [4] 60 No Swap 60 score [4] 90
Swap

score [0] 70 70 score [0] 50


score [1] 50 50 70 score [1] 70
score [2] 80 Swap 80 80 score [2] 60
score [3] 60 No Swap 60 80 score [3] 80
score [4] 90 Swap 90 score [4] 90
No Swap

score [0] 50 50 score [0] 50


score [1] 70 70 70 score [1] 60
score [2] 60 No Swap 60 70 score [2] 70
score [3] 80 Swap 80 80 score [3] 80
score [4] 90 No Swap 90 score [4] 90
No Swap

Lynne Koenecke 81
Illinois State University, ACS
Selection Sort

Before pass Swapping During Pass After pass

score [0] 80 Smallest = 50 (element 2) score [0] 50


score [1] 70 Exchange with the first element score [1] 70
score [2] 50 score [2] 80
score [3] 90 score [3] 90
score [4] 60 score [4] 60

score [0] 50 done score [0] 50


score [1] 70 score [1] 60
score [2] 80 Smallest of elements 1 - 4 = 60 score [2] 80
score [3] 90 Exchange with the second element score [3] 90
score [4] 60 score [4] 70

score [0] 50 done score [0] 50


score [1] 60 done score [1] 60
score [2] 80 Smallest of elements 2 - 4 = 70 score [2] 70
score [3] 90 Exchange with the third element score [3] 90
score [4] 70 score [4] 80

score [0] 50 done score [0] 50


score [1] 60 done score [1] 60
score [2] 70 done score [2] 70
score [3] 90 Smallest of elements 3 - 4 = 80 score [3] 80
score [4] 80 Exchange with the fourth element score [4] 90
S e a rc h in g a n A r r a y

Linear Search (Sequential Search)


Searching the array item by item, quitting when the target item is found

Algorithm
target not found
start with initial array element
while (target is not found and there are more elements)
if (current element matches target)
set flag to indicate target found
else
advance to the next element
if target found
return target index as the result
else
return -1 as the search result (target not found)
/***************************************************************
*Search for the target item of an array
*Returns the index of the target or not_found
*Pre-conditions: target and first n elements are devined & n>0
* array is the array, target is the value to search for, n = num_elements
***************************************************************/
int search (const int array [ ], int target, int n)
{
int k;
int found = 0; /* flag to indicate whether the target has been found */
int where; /*index where target found or not found*/

/*compare each element to the target */


k = 0;
while (!found && k < n) /* loop stops at either the last element or on a value that matches target*/
{
if (array [k] = = target)
found = 1; /* if the target has been found, the flag is set to found or 1*/
else
++k;
}

/*returns index of element that matched target or not found */


if (found) /*remember true = 1 */
where = k; /* k is the index number where the loop stopped */
else
where = 0;
return (where);
}
Binary Search
Searching a sorted array. Takes the array, divides it in half, searches the
appropriate half and "throws away" the other half. The half kept is then split
and the procedure is repeated until the target item is found.

Algorithm array[ ]
bottom = subscript of the initial array element
element
0 5
top = subscript of the last array element
1 8
found = false
2 12
3 20
while (target not found)
4 32
calculate middle position
5 35
if (the element at middle is the target
then) 6 36
found = true 7 40
record position 8 60
else 9 65
if (element at middle > target) 10 68
top = middle - 1 11 70
else 12 75
bottom = middle + 1

Looking for 36
int binary_search (int array [ ], int size, int item)
{
int middle, where, botom, top, found;

bottom = 0;
top = size;
found = 0;

while (!fount && bottom <= top)


{
middle = (bottom + top)/2;
if (array [middle] = = item)
{
found = 1;
where = middle;
}
else if (array[middle]>item)
top = middle - 1;
else
bottom = middle + 1;
}
if (found)
return (where);
else
return (-1); /*indicates unsuccessful*.
}
Ch a r a c t e r v s. S tr i n g s

char
• variable that stores a single character of information
• placed between two apostrophes 'c' or 'C' or 'm' or 'M', etc.
• use %c for printf or scanf
• getchar - reads a character from keyboard
• putchar - displays a character to the screen

Buffers
• buffers stores characters in s special location in main memory to be sent to secondary
storage or they can be brought in from secondary storage
• there is a stdin buffer and a stdout buffer
• when the buffer fills, the computer flushes to a peripheral device
• you can force the buffer to flush by fflush (include conio.h) fflush(stdin); flushes the
stdin buffer

/*code with no flush*/


#include <stdio.h>
void main()
{
char a_character;
clrscr();
printf ("Enter a character: ");
a_character = getchar();
printf ("\nThe character you just entered is: %c\n",a_character);
printf ("Enter another character: ");
a_character = getchar();
printf ("\nThe character you just entered is: %c\n",a_character);
getch();
return 0;
}
/*code that flushes stdin*/
#include <stdio.h>
#include <conio.h>
void main()
{
char a_character;
clrscr();
printf ("Enter a character: ");
a_character = getchar();
printf ("\nThe character you just entered is: %c\n",a_character);
fflush(stdin);
printf ("Enter another character: ");
a_character = getchar();
printf ("\nThe character you just entered is: %c\n",a_character);
getch();
return 0;
}

This code flushes the input buffer and allows you to grab the next character.
C d e f in e d c h a r a c t e r f u n c t i o n s
(uses #include <ctype.h>)

Function returns TRUE if argument is:


tolower returns the lowercase letter of its character argument
toupper returns the uppercase letter of its character argument
isalnum letter or digit
isalpha letter
iscntrl control character
isdigit digit
isgraph printable character, but not white space
islower lowercase letter
isprint printable character, including blank
ispunct printable character other than letter, digit, or white space
isspace space, newline, tab, form feed, carr
isupper uppercase letter

strings
• series of characters dealt with as a single unit
• can include letters, digits, and +, -, *, /, $, and other special characters
• enclosed in double quotes
• treated as an array of characters (char) is the ASCII value 0 (null or '\0')
follows the last meaningful character

The end of all strings are marked with null zero '\0' by C
You must account for this in your delcaration.
'x' - takes one byte of memory x
"x" - takes two bytes of memoryx\0

char month[10];
If the month "September" were stored in memory and the address of month it
would look like the following
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
S e p t e m b e r \0

*Remember amount of storage required is the number of non-null characters + 1

There are only 3 ways to assign string values:


1. Initialization
2. One character at a time.
3. Using C's strcpy ( ) function (use #include <string.h>

1. Initialization
char month[10] = "January";

month = "January"; /* This is illegal */

The only time an = sign can be used is in initialization.


2. One character at a time
#include <stdio.h>

void main()
{
char mystring[20];
clrscr();
mystring[0] = 'H';
mystring[1] = 'e';
mystring[2] = 'l';
mystring[3] = 'l';
mystring[4] = 'o';
mystring[5] = '\0';

printf ("%s",mystring);
printf ("\n");
printf ("%c",mystring[5]);
getch( );
}

Output
Hello

 (represents where the cursor is after the code is executed)


3. C's strcpy( ) function - must use #include <string.h>

strcpy (month, "April");

A r r a y s o f S tr in g s

If you want to store several strings under the same name, you must use an
array of strings. The are declared as follows:

char months [12][10];


data_type array_name [#elements][max_string_length + 1];

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
Memory would look like this after the values have been assigned.

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
[0] J a n u a r y \0
[1] F e b r u a r y \0
[2] M a r c h \0
[3] A p r I l \0
[4] M a y \0
[5] J u n e \0
[6] J u l y \0
[7] A u g u s t \0
[8] S e p t e m b e r \0
[9] O c t o b e r \0
[10] N o v e m b e r \0
[11] D e c e m b e r \0

I/O of strings

Function Call Write to Add '\n' ? Error Return


printf ("%s", string); stdout no negative
puts (str); stdout yes EOF
fprintf (outfile_ptr, "%s", string); output file no negative
fputs (str, outfile_ptr); output file no EOF
#include <stdio.h>
void main()
{
clrscr();
printf (" s %s\n","123456789");
printf ("15s%15s\n","123456789"); Output
printf ("20s%20s\n","123456789"); s 123456789
printf ("-12s %- 15s 123456789
12s\n","123456789"); 20s 123456789
getch(); -12s 123456789
}

#include <stdio.h>
void main()
{
/*Demostrates that the control string is just a string*/
char format [] = "%s\n";
char message [] = "hello";
clrscr();
printf (format, message);
getch();
}

Output
hello

F i l e s in C

Files defined

C performs input and output by streams. The standard input and output are
the keyboard and monitor respectively. Disk file streams work basically the
same way.

Text Files
• A text (stream) file is a collection of characters stored under the same
name in secondary memory (i.e. on a disk).
• Each line has 0-255 characters.
• The line is ended by a special character called an end of line character or
'\n'. A line is not a string because it is not terminated with '\0'.
• The CR-LF is translated into \n as it is being read from a file in a C
program.
• The \n is translated into CR-LF as it is being written to a file in a C
program.
• Data is sent one character at a time.

Record or Binary Files


• Data is written and read unchanged.
• Null and EOL characters have no special significance.
• Used for high data volume.
• Blocks of data are transferred by each I/O operation.
Indexed Files
• Allow for fast access to any record on a file.
• Each record is indexed and you don't have to go through all records to
access the record you are looking for.

File Names
You must name files when dealing with disk files. The DOS naming
convention must be used in Turbo C++. You will be working with files on
your floppy disk. Files should be named a:\filename.txt. (The file name must
be 8 characters or less and the extension must be 1 to 3 characters.)

possible file names


a:payroll.dat
a:words.rpt
a:report.rpt
a:timecard.in

Declaring Files
Before a file can be used for input or output, you must declare a file pointer
variable and give it a value. The stidio library function fopen prepares the file
for input or output before permitting access. A file pointer's data type is FILE
*. A declaration statement for a file to be used in C would look like one of
the following:
FILE * infile_ptr;
FILE * in_ptr;
FILE * out_ptr;
FILE * fp;
Opening a File stream
The file must be opened before a program can read from it or write to it. The
declarations above only declare space in memory. No value has been
assigned. The library function fopen() points to the file pointer and checks to
see if the filename is valid.

fopen requires 2 arguments. Both arguments are strings and can be displayed
in the function as literals or variables.

fp = fopen (filename, mode);/* both filename and mode have been declared and have values*/
infile_ptr = fopen ("a:students.txt","r");
out_ptr = fopen ("a:payroll.dat","w");

Errors
There are several possibilities for file error. A few of those are:
• The program is trying to write to a write-protected disk.
• The program is trying to read a file that is not on the disk.
• The pathname is incorrect.

If a file does not successfully open the value assigned is NULL. Code should
always be written after an fopen to verify that the file was opened correctly.

if (infile_ptr == NULL)
{
printf("students.txt does not exist.\n");
exit (1); /* terminates the program*/
}

The statements can be combined in one if statement:


if ((in_ptr= fopen ("clients.txt", "r")) = = NULL)
printf("File could not be opened.\n");
else
......

Modes
Values of Mode
Mode Meaning
r Open the file for reading only. If the file doesn't exist, fopen()
returns NULL.
w Open the file for writing. If a file of the specified name does not
exist, it is created. If the file already exists, existing data will be
erased.
a Open the file for appending. If a file of the specified name doesn't
exist, it is created. If the file already exists, new data is appended
(added) to the end of the file.
r+ Open the file for reading and writing. If a file of the specified name
does not exist, it is created. If the file already exists, new data is
added at the beginning of the file, overwriting existing data.
w+ Open the file for reading and writing. If a file of the specified name
does not exist, it is created. If the file already exists, it is
overwritten.
a+ Open the file for reading and appending. If a file of the specified
name does not exist, it is created. If the file already exists, new data
is appended to the end of the file.
wb Open a binary file for writing.
rb Open a binary file for reading.
Closing a File
The function fclose() is used to close a file when the program no longer needs
the use of the file.
fclose (infile_ptr);
fclose (out_ptr);
The file argument must be an opent file.

File I/O Text Files

Skip Stop
White reading
Function Call Read from Space Read Error
with return
before?
scanf ("%s", string); stdin yes word white space EOF
gets (string); stdin no line '\n' (discard) NULL
fscanf (infile_ptr, "%s", string); input file yes word white space EOF
fgets (str, n, infile_ptr); input file no line '\n' (keep), NULL
EOF, or n-1
characters

Function Call Write to Adds ‘\n’? Error return


printf (“%s”, string); stdout no negative
puts (string); stdout yes EOF
fprintf (outfile_fp, “%s”, string); output file no negative
fputs (string, outfile_fp); output file no EOF
fprintf - functions similar to printf. Output goes to a file, rather than the
monitor
fprintf (outfile_ptr, "Price = %.2f, tax = $%.2f\n", price, price * TAX_RATE);

fputs - writes data to a file


fputs (string, outfile_ptr);

fscanf - functions similar to scanf. Takes input from a specified file.


fscanf (infile_ptr, "%f", &price);

fgets - functions similar to gets. Output goes to a file, rather than the monitor.
fgets (str, 20, infile_fp);
/* fgets puts characters in the array str until it encounters and EOR or ‘\n’ or after reading
19 characters */

feof - file end of file detects the end of a file. If there is more data in the file a
value of zero (false) is returned.

if (feof (infile_ptr)) . . /* the body of the if statement executes if there is data in the file*/
-evaluates to true or false
File I/O Binary Files

fwrite - writes information to a file in binary


fwrite (&EmployeeRec, sizeof (employee_t),1, employ_ptr);
parameters are: 1. starting address of area in memory that contains the data
2. number of bytes in an item, such as the number of bytes in
a structure, to be written
3. number of data, such as the number of records
4. the file pointer

fread - used to read a record or an array of records all a once


fwrite (&EmployeeRec, sizeof (employee_t),1, employ_ptr);
parameters are: 1. starting address of area in memory to receive data
2. number of bytes in an item, such as the number of bytes in
a structure, to be read
3. number of data, such as the number of records to be read
4. the file pointer

feof - file end of file detects the end of a file. If there is more data in the file a
value of zero (false) is returned.

if (feof (infile_ptr)) . . /* the body of the if statement executes if there is data in the file*/
-evaluates to true or false
Recursion
A function that calls itself is said to be recursive. The ability to invoke itself
enables a recursive function to be repeated with different parameter values.
You can use recursion as an alternative to iteration (looping).

The recursive algorithms that we write will generally consist of an if


statement with the following form:

if this is a simple case


solve it
else
redefine the problem using recursion

Recursive factorial Funcion

/*
* Compute n! using a recursive definition
* Pre: n>=0
*/

int factorial (int n)


{
int ans;

if (n == 0)
ans = 1;
else
ans = n * factorial (n-1);
return (ans);
}
Trace of: fact = factorial (3);

fact = factorial (3);

n is 3

ans is 3 * factorial (2)


return (ans)

n is 2

ans is 2 * factorial (1)


return (ans)

n is 1

ans is 1 * factorial (0)


return (ans)

n is 0
ans is 1
return (ans)
Iterative factorial Function

/*
* Compute n! using an iteration
* Pre: n>=0
*/

int factorial (int n)


{
int i, product = 1;

/* Compute the product n x (n-1) x (n-2) x. . x 2 x 1 */


for (i=n; i>1; i=i-1)
{
product = product * i;
}
/*Return function result */
return (product);
}

You might also like