0% found this document useful (0 votes)
6 views

Chapter 9 Input, Output, And Processing

Uploaded by

alrashedheba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 9 Input, Output, And Processing

Uploaded by

alrashedheba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

CHAPTER 9- INPUT, OUTPUT, AND

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

Flowchart for the pay


calculating 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

Computer programs typically follow 3 steps


1. Input is received
2. Some process is performed on the input
3. Output is produced

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

Figure 2-7 The statements Figure 2-8 Output of


execute in order Program 2-1

1-15
Notes
16

Statement in C language normally ends with semicolon symbol ;


C is a case-sensitive language. For example A variable named salary is different
than a variable named Salary
C keywords are written in lower case. Examples:
• If, while, else, …

x = x + 2; it means “new value of x” = “old value of x” + 2


Notice that x++ means x = x + 1, also, x-- means x = x - 1
Notice that x+=5 means x = x + 5
Notice that x-=5 means x = x - 5
Notice that x*=5 means x = x * 5
Notice that x/=5 means x = x / 5
11/23/2024 Introduction to Computer Science
2.2 Output, Input, and Variables
In C:
 On way to show simple string output on screen is using
puts
Ex: puts (" Kate Austen");
A more powerful and flexible way to show output on
screen is using printf
Ex: printf (" Kate Austen");
“puts” function takes only one argument (parameter). It prints a string without variables.
Also, it adds a new line after printing
“printf” function takes only several argument (parameter). It can print a string with
variables. Also, it does not add a new line after printing

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

Table 2-1 Common math operators

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

 The C language was developed in the early 1970s by Dennis Ritchie at


Bell Laboratories.
 It was originally intended for writing operating systems and system
software—most of the UNIX operating system is written in C.
 Later, it became popular among programmers for several reasons:

❑ C has all the high-level instructions a structured high-level programming


language should have: it hides the hardware details from the programmer.
❑ C also has some low-level instructions that allow the programmer to access
the hardware directly and quickly:
❑ C is a very efficient language: its instructions are short. This conciseness
attracts programmers who want to write short programs.
1-29
2.4 Variable Declarations & Data Types

 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

 Declare String test1

 C:
 intage;
 float price;

Note: NO string datatype

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;

OR declare and initialize at once


 intage =0;
 float 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:

printf (“The value of the number is: %d”, num);

 The %d tells the program to print a decimal integer.


 The %f tells the program to print a float value.
 The %c tells the program to print a character
 The %s tells the program to print a string.(Sequence of characters)

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

Character Ascii Code


Formatted Output in C: Output of the previous code
Characters: a A
A 65
Decimals: 1977 B 66
Preceding with blanks: 1977 … …
Preceding with zeros: 0000001977 Z 90
Some different radices: 100 64 144 0x64 0144 a 97
floats: 3.14 +3e+000 3.141600E+000 b 98
Width trick: 10 … …
A string
z 122
|1 | 2|
char c1 = 'g‘, c2 = 'M';
// prints 'G', so it converts to Upper case
printf("%c",c1-32);

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

Note: all on the same line


Some common escape sequences
printf( "Weclome \nto \nPSUT\n");

Output is
Welcome
to
PSUT
Note: each on a single line

printf( "Welcome to \"PSUT\"\n");


Output is
Welcome to “PSUT”
Note: the print of “ around the word PSUT
Some common escape sequences

Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.


\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double-quote character in a string.
2.4 Variable Declarations & Data Types in C

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:

scanf (“%d”, &num);

 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

const float INTEREST_RATE = 0.069

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:

const float INTEREST_RATE = 0.069;

1-46
The mod operator and integer division

 Remember that when an integer is divided by an Division Result


integer, then integer division is applied
int x1 = 5 / 2; // x1 = 2
int x2 = 5 % 2; // x2 = 1 2
 In the case of dividing by powers of 10, you can
2 5
easily find the division result and remainder without
long division. Easy math
4
int x3 = 1234 / 10; // x3 = 123 -------
int x4 = 1234 % 10; // x4 = 4 1
int x5 = 1234 / 100; // x5 = 12
int x6 = 1234 % 100; // x6 = 34
Remainder Result

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

Figure 2-18 Program with the hand trace chart completed

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

 One line comment using //


Example:
// calculate the result

 Multiline comment using /* */


Example:
/*
Input numbers then
find their averege
*/

11/23/2024 Introduction to Computer Science


2.8 Designing Your First Program
Calculate the area of a circle

area = 3.14 * r2

Determine what is required for each phase of the


program:

1.What must be read as input?


2.What will be done with the input?
3.What will be the output?

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

The dashed rectangle add comments on separate


parts of flowchart

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

11/23/2024 Introduction to Computer Science


2.8 Running your code on-line @
https://www.onlinegdb.com/online_c_compiler

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

Determine what is required for each phase of the


program:

1.What must be read as input?


2.What will be done with the input?
3.What will be the output?

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.

Determine what is required for each phase of the


program:

1.What must be read as input?


2.What will be done with the input?
3.What will be the output?

1-63
2.8 Another Simple Program:
Calculating an Average
1. Input is received.
 The first test score.
 The second test score.

 Third test score

2. Some process is performed on the input.


 Calculate the average of the 3 test scores
3. Output is produced.
 The average of tests

1-64
2.8 Designing Your First Program
// Declare Variables
Declare Real testScore1
Declare Real testScore2
Declare Real testScore3
Psydocode
Declare Real scoreAverage

// Get test scores


Output "Please Enter test1 score"
Input testScore1
Output "Please Enter test2 score"
Input testScore2
Output "Please Enter test3 score"
Input testScore3

// calculate score average


Set scoreAverage = (testScore1+testScore1+testScore1)/3;

//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

You might also like