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

ch02 Problem Solving With C v2

Uploaded by

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

ch02 Problem Solving With C v2

Uploaded by

Manar Abutair
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

CHAPTER 2

Input,

Processing,

and Output

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Algorithm, Flowchart, and Pseudocode to Enter and Print Two Variables

0-8
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.1 Designing a Program

Flowchart for the pay calculating program

1-9
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.1 Designing a Program
Connector
• Flowchart Connector Symbol
– Use connectors to break a flowchart into two or
more smaller flowcharts, and placing them side-by-
side on the page.

Connector

1-10
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.1 Designing a Program
• Off-Page Connector Symbol
– To connect flowcharts on different pages

Connector

Connector

1-11
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.2 Output, Input, and Variables
Input, Processing, and Output of a Pay
Calculating program:

1-13
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.2 Output, Input, and Variables
IPO Chart: Describes the input, processing, and
output of a program.
Example:

1-14
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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 execute in order Figure 2-8 Output of Program 2-1

1-15
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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");

1-16
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-17
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.2 Output, Input, and Variables
In C:
– scanf is 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);

1-18
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-19
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-20
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-21
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.3 Variable Assignment & Calculations
In C:
The statement
price = 20;
Stores 20 inside variable price

1-22
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-23
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.3 Variable Assignment & Calculations
In C:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Note: there is NO exponent operator in C

1-24
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.3 Variable Assignment & Calculations
Priorities
()
* / %
+ -

1-25
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Evaluating a Mathematical Expression

0-26
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
• Declare Real grossPay

1-27
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types

• In C:
– Common Data Types
• char: single character
• int : an integer, no fraction
• float : real numbers

Note: NO string datatype

1-29
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types

• Pseudocode
– Declare Integer age
– Declare Real price
– Declare String test1
• C:
– int age;
– float price;
Note: NO string datatype

1-30
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types
For safety and to avoid logic errors, variables
may be initialized to 0 or some other value

1-31
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types

• In C:
• int age;
• float price;
age =0;
price =0;

OR declare and initialize at once


• int age =0;
• float price =0;

1-32
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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)

1-33
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types in C

Formatted Output in C:

1-34
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-35
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-36
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-37
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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");

1-38
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.4 Variable Declarations & Data Types in C

Formatted Output in C:
Characters: a A
Decimals: 1977
Preceding with blanks: 1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick: 10
A string

1-39
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
Some common escape sequences
printf( "Welcome ");
printf( "to ");
printf( "PSUT");

Output is
Welcome to PSUT

Note: all on the same line

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


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

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


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.

Copyright © 2016 Pearson Education, Inc., Hoboken NJ


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.
• The %d tells the program to expect a decimal integer.
• The %f tells the program to expect a float value.
float type indicates variable can be a
• The %c tells the program to expect a character
non-integer
• The %s tells the program to expect a string (array of characters).

1-43
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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
Constant Real INTEREST_RATE = 0.069

1-44
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-45
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-46
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-47
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-48
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-49
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Designing Your First Program
// Declare Variables
Declare Real r
Declare Real area

// 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-50
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Designing Your
First Program
Flowchart for program

1-51
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-52
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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;
} Copyright © 2016 Pearson Education, Inc., Hoboken NJ
1-53
2.8 Running your code on-line @
https://www.onlinegdb.com/online_c_compiler

1-54
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-55
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-56
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Another Simple Program with
constants
1 // Declare the variables
2 Declare Real fiveYears
3
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-57
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Another Simple Program with
constants

C program

1-58
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-59
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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 area
3. Output is produced.
– The circle’s area

1-60
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Designing Your First Program
// Declare Variables
Declare Real r
Declare Real area

// 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-61
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
2.8 Another Simple Program
Flowchart for program

1-62
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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-63
Copyright © 2016 Pearson Education, Inc., Hoboken NJ
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;
} Copyright © 2016 Pearson Education, Inc., Hoboken NJ
1-64
2.8 Running your code on-line @
https://www.onlinegdb.com/online_c_compiler

1-65
Copyright © 2016 Pearson Education, Inc., Hoboken NJ

You might also like