Chapter 9 Input, Output, And Processing
Chapter 9 Input, Output, And Processing
PROCESSING
11/23/2024 Chapter 9 1
Chapter Topics
2.1 Designing a Program
2.2 Output, Input, and Variables
2.3 Variable Assignment and Calculations
2.4 Variable Declarations and Data Types
2.5 Named Constants
2.6 Hand Tracing a Program
2.7 Documenting a Program
2.8 Designing Your First Program
2.9 C programming language: Introduction
1-2
2.1 Designing a Program
1. The first step in programming is designing –
flowcharts and pseudocode help with this
process.
2. Next, the code is written.
3. All code must be cleared of all syntax errors.
4. After the executable is created, it can be checked
for logic errors.
5. If logic errors exist, the program must be
debugged.
1-3
2.1 Designing a Program
The purpose of Programming Logic and Design is to
focus on Flowcharts and Pseudocode.
The design is the foundation of a good program.
Figure 2-1 The program development cycle
1-4
2.1 Designing a Program
Two steps in designing a program
1. Understand the tasks that the program is to
perform.
• Learning what the customer wants.
2. Determine the steps that must be taken to perform
the task.
• Create an algorithm, or step-by-step directions to
solve the problem.
• Use flowcharts and/or pseudocode to solve.
1-5
2.1 Designing a Program
Pseudocode
Fake code used as a model for programs
No syntax rules
Well written pseudocode can be easily translated
to actual code
Display “Enter the number of hours”
Input hours
Display “Enter the hourly pay rate”
Input payRate
Set grossPay = hours * payRate
Display “The gross pay is $”, grossPay
1-6
2.1 Designing a Program
Flowcharts
A diagram that graphically depicts the steps that
take place in a program
Terminator used
for start and stop
Parallelogram
used for input
and output
Rectangle used
for processes
1-7
Algorithm, Flowchart, and Pseudocode to Enter and Print Two Variables
0-8
2.1 Designing a Program
1-9
2.1 Designing a Program
Flowchart Connector Symbol Connector
Useconnectors to break a
flowchart into two or more
smaller flowcharts, and placing
them side-by-side on the page.
1-10 Connector
2.1 Designing a Program
Off-Page Connector Symbol
To connect flowcharts on different pages
Connector
Connector
1-11
2.2 Output, Input, and Variables
Output – data that is generated and displayed
Input – data that a program receives
Variables – storage locations in memory for data
1-12
2.2 Output, Input, and Variables
Input, Processing, and Output of a Pay Calculating
program:
1-13
2.2 Output, Input, and Variables
IPO Chart: Describes the input, processing, and output
of a program.
Example:
1-14
2.2 Output, Input, and Variables
Display is the keyword to show output to the screen
Sequence – lines execute in the order they appear
String Literals – a sequence of characters
1-15
Notes
16
1-17
2.2 Output, Input, and Variables
Input is the keyword to take values from the user of
the program
It is usually stored in variables
1-18
2.2 Output, Input, and Variables
In C:
scanfis used to take values from the user of the
program
Ex:if we have a variable named age of type integer, we
can use
scanf(“%d", &age);
Ex: You can read several variables using one scanf
scanf(“%d%f%f", &age, &salary, &weight);
1-19
2.2 Output, Input, and Variables
Programmers can define variable names following
certain rules
Must be one word, no spaces
Generally, punctuation characters are avoided
Generally, the first character cannot be a number
Name a variable something that indicates what may
be stored in it
camelCase is popular naming convention
1-20
2.2 Output, Input, and Variables
Example of proper variable names:
A2
_A
student_name
EmployeeSalary
Example of improper variable names:
2A
student-name
Employee Salary
1-21
2.3 Variable Assignment &
Calculations
Variable assignment does not always have to come
from user input, it can also be set through an
assignment statement
Set price = 20
1-22
2.3 Variable Assignment &
Calculations
In C:
The statement
price = 20;
Stores 20 inside variable price
-----------------------
In this statement, 5 and 2 are called operands
x=5+2
------------------------
Suppose: int d = 3.5, what is the value stored in d
Answer: 3 because d is ‘int’, so, the fraction part is
truncated (No rounding here)
1-23
2.3 Variable Assignment &
Calculations
Calculations are performed using math operators
The expression is normally stored in variables
Set sale = price – discount
1-24
2.3 Variable Assignment &
Calculations
In C:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Note: there is NO exponent operator in C
1-25
2.3 Variable Assignment &
Calculations
Priorities
Group 1: ()
Higher Priority Group 2: * / % Lower Priority
Group 3: + -
1-26
Evaluating a Mathematical Expression
Expressions are evaluated from left to right taking priority into consideration
Assume:
X=2
Y=3
Z=6
0-27
2.4 Variable Declarations & Data
Types
A variable declaration includes a variable’s name and
a variable’s data type
Data Type – defines the type of data you intend to
store in a variable
Integer – stores only whole numbers
Real – stores whole or decimal numbers
String – any series of characters
1-28
2.4 Variable Declarations & Data Types in C Programming Language
In C:
Common Data Types
char: single character
int : an integer, no fraction A note to remember:
float : real numbers int occupies 4 bytes
float occupies 4 bytes
Note: NO string datatype double occupies 8 bytes
char occupies 1 byte
1-30
2.4 Variable Declarations & Data Types
Pseudocode
Declare Integer age
Declare Real price
C:
intage;
float price;
1-31
2.4 Variable Declarations & Data
Types
For safety and to avoid logic errors, variables may be
initialized to 0 or some other value
1-32
2.4 Variable Declarations & Data Types
In C:
intage;
float price;
age =0;
price =0;
1-33
2.4 Variable Declarations & Data Types in C
Output variables in C:
The programmer can include the value of a variable or variables as part of the string.
The following displays the value of a variable at the end of a string:
The data type “double” is used to store floating point numbers. It is similar to “float”.
However, it can take wider range of values than the data type “float”
• How to read a “double” variable with “scanf”? Use the formatting specifier “lf”
• How to write a “double” variable with “printf”? Use the formatting specifier “f” or “lf”
1-34
2.4 Variable Declarations & Data Types in C
Formatted Output in C:
1-35
2.4 Variable Declarations & Data Types in C
Formatted Output in C:
The syntax for a format placeholder is
%[flags][width][.precision][length]type
1-36
2.4 Variable Declarations & Data Types in C
Formatted Output in C: flags
Character Description
- Left-align the output of this placeholder. (The
(minus) default is to right-align the output.)
Prepends a plus for positive signed-numeric types.
+ positive = +, negative = -.
(plus) (The default doesn't prepend anything in front of
positive numbers.)
Prepends a space for positive signed-numeric
types. positive = , negative = -. This flag is
ignored if the + flag exists.
(space)
(The default doesn't prepend anything in front of
positive numbers.)
When the 'width' option is specified, prepends
zeros for numeric types. (The default prepends
0
spaces.)
(zero)
For example, printf("%2X",3) produces 3,
while printf("%04X",3) produces in 0003.
1-37
2.4 Variable Declarations & Data Types in C
Formatted Output in C:
The Width field specifies a minimum number of characters to output, and is
typically used to pad fixed-width fields in tabulated output, where the fields
would otherwise be smaller, although it does not cause truncation of
oversized fields.
The width field may be omitted, or a numeric integer value, or a dynamic value when
passed as another argument when indicated by an asterisk *. For example, printf("%*d", 5,
10) will result in 10 being printed, with a total width of 5 characters.
Precision field, for floating point numeric types, it specifies the number of
digits to the right of the decimal point that the output should be rounded.
The precision field may be omitted, or a numeric integer value, or a dynamic value when
passed as another argument when indicated by an asterisk *. For example,
printf("%.3f", 55.2319) will result in 55.232 being printed.
1-38
2.4 Variable Declarations & Data Types in C
Formatted Output in C:
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d \n", 1977);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radices: %d %x %o %#x %#o \n",
100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
printf( "|%-5d|%5d|\n", 1, 2 );
1-39
2.4 Variable Declarations & Data Types in C
1-40
// prints 'm', so it converts to Lower case
printf("%c",c2+32);
Some common escape sequences
printf( "Welcome ");
printf( "to ");
printf( "PSUT");
Output is
Welcome to PSUT
Output is
Welcome
to
PSUT
Note: each on a single line
Input variables in C:
The C language has several input functions. For example, the scanf function
reads data from the keyboard, formats it, and stores it in a variable. The
following is an example:
When the program encounters this instruction, it waits for the user to type an
integer. It then stores the value in the variable num. Float type
The %d tells the program to expect a decimal integer. indicate variable
The %f tells the program to expect a float value. can be a real
The %c tells the program to expect a character number
The %s tells the program to expect a string (array of characters).
1-44
2.5 Named Constants
A named constant is a name that represents a value
that cannot be changed
Makes programs more self explanatory
If a change to the value occurs, it only has to be
modified in one place
1-45
2.5 Named Constants
Constants in C:
Constant, like a variable, is a named location that can store a value, but the
value cannot be changed after it has been defined at the beginning of the
program.
For example, in a C program, the tax rate can be defined at the beginning
and used during the program:
1-46
The mod operator and integer division
1-47
2.6 Hand Tracing a Program
Hand tracing is a simple debugging process for
locating hard to find errors in a program
Involves creating a chart with a column for each
variable, and a row for each line of code
1-48
2.7 Documenting a Program
External documentation describes aspects of the
program for the user, sometimes written by a
technical writer
Internal documentation explains how parts of the
program works for the programmer, also known
as comments
// comments are often distinguished within
// the program with line comments
1-49
Comments in C language
50
area = 3.14 * r2
1-51
2.8 Designing Your First Program
1. Input is received.
The radius
2. Some process is performed on the input.
Calculate the area
3. Output is produced.
The circle’s area
1-52
2.8 Designing Your First Program
// Declare Variables
Declare Real r
Declare Real area Psydocode
// Get radius
Output "Please Enter the radius"
Input r
// calculate area
Set area = 3.14 * r ^2
//Display result
Display "The area is " , area
1-53
2.8 Designing Your
First Program
Flowchart for program
1-54
2.8 Designing Your First Program
Summary
Input
Determine data needed for input
Choose variables to store the input
Process
Determine calculations to be performed
Choose variables to store the calculations
Output
Determine what output the program will display
Usually the results of the program’s calculations
1-55
2.8 Your First Program in C
#include <stdio.h>
int main() {
// Declare Variables
double r;
double area;
// Get radius
printf( "Please Enter the raduis\n" );
scanf("%f",&r);
// calculate area
area = 3.14 * r *r;
// Display result
printf( "The area is %f" ,area);
return 0;
}
1-56
Useful Keyboard Shortcuts
57
Shortcut Usage
Shift + Arrows Selection
Ctrl + a Select all
Ctrl + x Cut
Ctrl + c Copy
Ctrl + v Paste
Ctrl + z Undo
Ctrl + y Redo
Tab after selection Move all selected lines one tab forward
shift + tab after selection Move all selected lines one tab backward
1-58
2.8 Another Simple Program with
constants
Scientists have determined that the world’s ocean levels are
currently rising at about 1.5 millimeters
per year. Write a program to display the following:
● The number of millimeters that the oceans will rise in five years
1-59
2.8 Another Simple Program with
constants
1. Input is received.
No input
2. Some process is performed on the input.
Calculate the rise
3. Output is produced.
The number of millimeters that the oceans will rise in
five years
1-60
2.8 Another Simple Program with
constants
1 // Declare the variables
2 Declare Real fiveYears
3
Psydocode
4 // Create a constant for the yearly rise
5 Constant Real YEARLY_RISE = 1.5
6
7 // Display the amount of rise in five years
8 Set fiveYears = YEARLY_RISE * 5
9 Display "The ocean levels will rise ", fiveYears,
10 " millimeters in five years."
11
1-61
2.8 Another Simple Program with
constants
C program
#include <stdio.h>
int main(){
float fiveYears;
const float YEARLY_RISE = 1.5;
fiveYears = 5 * 1.5;
printf("The ocean levels will rise %f millimeters in five years.",fiveYears);
return 0;
}
1-62
2.8 Another Simple Program:
Calculating an Average
Suppose you have taken three tests in your computer
science class, write a program that will display the
average of the test scores.
1-63
2.8 Another Simple Program:
Calculating an Average
1. Input is received.
The first test score.
The second test score.
1-64
2.8 Designing Your First Program
// Declare Variables
Declare Real testScore1
Declare Real testScore2
Declare Real testScore3
Psydocode
Declare Real scoreAverage
//Display result
Display “Average of your three test scores = " , scoreAverage
1-65
2.8 Designing Your First Program
Summary
Input
Determine data needed for input
Choose variables to store the input
Process
Determine calculations to be performed
Choose variables to store the calculations
Output
Determine what output the program will display
Usually the results of the program’s calculations
1-66
2.8 Your First Program in C
#include <stdio.h>
int main(){
// Declare Variables
float testScore1;
float testScore2;
float testScore3;
float scoreAverage;
// Get test scores
printf("Please Enter test1 score");
scanf("%f",&testScore1);
printf("Please Enter test2 score");
scanf("%f",&testScore2);
printf("Please Enter test3 score");
scanf("%f",&testScore3);
// calculate score average
scoreAverage = (testScore1+testScore2+testScore3)/3;
//Display result
printf("Average of your three test scores = %f",scoreAverage);
1-67 return 0;
}
2.8 Running your code on-line @
https://www.onlinegdb.com/online_c_compiler
1-68