Uploaded by Angel so

Allchaps

advertisement
IE1005 From Computational
Thinking to Programming
Lesson 1
Computers & Programming
(Reference: Harry H. Cheng, Chapter 1)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
1-1
What is a Computer?
Instructions &
Data Storage
in Memory
Input
Processing
Output
Keyword: programmable
1-2
Computer Systems
Two main components:
1. Hardware: monitor,
keyboard, etc.
2. Software: Collections of
instructions for the
computer to execute
(programs).
Personal Computer (PC)
1-3
Hardware Components
• Main Memory (Primary Storage)
- on Main Board
• The Central Processing Unit (CPU)
- on Main Board
• Secondary Storage (hard disks, thumb drives)
- outside of Main Board
• Input Devices
• Output Devices
1-4
Main Memory (1)
To store
• instructions to be executed,
• data to be manipulated,
• processing results.
Information is stored in bits--short for
binary digits (0 or 1, off or on).
These bits are organized into groups of 8 bits
(1 byte) called memory cells.
1-5
Main Memory (2)
Think of main memory as a collection of boxes
(cells). Each cell can hold 1 byte of data and
has a unique address (an integer value).
Address
Contents
100000
100001
100002
100003
3.14159
100004
H
100005
I
‘Logical’ Cell
Size is
greater than
1 byte
Cell Size of
1 byte each
1-6
Main Memory (3)
As each memory cell can be accessed directly,
main memory is also known as Random
Access Memory (RAM).
The size is measured in kilobytes (KB)
megabytes (MB), or gigabytes (GB):
1 KB = 210 bytes = 1024 bytes
1 MB = 220 bytes = 1024 KB
1 GB = 230 bytes = 1024 MB
* Note: the above conversion only applies
when referring to memory size
1-7
Main Memory (4)
RAM is high-speed memory for storing
instructions and data temporarily.
However, the most common type of RAM has
two disadvantages:
1. It is volatile (i.e. it loses all data when
power is cut off).
2. It is expensive.
We need cheap and permanent storage:
disks, tapes, etc.
1-8
Read-Only Memory
ROM (Read-Only Memory) stores data
permanently. Usually, they can only be read from
but not written to. The data are physically
encoded in the circuit, so they cannot be modified
easily, if at all.
Usually used to store boot-up (start-up)
instructions, i.e., the initial instructions that run
when the computer is powered on.
It is also used for storing other
critical system instructions.
1-9
CPU Components
Registers
M
Control
Unit
ALU
Data,
Address,
Control
Buses
e
m
o
r
y
1-10
ALU
The ALU (Arithmetic Logic Unit) is a
fundamental component of the CPU, and it
can perform:
• Arithmetic operations (+, -, x, )
• Logical operations (COMPARE, AND, OR,
NOT, etc.)
1-11
Registers & Control Unit
Control Unit:
It controls flow of instructions and data from
and to memory, and inside the CPU. It tells
the ALU what operation to perform on the
data.
Registers:
These are memory cells in the CPU that allow
very rapid access of instructions and data by
the ALU and the Control Unit.
1-12
Secondary Storage & I/O Devices
For cheap and permanent storage of data.
Examples:
• Hard disks
• Flash drives
• CD-R, CD-RW, DVD, DVD-RW
• Magnetic tapes
Input Devices: keyboard, mouse, microphone
Output Devices: monitor, printer, speaker
1-13
Flash Memory
Flash memory is a type of non-volatile
memory that can be erased and
reprogrammed.
It is used in memory cards (e.g. for digital
cameras and cell phones) and USB flash
drives (thumb drive, pen drive, USB stick, …)
for storage and transfer of data between
digital devices.
1-14
Interaction Between CPU,
RAM and Hard Disk
2a.One instruction and associated
data are fetched from RAM to
CPU at any one time
CPU
2b.ALU computes and stores
intermediate results in
registers in CPU
2c.Final
results
are
transferred back to
RAM
Example: Executing a
program on a data file
B
U
S
RAM
3a.Final results are
either shown on
screen or saved
to Hard Disk
3b.Program and data
released to Hard
Disk
when
terminated
1. Program and data
transferred to RAM
Hard Disk
1-15
System Software
Two major types of software: (i) System
Software; (ii) Application Software.
System Software sub-categories:
1. Operating Systems (OS)
Manage resources of a computer. Most
important software.
2. Utility Programs
e.g. programs to format disks, compress
data, etc.
3. Software Development Tools
e.g. compilers, linkers, etc.
1-16
Operating System (OS)
• Loaded into RAM when computer is started (a
process known as booting the computer).
• Controls access to computer
• Enforces security and privacy of files
• Allocates/manages memory, CPU resources, etc.
• An OS shields the user from the complexity of
computer hardware.
• Examples: Windows 2000/2003/XP/Vista/7/8/10/11,
UNIX (Linux), Mac OS X
1-17
Application Software
Software that are very useful to most users.
Examples are:
•
•
•
•
•
Word Processors (Microsoft Word)
Spreadsheets (Excel)
Graphics (Photoshop)
World Wide Web (WWW) Browsers
(Internet Explorer, Microsoft Edge, Mozilla
Firefox, Opera, Safari, Google Chrome)
Computer-Aided Design (CAD) (AutoCAD)
1-18
What is Programming?
The computer needs detailed and exact
instructions to carry out the steps needed to
solve a problem.
These instructions must be coded (i.e. written)
using a programming language and they
form a computer program.
1-19
Programming Languages
A programming language is an artificial
language with a set of special words
(keywords) and a set of rules (syntax or
grammar).
Two main categories:
(1) Low-level languages
Machine language, Assembly language
(2) High-level languages
C, C++, Java
1-20
Machine Language
Each CPU has a set of instructions designed
and manufactured into it.
These machine instructions are different for
CPUs from different chip design companies.
They consist of sequences of 0s and 1s.
The only language "understood" by the
computer. Machine language statements look
like:
100100 0000 010001
100110 0000 010010
100010 0000 010011
Difficult to use for humans!
1-21
High-Level Languages
Most popular because
• They use English words (such as PRINT,
READ, WRITE, etc.) Need a translator
(compiler) to convert the statements into
machine language.
• The programs are portable. High-level
languages are not tied to any particular CPU
in any machine.
• Programs are much easier to read,
understand and modify for humans!
1-22
High-Level Languages (Examples)
There are numerous high-level languages.
Common ones are:
•
•
•
•
•
•
FORTRAN (Formula Translation)
C, C++
Java
C# (C Sharp)
Perl
Python
1-23
Language Standard
Each major high-level language has a
language standard that describes its syntax
(grammar).
The syntax rules are very strict. Deviations
will result in syntax errors.
1-24
The Programming Process
1. Problem Solving:
(a) Problem Specification
(b) Problem Analysis
(c) Algorithmic Design (Solution Procedures)
2. Implementation
(a) Coding
(b) Testing
(c) Maintenance
1-25
Algorithm
An algorithm is a set of precisely stated, finite
sequence of executable steps for solving a
problem.
Finding a suitable algorithm is often the most
difficult part of the problem solving process.
An algorithm is usually written using informal
English-like statements known as pseudocode*.
Another representation is using a graphical
flowchart (not covered here).
*
You will learn more in IE2108 DATA STRUCTURES
& ALGORITHMS
1-26
Pseudocode Example 1
To calculate the area of a circle, given its radius:
INPUT radius
circle_area=3.14159*radius*radius
OUTPUT circle_area
Note: We can use words like GET or READ, etc.
instead of INPUT; similarly, we can also use
WRITE, PRINT, etc. for OUTPUT.
1-27
Pseudocode Example 2a
To find the larger of two user-input numbers,
number1 and number2:
INPUT number1, number2
number1 is greater,
IF number1 > number2 THEN If
max assumes value of
SET max = number1
number1
ELSE
Otherwise, max
SET max = number2
assumes value
END IF
of number2
OUTPUT max
1-28
Pseudocode Example 2b
The following is an alternative (and better)
form for finding the larger of two user-input
numbers.
INPUT number1, number2
SET max = number1
IF number2 > max THEN
SET max = number2
END IF
OUTPUT max
Set number1 as the
maximum value first
If number2 is greater,
then replace number1
as the maximum value
1-29
Pseudocode Example 3
To calculate and display the distances travelled by a
particle falling under gravity from an initial time 0 to a
given point in time. Assume zero initial velocity.
Formula is
s=1/2*a*t*t, where a = acceleration, t = time
s = distance travelled
The results are to be displayed in a table form:
Time Elapsed
Distance Travelled
---------------------------------0.00
0.00
0.50
1.23
1.00
4.90
1.50
11.03
2.00
19.60
max_time = 2.00, interval = 0.50, initial time = 0
Table Title
1-30
Pseudocode Example 3
INPUT max_time, interval
SET accel = 9.8, time = 0
Compute and
PRINT Table Title
display as long as
WHILE time <= max_time time ≤ max_time
Compute and
display time and
associated
distance travelled
distance = 0.5*accel*time*time
PRINT time, distance
SET time = time + interval
Increment time, for computation and display at other time values
1-31
END WHILE
Edit, Compile & Link Cycle
1. Create the source program (simple.c) by
typing program statements using a
program editor.
2. Use a compiler to translate the source
program into machine language. This
produces an object file (simple.o) if there
are no syntax errors. If there are errors, we
need to go back to the editor to fix these
errors.
3. Use a linker to link this object file with
other necessary components (i.e. libraries)
to get a stand-alone executable file
(simple.exe).
1-32
Edit, Compile & Link Cycle
These steps are usually carried out within an
IDE (Integrated Development Environment).
An IDE typically contains an editor, a compiler,
a linker, a debugger (for helping to find and
correct programming errors), and other
components.
We will use CodeBlocks in this course.
1-33
Errors (Bugs) in Programs
A bug is an error in software/hardware.
Correcting a bug is known as debugging. The
following types of errors may appear in our
programs:
• Syntax Errors: errors in grammar
• Logical Errors: errors due to the use of
wrong algorithm, wrong formula, etc.
• Runtime Errors: errors that occur when a
program is being executed. An example is
division by a variable value which turns out to
be zero.
* Compiler can only help you catch
Syntax Errors
1-34
Summary
1. Computer hardware components
•
Main memory, CPU, secondary storage
2. Computer software
•
•
•
•
•
System and Application software
Programming Language: Low Level and
High Level
Algorithm and Pseudocode
Edit, Compile and Link Cycle
Errors (bugs)
1-35
IE1005 From Computational
Thinking to Programming
Lesson 2
An Overview of C
(Reference: Harry H. Cheng, Chapter 2, 3 and 7)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
2-1
“Be Prepared, Give Feedback”
Alternative Place for Practice
At Home
– **Get CodeBlocks (Free from
http://www.codeblocks.org/downloads/binaries/
– Get Chide (Free from
www.softintegration.com/docs/ch/chide/)
– Get Microsoft Visual Studio (Free from
https://visualstudio.microsoft.com/students/)
In School
– Your Tutorial/Practical Laboratory
(check availability with Lab Tech)
2-2
2
History of C
C was designed by Dennis
Ritchie of the Bell Laboratories in
the early 1970s for writing
systems software for the UNIX
OS.
C was evolved from B!
B was created from BCPL (Basic
Combined Programming Language)
which was designed by Martin
Richards (Cambridge) in 1967.
2-3
ANSI C
In 1989, the American National Standards
Institute (ANSI) approved a standard for C
known as ANSI C, or Standard C (known as
C89). It was also accepted as an ISO standard
and is known as ANSI/ISO C.
New standard: C11
ANSI C is a mature, important, general purpose
language that is widely available.
We will use ANSI C in this course.
2-4
C’s Descendents & Relatives:
• C++ : a superset of C
C with Object-Oriented extensions
• Java (created by Sun Microsystems)
- Very popular language
Uses a lot of C/C++ syntax
Internet & platform-independent programming
• C# : for Microsoft’s .NET platform
2-5
Variables, Identifiers & Keywords
Variable – a named data storage location in
RAM.
Identifier – name of a variable.
Keywords – predefined words with special
meanings, e.g. int, void, float
Keyword definitions cannot be changed.
Full list of Keywords for C89 (a total of 32
words) is given in the next slide.
2-6
C89 Keywords
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
Note: Not all keywords will be covered in this
course.
2-7
Rules for naming identifiers:
• It can contain letters, digits, and the
underscore character (_).
• It must start with a letter or the underscore.
• It is case sensitive.
• C keywords cannot be used.
Valid names: sum, number_1, exam_mark
Invalid names: 1st, metric#, exam mark,
float
space NOT allowed
Always choose meaningful names.
2-8
Constants
C has several types of constants:
• Integer constants: -25, 1000
• Floating-point constants:
3.14159265, -1.5E-2, 1.5e-2
• Character constants which are enclosed
within a pair of single quotation marks:
'A', '1', '$'
• String constants which are enclosed within
a pair of double quotation marks:
"This is a string constant."
2-9
Expressions & Statements
An expression consists of variables, constants,
and operators (such as +, -, *, /, etc) written
according to the syntax of the C language.
Some examples of C expressions:
a+b,
x+y*z/w,
cos(x)
In C, every expression has a value of a certain
type that can be assigned to a variable:
e.g. for a+b, a=1.2, b=2.3, and a+b=3.5 can be
assigned to variable c
C statements can be formed from expressions:
2-10
e.g. y = a+b*cos(x);
Program 2.1
/* This C program will print a message
on the computer screen. */
#include <stdio.h>
int main(void)
{ printf("This is my first program.\n");
printf("Programming is easy.");
return 0;
}
Screen Output:
2-11
Dissection of Program 2.1:
/* This is a comment */
• You can insert comments between /* and */.
• Computer will ignore all the comment
statements.
• It is important to insert comments at suitable
places in the program to explain what the
statements are doing. This is part of program
documentation.
2-12
Dissection(continued):
#include <stdio.h>
stdio.h = standard input-output header file
• A part of all C development environments.
• Provides functions to perform I/O operations
(such as printf here).
• # sign : preprocessor directive. Tells the
preprocessor to do something before compiling.
• #include <stdio.h> tells preprocessor to
include the contents of the file stdio.h into our
program before compilation.
2-13
preprocessor is a program that processes its input data to produce output that is used as input to another
program.
Dissection (continued):
int main(void)
• Starting point for program execution.
• One and only one main() function.
• The parentheses after main enclose a definition
of the input data to be provided to main() when it
starts executing. The word void means that no
input data needs to be provided to main().
What is a C function?
• A collection of statements for doing a specific task.
• Can call the function name to execute the
statements
2-14
Dissection (continued):
int main(void)
• A mathematical function has at least one
argument (input data) whereas a C function
may have 0 or more arguments.
• void means the function has no argument.
• A function may also return an output value to
its caller.
• Here main() returns an integer value to the
operating system.
• int and void are C keywords.
2-15
Dissection (continued):
printf("This is my first program.\n");
• printf() is a function with arguments.
• For the above, "This is my first program.\n"
is the argument.
•It sends the string constant, enclosed by " and ":
This is my first program.
to the screen.
• It is provided by <stdio.h>.
2-16
Dissection (continued):
\n : newline character. Moves screen cursor to
beginning of next line.
Suppose it is not used in printf():
printf("This is my first program. ");
printf("Programming is easy.");
Output (Both sentences will be in a single line):
This is my first program. Programming is easy.
2-17
Dissection (continued):
The semi-colon indicates the end of a C
statement.
;
return 0;
This means main() returns the value 0 to the
caller (the Operating System in this case). The
return value is not used in this course. Treat the
statement as a requirement under ANSI/ISO C.
{ } marks the beginning and end of a block of
statements (in this case, the function body).
2-18
Program 2.2
/* This program adds two integers. */
#include <stdio.h>
int main(void)
{ int number1, number2, sum;
number1 = 20;
number2 = 30;
sum = number1 + number2;
printf("The sum of %d and %d is %d.",
number1, number2, sum);
return 0;
}
2-19
Declaration of Variables
The line:
int number1, number2, sum;
is called a declaration statement.
The purpose is to ask the computer to reserve
3 memory locations to store values. These
locations are called number1, number2,
sum and they will be used to store integer
numbers (numbers without a fractional part,
or without a decimal point). The statement
declares 3 integer variables.
Syntax: data_type variable_name
2-20
Sum = number1
+ number2;
number1 = 20;
number2 = 30;
20
30
50
number1
number2
sum
printf("The sum of %d and %d is %d.",
number1, number2, sum);
Output:
The sum of 20 and 30 is 50.
2-21
Conversion/Format Specifiers
printf("The sum of %d and %d is %d.",
number1, number2, sum);
When displaying output, we need to tell the
computer what and how to output. Since our
output are integers, we use the conversion or
format specifier %d (to indicate integer format)
which is also described as a placeholder.
Each integer value (from number1, number2,
sum) requires one %d and each value will be
displayed at the corresponding location of the
placeholder in the order specified.
2-22
Program 2.3
/* Calculate volume of a cylinder */
#include <stdio.h>
int main(void)
{
float radius, height, volume;
printf("This program computes the
volume of a cylinder.\n\n");
printf("Input the radius => ");
scanf("%f", &radius);
2-23
Program 2.3 (Continued):
printf("Input the height => ");
scanf("%f", &height);
/* Compute the volume. */
volume = 3.14159*radius*radius*height;
printf("The volume is %f.", volume);
return 0;
}
2-24
3 new items:
(1) float radius, height, volume;
The keyword float is for declaring variables
which take floating-point values (numbers with a
decimal point). Conversion specifier is %f.
(2) scanf("%f", &radius);
scanf() is for capturing user input.
Syntax: scanf ("format_specifier", address_of_variable)
Note the input will be represented as a float (%f) value
and ampersand (&)character in front of radius means
value will be stored at a location named by radius 2-25
(3) The asterisk (*) denotes
multiplication.
Screen Output:
This program computes the volume of a
cylinder.
Input the radius => 1.5
Input the height => 5
The volume is 35.342888.
Entered by
user
Default: 6 decimal places.
2-26
Program 2.4
/* Solution of a*x*x + b*x + c = 0 */
#include <stdio.h>
#include <math.h>
int main(void)
{
double a, b, c, root1, root2;
printf("Input the coefficient a => ");
scanf("%lf", &a);
printf("Input the coefficient b => ");
scanf("%lf", &b);
printf("Input the coefficient c => ");
scanf("%lf", &c);
2-27
Program 2.4 (Continued)
/* Compute the roots. */
root1 = (- b + sqrt(b*b-4*a*c))/(2*a);
root2 = (- b - sqrt(b*b-4*a*c))/(2*a);
printf("The first root is %8.3f\n", root1);
printf("The second root is %8.3f\n", root2);
return 0;
}
2-28
New items
#include <math.h>
This provides the sqrt() function.
double a, b, c, root1, root2;
The double data type is similar to float but it
represents real numbers with higher precision
and a much wider range.
The conversion specifier in scanf() is now
%lf.
2-29
Suppose we input:
a = 2, b = 6, c = 1
There are 2 space characters
+
The remaining 6 characters
are ‘-’, ‘0’, ‘.’, ‘1’, ‘7’ and ’7’
ll
Screen Output:
The first root is
The second root is
–0.177
–2.823
Thus, there are
8 characters in
total
%8.3f gives 3 decimal places and the output is
allocated (a minimum of) 8 character slots.
Note that this is for formatting of output; do
not write statements such as
scanf("%8.3f", &a);
scanf("%f\n", &a);
2-30
Program Statement Layout
It is important that you type your program so
that the structure is clear. Use indentations
(i.e., leave a space before the first word of
each line of statement within a function body).
int main(void)
{
float radius, height, volume;
printf("This program . . .");
printf("Input the radius => ");
scanf("%f", &radius);
2-31
Single and Multi-Line Comments
/* This is a
multi-line
comment
*/
// This is a single line comment
(new in C99, supported by CodeBlocks too)
2-32
Note about Program 2.4
Program 2.4 fails if the user enters 0 for the
coefficient a.
We should test the value of a given by the
user to see whether it is zero or not, before
proceeding with the actual computation.
This is done using the if-else decision
making structure as in Program 2.5. (Refer to
Lesson 6 for a more detailed discussion on ifelse.)
2-33
Program 2.5 (quadratic equation)
if (a == 0)
/* If coefficient a is
zero, do the below. Note the double
equal or == sign */
{
printf("You have entered a = 0.\n");
printf("Only one root: %8.3f", -c/b);
}
else //otherwise do the below
{
root1 = (-b + sqrt (…))/(2*a);
. . .
}
2-34
Notes on Program 2.5
Note that the double equal or == sign is used
for checking equality of two values. This will
be discussed again in Lesson 6.
if statement has one pair of braces or { } to
enclose its associated block of statements.
Similarly, else statement also has another
pair of braces or { } to enclose its associated
block of statements.
2-35
Pseudocode Example 3 (Lesson 1)
INPUT max_time, interval
SET accel = 9.8, time = 0
PRINT Table Title
WHILE time <= max_time
distance = 0.5*accel*time*time
OUTPUT time, distance
SET time = time + interval
END WHILE
We’ll implement a version of this algorithm
without user-input in the next example.
2-36
Program 2.6
/* Distance travelled by a particle falling under
gravity. Initial velocity = 0 */
#include <stdio.h>
int main(void)
{
double time = 0, max_time = 4, interval = 0.5,
acceleration = 9.8, distance;
printf("Time Elapsed Distance Travelled\n" );
printf("--------------------------------\n" );
2-37
Program 2.6
while (time <= max_time)
{
distance = 0.5*acceleration*time*time;
printf("%8.2f %8.2f\n", time, distance);
time = time + interval;
}
return 0;
}
2-38
Screen Output
Time Elapsed
Distance Travelled
---------------------------------0.00
0.00
0.50
1.23
1.00
4.90
1.50
11.03
2.00
19.60
2.50
30.63
3.00
44.10
3.50
60.03
4.00
78.40
2-39
New Concept: the while loop
while (time <= max_time)
{ . . .
}
The loop body (The part enclosed within the
braces or {}) will be executed as long as the
condition (time <= max_time) is TRUE.
Loops will be discussed in detail in Lesson 7.
2-40
Exercises
(1) Modify the program so that max_time
and interval are both user-input values
(as specified in the algorithm).
(2) Modify the program assuming that the
particle has an initial velocity u that will
be entered by the user. The formula is
1 2
s  ut  at
2
You will have a chance to do the above in
Practical Lesson 3.
2-41
Preprocessor Directives & Macros
# indicates a preprocessor directive.
Example: #include <stdio.h>
There is another preprocessor directive:
#define that is frequently used to define
constants. It is also said to define a macro.
Example:
#define PI 3.14159
#define GST 0.07
2-42
Preprocessor Directives & Macros
The PI and GST defined previously are also
known as symbolic constants and the names
are usually typed in capital letters.
General Form:
#define macro_name replacement_text
This is purely a text replacement command. The
preprocessor will replace the macro_name in
our program with the replacement_text. If we
use the symbolic constant PI, Program 2.3 is
modified as shown in the next slide:
2-43
Program 2.3 (Using a macro)
#include <stdio.h>
#define PI 3.14159
int main(void)
{ . . .
/* Compute the volume. */
volume = PI*radius*radius*height;
Note: During preprocessing, the computer will replace
all occurrences of PI (except those in comments and
quoted strings) with 3.14159. Hence the statement for
the calculation of volume will be changed by the
preprocessor to:
volume = 3.14159*radius*radius*height;
2-44
Preprocessor Directives & Macros
Advantages:
(1) Macros may make programs easier to
understand because a meaningful name used
(like PI, GST) is easier to understand than a
number.
(2) If there is a need to change the value, we
only need to change the #define
statement. This is very useful if the same
constant is used many, many times in a
program.
2-45
Parameterized Macros
Macros can have input parameters, like Functions
which you will learn later. General Form:
#define macro_name(parameters) replacement_text
Example:
#define CIRCLE_AREA(r) (3.14159*(r)*(r))
This means CIRCLE_AREA(r) will be replaced by
(3.14159*(r)*(r)), where the value of r is provided
by you.
r = 2.5 here
In other words, when you write the below statement:
volume = CIRCLE_AREA(2.5)*height;
This statement will become
volume = (3.14159*(2.5)*(2.5))*height;
2-46
after preprocessing.
Parameterized Macros
Why are there so many parentheses (brackets)?
#define CIRCLE_AREA(r) (3.14159*(r)*(r))
This is to guard against mistakes when the parameter r
is to be replaced by another expression such as (2+a).
E.g. We now want to calculate the area of a circle with
radius as (2+a). We assign a = 1.
Using the above macro, CIRCLE_AREA(2+a)
will give (3.14159*(2+a)*(2+a))
Since a = 1, the result will be (3.14159*(2+1)*(2+1))
= (3.14159*(3)*(3)) Area of circle with radius 2-47
(2+a) where a=1
Parameterized Macros
Let’s now see what happens when there are no
parentheses () enclosing r. This means:
#define CIRCLE_AREA(r) (3.14159*r*r)
To calculate the area of a circle with radius as (2+a),
where a = 1, using the above macro,
CIRCLE_AREA(2+a) will give (3.14159*2+a*2+a)
Since a = 1, the result will be (3.14159*2+1*2+1)
= (6.28318+2+1)
NOT the area of circle with
radius (2+a) where a=1
*
is
at
a
higher
precedence level and will
be executed ahead of +
2-48
Summary
1. Terminology
• Variables, identifiers, keywords
• Constants
• Expression and statement
2. Six Examples of C program that illustrate:
• Printing to computer screen
• Using variables and performing calculations
• Getting input from user
• Using C mathematical functions
• Using if-else structure
• Using while-loop structure
3. Preprocessor Directives and Macros
2-49
IE1005 From Computational
Thinking to Programming
Lesson 3
Fundamental Data Types
(Reference: Harry H. Cheng, Chapter 3)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
3-1
Special Announcement
Please stick to your registered Tutorial Group / Class,
and do not attend another class.
This is because the Computer Laboratory has just
enough computers for the registered students.
Also, you can only take the Continual Assessments in
your registered class.
**Please check your NTU e-mailbox regularly as your
tutor/lecturers will communicate with you via your NTU
email account.
3-2
We seek your cooperation in this. Thank you very much!
Recap: Lecture Lesson 2
Program Structure
/* Comment */
#include <stdio.h>
int main (void)
{
D Declaration of variables
I Initialization of variables
/* load header files*/
/* main function */
/* name, type, size of variables*/
/* give values to variables*/
C Data processing and Computation /* operation and
expression*/
O Termination and Output of result
return 0
/* printf(“xxx”); */
/* exit a function */
}
3-3
Binary Number System
Computer’s basic design depends on two states:
off and on (symbolized as 0 and 1) in the CPU,
RAM, storage devices, etc.
This 2-state design (off, on) corresponds to the
Binary Number System (base 2) in
mathematics.
Binary digit or bit:
Binary Addition:
0 or 1
0
1
+0 +0
0
1
1
+1
10
3-4
Binary Examples
Use the following to convert 8 binary bits
b7b6b5b4b3b2b1b0 to Decimal D:
(b7X27) + (b6X26) + (b5X25) + (b4X24) + (b3X23) +
(b2X22) + (b1X21) + (b0X20) = D
b7b6b5b4 b3b2b1b0
For example, for the binary bits 1100 0001, the
decimal value will be:
(1X128) + (1X64) + (0X32) + (0X16) + (0X8) +
(0X4) + (0X2) + (1X1) = 193
It is not necessary to know how to do this kind of
conversion in this course.
Use your scientific calculator to do conversions, if
3-5
needed.
Units of Data Storage
Binary digit or bit::
Byte:
:
0 or 1
comprises 8 bits
1 Kilobyte (KB)
= 1024 bytes = 210 bytes
1 Megabyte (MB) = 1024 KB
= 220 bytes
1 Gigabyte (GB)
= 1024 MB
= 230 bytes
1 Terabyte (TB)
= 1024 GB
= 240 bytes
* Note: the above conversion only applies when
referring to memory size
3-6
Data Types: Integers
Data in computing are stored in various
forms known as data types.
C has the following fundamental data types:
char, int, float, double
Integers (int) are whole numbers (no
decimal point). They are represented
exactly using bit patterns of 0s and 1s.
Example: 20 (=16+4) is represented exactly
by 10100 (see slide 3-5)
3-7
Data Representation (Integers)
Humans
(numbers)
0
1
2
3
4
5
Computers
(off, on)
Represented
by different
bit patterns
Question: How many bits are required
to represent a number?
3-8
1 bit can only represent 2 cases:
0, 1
Hence we must use more bits to represent
various types of data.
If we use 2 bits, we get 4 possibilities, to
represent 4 different numbers:
00 01 10 11
For 3 bits:
000
100
001 010
101 110
011
111
There are 23 = 8 possibilities  can represent 8
different numbers
3-9
No of Bits
Possible states
(to represent different numbers)
4
6
7
8
16
32
16 (=24)
64 (=26)
128 (=27)
256
65,536
4,294,967,296 (=232)
3-10
All Possible Bit Patterns for 7 bits:
Exact Representation of Integers
0000000
(010 : decimal 0)
0000001
(110 : decimal 1)
0000010
(210 : decimal 2)
. . .
1111110
(12610 : decimal 126)
1111111
(12710 : decimal 127)
3-11
Numbers: Integers
C provides several integer types, with different
storage requirements:
short:
uses 16 bits = 2 bytes
(short data type can represent 216 = 65536
different numbers, from -32768 to 32767)
int:
uses 32 bits = 4 bytes
We also have unsigned short, unsigned int.
Unsigned short: uses 2 bytes (but number range
is from 0 to 65535)
3-12
Characters in Computing
26 x 2 letters (upper & lower case)
10 numeric digits,
punctuation marks,
special characters (~ @ $ #, …)
control characters, etc.
How are these stored in a computer?
Remember that computers can only deal with 0s
and 1s.
3-13
No of Bits
Possible states
(to represent different characters)
4
6
7
8
16
16
64
128
256
65,536
Need at least 7 bits to represent characters in
computing. Normally use 8 bits (1 byte).
3-14
Data Representation (Characters)
Humans
(alphabets)
A
B
C
D
E
Computers
(off, on)
Represented
by
different
bit patterns.
But what are
these
patterns?
3-15
ASCII codes
Each character has a numeric code called the
ASCII code. (Pronounced: askey). The computer
stores this numeric code because it is not able to
store the character shape that we humans use.
ASCII = American Standard Code for
Information Interchange
Char
ASCII
A
B
a
b
65 66 97 98
0
1
+
lf
sp
48 49 43
10
32
lf = line feed, sp = space
3-16
The ASCII Table
0
1
2
3
4
5
6
7
8
9
0
NUL
SOH
STX
ETX
EOT
ENQ
ACK
BEL
BS
HT
1
LF
VT
FF
CR
SO
SI
DLE
DC1
DC2
DC3
2
DC4
NAK
SYN
ETB
CAN
EM
SUB
ESC
FS
GS
3
RS
US
SP
!
“
#
$
%
&
‘
4
(
)
*
+
,
-
.
/
0
1
5
2
3
4
5
6
7
8
9
:
;
6
<
=
>
?
@
A
B
C
D
E
7
F
G
H
I
J
K
L
M
N
O
8
P
Q
R
S
T
U
V
W
X
Y
9
Z
[
\
]
^
_
'
a
b
c
10
d
e
f
g
h
i
j
k
l
m
11
n
o
p
q
r
s
t
u
v
w
y
z
{
|
}
~
DEL
12
x
To get equivalent integer value of a character:
1st Digit is row number, 2nd Digit is column number
E.g. ‘A’ = 65 (from row 6, column 5)
3-17
Upper ASCII & UNICODE
For the PC, there is also a set of upper (or
extended) ASCII codes, from 128 to 255
(so needs 8 bits). They represent European
characters and graphics characters.
CJK (Chinese, Japanese and Korean)
character sets need 16 bits – UNICODE
which includes characters/symbols from all
major languages in the world.
3-18
Extended ASCII Codes
3-19
Character or Number:
What is 1000001?
Using the conversion method from slide 3-5:
b6b5b4 b3b2b1b0
1000001 (binary) = 64 + 1 = 65 (decimal)
The bit string 1000001 represents both
character ‘A’ and the integer 65. In fact, it may
also represent an instruction or part of an
instruction.
How does the computer know which is which?
The context, defined by the program,
determines the correct meaning.
3-20
Data Type: Characters
Declaration of a char variable:
char ch;
The computer will allocate a 1-byte cell (with
the name ch) in RAM.
x
memory cell
ch
To store an actual character such as the lower
case x in ch, we write:
ch = 'x'; //'x' is a character constant
Note that a character, x in this case,
must be enclosed with ' '
3-21
Data Type: Characters
Conversion specifier:
%c
printf("The character is %c", ch);
OUTPUT:
The character is x
String constant: comprises a list of characters,
enclosed with " "
Example:
"FE1008 Computing"
3-22
Conversion Specifier
char ch = 'x';
(ASCII value = 120, or 11110002)
printf("The character is %c", ch);
OUTPUT:
The character is x
If we change %c to %d:
printf("The character is %d", ch);
the output is (the associated ASCII integer value)
The character is 120
3-23
Char data type and numeric
values
The char data type is also one of C’s integer
data types.
Type
Meaning
Value Range
char
character
-128 to 127
unsigned
char
0 to 255
3-24
Data Type: Integers
Type
Meaning
Value Range
char
character
short short integer
int
integer
-128 to 127
-32,768 to 32,767
-2,147,483,648 to
2,147,483,647
long long integer
unsigned
char
unsigned
short
Same as int(not always)
0 to 255
0 to 65535
3-25
Falling off the Edge?
Range for short int:
Suppose we have:
-32,768 to 32,767
32767+1 wraps around
and becomes -32768
short old_bal = 32767, new_bal;
new_bal = old_bal + 1;
What do you think will happen if we execute
printf("New balance = %d", new_bal); ?
Output:
New balance = -32768
When max value 32767 is reached,
32767+1 wraps around and goes back to
the beginning (i.e. -32768)
3-26
The storage sizes of short, int, long are
system dependent.
On some, sizes of short and int are the same:
2 bytes.
For CodeBlocks, sizes of int and long: 4 bytes.
To find out the correct size of a data type on a
system, use sizeof().
printf("The size of int is %d bytes.",
sizeof(int));
Output (CodeBlocks):
The size of int is 4 bytes.
3-27
Escape Sequences
\n: an escape sequence,
\: escape character
Some common escape sequences are listed
below:
Sequence
Meaning
\n
newline
\t
horizontal tab
\"
\\
double quote
backslash
3-28
Example:
How do we output a double quote character " on the
screen? Like:
This is a double quote ".
It is wrong to write:
printf("This is a double quote ".");
It should be
printf("This is a double quote \".");
" that comes after \ will be interpreted as a double
quote character ". It WILL NOT be interpreted as a
double quote enclosing a string of characters.
Similarly, to output the backslash character \, we
3-29
need to use the escape sequence \\.
Floating-point Numbers
Various types: float, double, long double
float type: represented by 4 bytes = 32 bits
The IEEE Floating-Point Representation divides
the bits in the following way:
Sign
bit
0
8-bit
exponent
10000010
23-bit mantissa
10110011000001000000000
3-30
The float Data Type
This representation gives the following range of
values:
1.2E-38 to 3.4E+38
with a corresponding negative range.
Here, E-38 means 10-38.
Because of the limited number of bits allocated
for the mantissa (i.e., the fractional part), a
number of the float type only has 6 or 7 digits
of precision (which is commonly referred to as
single-precision).
3-31
Which real numbers can be
represented exactly?
An example:
0 10000001 01110000000000000000000
= 5.7500000 (decimal)
The next larger number is:
0 10000001 01110000000000000000001
= 5.750000476837158203125 (decimal)
These two decimal numbers can be represented
exactly but there are infinitely many real
numbers (e.g. 5.7500001, 5.75000023) between
these two numbers, and these other numbers
cannot be represented exactly.
3-32
Overflow & Underflow
When the result of a computation is greater than
the largest floating point value (about
3.4E+38) , we get an overflow condition.
This usually indicates that something is wrong
because 1038 is a huge number which is not
commonly encountered in applications.
If smaller than 1.2E-38, we get an underflow
condition.
3-33
The Real Line and Floats
underflow
overflow
0
FLT_MIN
= 1.2E-38
FLT_MAX
= 3.4E+38
Note: FLT_MIN and FLT_MAX are macros
defined in the system (in float.h).
3-34
More accuracy & wider range
Double: 8 bytes = 64 bits
Sign
bit
11-bit
exponent
52-bit mantissa
Range: 2.2E-308 to 1.8E+308
(-ve range also)
Gives 14 or 15 digits of precision (doubleprecision).
It is the default data type for floating-point
numbers. A numeric constant with a decimal point
(such as 2.0) is considered as a double.
3-35
What ANSI C says
ANSI C only guarantees (accuracy wise) that
• a double is greater than or equal to a
float, and
• a long double is greater than or equal to
a double.
3-36
Format/Conversion Specifiers
For output, we always need to specify what and
how to output. For example, in the printf()
below:
printf("The root is %f\n", root1);
the format string "The root is %f\n" is for
this purpose. %f is known as a conversion or
format specifier.
We have used conversion specifiers such as %d
and %c. There are several others.
3-37
Format/Conversion Specifiers
Character
%d
%f
%e
%E
%c
%%
Argument
integer
float
float
float
character
Output
signed decimal integer
signed floating point no.
float using e notation
float using E notation
a single character
% sign
3-38
Float type conversion specifiers
%f, %e, %E
Suppose number = 12.34
%f
gives
12.340000 (default 6 decimal places)
%e gives
1.234000e+001 (which is 1.234 x 101)
%E gives
1.234000E+001 (which is 1.234 x 101)
Note that %e and %E are the same except for the
respective display of a lower case e and an upper
case E.
3-39
Float type format/conversion
specifiers
%f, %e
Suppose number = 0.0001234
%f
gives
%e gives
0.000123
1.234000e-004
Note: Use %e if you are not sure about the size
of output numbers.
3-40
Format Modifiers
We can specify:
1. A minimum field width
which is the minimum number of spaces to use
for output, e.g.
%5d (i.e. minimum 5 character spaces
are to be used for displaying an integer.)
2. Number of decimal places (for floats)
%m.nf (m is the minimum field width, n
is the number of decimal places)
3. Left justification
Default is right justification.
3-41
Format Modifiers
Examples:
(1) To output 123
Each denotes a
space character
(a) using %5d gives [ ][ ]123
(right justification)
(b) using %-5d gives 123[ ][ ]
(left justification)
(2) Suppose the number is 12.34
%8.3f
________
(A total of 8 space are to be used)
Try %1.3f,
%0.3f,
%.3f (If the field
width is too small, the computer will ignore it.)
See Practical Lesson 3 (printf.c)
3-42
Outputting the % sign
To output the percentage sign %, we need to
type two % signs:
printf("This is the %% sign.");
Note: Just like the backslash (\) character,
% also has a special meaning in the
printf() statement. As you have seen, it is
used in the form %c, %d, %f, etc.
3-43
Summary
1. Integer data type
•
•
short, int, long
char
2. Escape sequence using \
3. Floating Point data type: float, double
4. Format specifiers and modifiers
5. How to output a % sign
3-44
IE1005 From Computational
Thinking to Programming
Lesson 4
C Operators
(Reference: Harry H. Cheng, Chapter 4)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
4-1
What are C operators?
A C operator is a symbol (e.g. +, -) that instructs C
to perform a specific action on one or more objects
(which can be simple variables) known as operands.
C has a large collection of operators:
• Assignment operators
• Arithmetic operators
• Cast operators
• Increment/decrement operators
• Relational operators (Lesson 6: Decision Making)
• Logical operators (Lesson 6: Decision Making)
• Bitwise operators (not covered in this course)
4-2
The Assignment Operator (=)
The assignment operator (=) assigns the value of the
right-hand side expression to the variable on the left.
int
a = 2,
b = 3;
a = a + b;//assign sum of a(=2) and b(=3) to a
before
after
a=2+3
2
3
a
b
5
3
a
b
No change
4-3
Arithmetic Operators
These are: + - * / %
2+3=5
operands: 2, 3
+ is a binary operator (It acts on 2 operands).
When used for changing the sign of a number or a
variable, - is a unary operator. For example, -2
% is the modulus (remainder) operator.
5%2 = 1 //get remainder of 5 divided by 2
It is a useful operator. For example, the value of
num%2 will tell us whether the integer num is even
(remainder is 0) or odd (remainder is 1).
4-4
Program 4.1 (Use of % operator)
/* Checks whether an integer is even or odd */
#include <stdio.h>
int main(void)
{ int number;
== checks for
equality
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0) //if remainder is 0
printf("The integer is even.\n");
else //if remainder is 1
printf("The integer is odd.\n");
return 0;
}
4-5
Type Promotion (mixed-mode calculation)
Suppose we have
int inum;
double dnum;
and we wish to calculate inum/dnum. Notice
that this is a mixed-mode calculation involving
two different data types (int and double).
In this case, a copy of inum will be “promoted”
to type double first before the division is carried
out. Variable inum remains as int.
inum/dnum  1/2.0  1.0/2.0  0.5
4-6
Type Promotion (mixed-mode calculation)
In a mixed-mode calculation, the following
promotion order (left to right) is used to convert
a copy of the value of a variable lower in the
order to one of the higher data type.
Promotion order: Lowest on the left
char, int, long, float, double
convert direction
4-7
Conversion by assignment
double dnum;
int inum;
(1) Suppose inum = 5 and we have the
assignment:
dnum = inum;
The result is as expected: dnum = 5.0, a double
number, and there is no loss of precision.
4-8
Conversion by assignment
(2) Suppose dnum = 5.8 and we have the
assignment:
inum = dnum;
The result is now: inum = 5, an integer number.
The fractional part is lost, so there is a loss of
precision. We have to be careful about this.
However, this fact can also be usefully employed
in some programming problems, as in to
purposely get the whole number part.
Note that dnum still remains as 5.8
4-9
Typecast
A typecast uses the cast operator to explicitly
control data type conversions.
If inum is of type int, (float)inum ‘casts’
inum to type float. We also have
(double)inum and (int)dnum.
Example: x = 7,
y = 5
x/y (both int) results in 1 whereas
(double)x/y (double divide by int) gives 1.4
Similarly, x/(double)y (int divide by double)
4-10
gives 1.4
Arithmetic Assignment Operators
The statement
a = a + b;
can be abbreviated as
a += b;
+=
is the addition assignment operator.
We may also combine = with -, *, /, %
4-11
a += b;
a = a + b;
a -= b;
a = a - b;
a *= b;
a = a * b;
a /= b;
a = a / b;
a %= b;
a = a % b;
Note that
a /= b+c;
means a = a/(b+c);
a %= b+c;
means a = a%(b+c);
4-12
Increment & Decrement Operators
(++, --)
Adding or subtracting 1 to/from a variable is a
very common operation in programming.
To do this, we have 3 forms:
c = c+1;
c += 1;
c++;
c -= 1;
c--;
Similarly,
c = c-1;
4-13
c++,
c--,
++c,
--c
c++
Post-increment
(increment last)
c--
Post-decrement
(decrement last)
++c
Pre-increment
(increment first)
--c
Pre-decrement
(decrement first)
Differences?
4-14
Example (Pre-decrement):
Suppose
c = 1;
and
result = --c;
c is decremented first (c becomes 0) before it is
assigned to result (also 0 now). We get
c = 0
and
result = 0
result = --c;
is equivalent to two statements:
c = c – 1; //Pre-operation (decr)
result = c; //Main operation
4-15
Example (Post-decrement):
Suppose
and
c = 1;
result = c--;
c (still 1) is assigned to result (also 1) before it is
decremented (c becomes 0 now), so
c = 0
and
result = 1
result = c--;
is equivalent to two statements:
result = c; //Main operation
c = c – 1;//Post-operation (decr)
4-16
c++,
Contents of
c before
c--,
++c,
--c
Expression Contents of Value of
Expression
c after
1
c++
2
1 (incr last)
1
++c
2
2 (incr first)
1
c--
0
1 (decr last)
1
--c
0
0 (decr first)
Note the last column gives the values of the
expressions (c++, etc) which are used in the
example below:
printf("%d", <expression>);
where <expression> can be c++, ++c, c--, --c
Note: printf("%d",
main operation
c);
is
4-17
Examples
What will be shown on screen after running :
results on
screen
Print first, then
(post) increase
int c=1, y;
printf("%d\n", c++);
printf("%d\n", ++c);
y = 5 + c++;
printf("%d\n", y);
(Pre) Increase
first, then print
c value
1
3
1
2
3
8
4
Add (c=3) to 5 and assign to
y (becomes 8), then (post)
4-18
increase c (from 3 to 4)
Precedence & Associativity of
Operators
Precedence is the order in which operations are
performed.
a + b/c Division before addition because / at
higher precedence level wrt +
(a+b)/c
Addition before division because addition
in()at higher precedence level wrt /
Associativity refers to left-to-right or right-to-left
evaluations of expressions when two or more
operators at the same precedence level appear in the
same expression.
See next slide for Order of Precedence for Operators
4-19
Precedence and Associativity Table
(Selected Operators Only)
Operator (Precedence: High to Low)
Associativity
()
from left
++ -- ! &(address of) *(dereference)
unary * (multiplication)
cast
/ (division) % (modulus)
from right
from left
+ (addition) - (subtraction)
from left
<
from left
==
<=
>
>=
!=
from left
&&
from left
||
from left
?:
from right
Assignment: =
+=
-=
*=
/=
%=
from right
4-20
Example (left-associative)
Consider 15%6*2
% and * are at the same precedence level.
Evaluation goes from left to right (leftassociative).
15%6 = 3,
then
3*2 = 6
Clearer to write it as
(15%6)*2
= 3*2 = 6
4-21
Example (right-associative)
Consider x = y += z -= 4
=, += and -= are at the same precedence level.
Evaluation goes from right to left as shown
below:
x = y += z -= 4
x = y += (z -= 4) [Do z = z-4 first]
x = (y += (z -= 4))[Then y = y+z]
(x = (y += (z -= 4))) [Lastly x = y]
Assuming y = 0, z = 0; x = ?
4-22
Example
int x =5, y = 5, z= 5
x %= y + z
What is the value of x after
running the program?
Ans:
Because, + precedence level is higher than %=,
so, x %=(y + z)
%=(5 + 5)
%=10
=5%10 = 5
4-23
Summary
1. Assignment (=)
2. Arithmetic (+ - * / %)
3. Mixed-mode
4. Conversion by Assignment
5. Typecast
6. Arithmetic assignment (+= -= *= /= %=)
7. Increment, decrement (++, --)
•
Difference between Post and Pre operations
8. Precedence & Associativity of Operators
4-24
IE1005 From Computational
Thinking to Programming
Lesson 5
Standard Library Functions
(Reference: Harry H. Cheng, Chapter 6, 9, 12)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
The C Standard Library
Functions are the building blocks of C
programs.
e.g.
printf(), scanf(), sqrt()
CodeBlocks (other C systems as well) provides
a rich collection of powerful functions known as
the C Standard Library for our use.
5-2
Header Files
The library has a set of associated header files
such as stdio.h. These contain
• prototypes of functions in the library
(Prototypes will be covered in a later lesson). .
• macro definitions
• other programming elements.
To use a function (e.g. printf( )), we need to
include the corresponding header file (stdio.h
for printf( )).
5-3
Table 5.1 Selected Header Files
Header File
Description
ctype.h
Character handling
math.h
Math functions
stdio.h
Input/Output
stdlib.h
Misc functions*
string.h
String functions
time.h
Time functions
* C Standard General Utilities Library
5-4
cmath (math.h)
cos
sin
tan
acos
asin
atan
Compute
Compute
Compute
Compute
Compute
Compute
cosine (function)
sine (function)
tangent (function)
arc cosine (function)
arc sine (function)
arc tangent (function)
atan2
cosh
sinh
Compute arc tangent with two parameters (function)
Compute hyperbolic cosine (function)
Compute hyperbolic sine (function)
tanh
Compute hyperbolic tangent (function)
exp
frexp
ldexp
log
log10
modf
pow
sqrt
ceil
fabs
floor
fmod
Compute exponential function (function)
Get significand and exponent (function)
Generate number from significand and exponent (function)
Compute natural logarithm (function)
Compute common logarithm (function)
Break into fractional and integral parts (function)
Raise to power (function)
Compute square root (function)
Round up value (function)
Compute absolute value (function)
Round down value (function)
Compute remainder of division (function)
5-5
How to use standard functions
We need to know:
• The name of the function
• What the function does
• Input Arguments (if any) of the function
• Data type of Output Result returned (if any)
• The associated header file name
5-6
stdio.h
Some I/O functions/macros:
• printf()
• putchar()
Displays one char on screen
Example: putchar('A');
• scanf()
• getchar()
Gets one char from input stream
• fflush()
Flushes I/O buffers
5-7
Input Stream & Input Buffer
The characters you type at the keyboard
form an input stream.
Usually this stream of characters first goes
into an area of memory known as the input
buffer before being retrieved (e.g. by
scanf() or getchar()) in a running
program.
5-8
Why Use fflush(stdin)?
This is used to flush away any unwanted
characters in the input buffer.
Consider
scanf("%d", &num);
scanf("%c", &ch);
to read an integer and a character from the
keyboard.
The second statement will not execute as
expected (i.e. character not captured)! Why?
Stdin:standard input stream
5-9
scanf()
Some points to note about scanf():
(a) When using %c to read in characters,
remember that whitespaces (spaces, tabs,
newlines) are characters.
scanf("%c%c", &ch1, &ch2);
Be careful about how you enter these two
characters. DO NOT separate them using a
whitespace. IF you enter “a b” using keyboard,
‘a’ will be stored in ch1 and space character
5-10
(NOT ‘b’) in ch2!
scanf()
(b) When reading in numbers using %d, %f or
%lf , scanf() skips leading whitespaces.
In inputting two numbers using
scanf("%d%d", &num1, &num2);
we can separate them using one or more
whitespaces which will be discarded by the
computer.
5-11
scanf()
(c) When reading numeric data, it will
continue reading until it meets a trailing
whitespace.
scanf("%d", &a);
Suppose you type 123 456. This input is
considered as two numbers. scanf()will
only read 123, leaving the rest behind in the
input buffer.
5-12
scanf()
(d) When reading numeric data, it will stop
reading any subsequent characters in the input
stream if it meets an invalid character.
scanf("%d", &a);
Suppose you type 123xyz. scanf() will read
the 123 part but leave xyz behind in the input
buffer.
IF you type ‘123’ and press ENTER key, 123
will be stored in a, leaving input (whitespace)
by ENTER key to be retrieved by next scanf()
5-13
Use of fflush(stdin)
Thus, should write
scanf("%d", &num); //get integer
fflush(stdin); //remove whitespace
input when ENTER key is
pressed
scanf("%c", &ch); //get actual char
stdin refers to the input stream created by
input from the keyboard.
Getting two integers as below does not need
fflush(stdin) as whitespaces are discarded:
scanf("%d", &num1);
scanf("%d", &num2);
5-14
getchar()
getchar() reads the next available character
from the input buffer and returns its value as
an integer.
We can assign the character read to a variable as
in the following:
ch = getchar();
or simply call the function without doing any
assignment:
getchar();
5-15
getchar()
It will only read a character from the input buffer
after the user presses the ENTER key.
Suppose you type
abcd 
When you press
ENTER key
when getchar() is expecting input, getchar()
will only read the first character 'a', leaving
behind the others.
5-16
Example: getchar()
can be used to stop program
execution temporarily until the user presses the
ENTER key.
getchar()
{
. . .
fflush(stdin);
/* Need to flush if
there is an input statement before this */
getchar(); /* Program pauses when
nothing is entered. When ENTER is pressed,
getchar() will read this whitespace */
//Proceed with subsequent statements
}
5-17
math.h
Some mathematical functions:
fabs(x) Absolute (or positive) value of a number,
e.g. fabs(-5.78) returns 5.78. Return data
type (which is 5.78 here) is double/float.
Trigonometric functions:
sin(x), cos(x), tan(x) x must be in radians
asin(x), acos(x), atan(x) Inverse functions
Exponential and log functions
exp(x)
ex
log(x)
loge x
log10(x) log10 x
5-18
math.h
Hyperbolic Functions:
sinh(x), cosh(x), tanh(x)
Other mathematical functions:
pow(x,y)
sqrt(x)
ceil(x)
floor(x)
x raised to power y
Square root of x
Ceiling function
Floor function
5-19
Example: sqrt(), pow()
double sqrt(double x);
It normally takes an argument of type double
but float x (or even int) is also acceptable.
double pow(double x, double y);
double x = 2.718;
y = pow(x,6.0);
 y = 2.7186.0
 z = (loge(2.718))2.5
z = pow(log(x),2.5);
Return data type of sqrt and pow is
double.
5-20
Example: ceil() & floor()
double x;
ceil(x) returns the integer (as a value of
type double!) that is just larger than or equal
to x.
ceil(1.4)
ceil(1.4) returns 2.0
returns
the
integer (as a value of type
double) that is just smaller
than or equal to x.
2.0
floor(x)
floor(1.4)
floor(1.4) returns 1.0
1.4
1.0
5-21
ctype.h
Some character functions:
•
•
•
•
•
•
•
isalpha
isdigit
isalnum
islower
isupper
tolower
toupper
Alphabetic character like ‘a’?
Numerical Digit character like ‘1’?
Alphabetic or Numerical Digit character?
Lower case character?
Upper case character?
Upper case --> lower case
Lower case --> upper case
5-22
Example (isdigit)
Digit like
'1'
Non-Digit like
'a'
isdigit
Non-zero
value (True)
isdigit
0 (False)
5-23
Example (isdigit)
#include <ctype.h>
char ch='1';
if (isdigit(ch) != 0) //isdigit() is TRUE
printf("%c is a digit.", ch);
else
printf("%c is not a digit.", ch);
Note:
•
isdigit returns TRUE (not 0) or FALSE (0).
• != means not equal
• We’ll see later that the if statement can be
simply written as
if (isdigit(ch))
5-24
stdlib.h
We shall only consider 4 functions:
abs(), system(), rand() and srand()
abs(x) returns the absolute (or positive integer)
value of a number x, e.g. abs(-5.78) returns 5.
Return data type (which is 5 here) is integer.
system() enables
system commands.
us
to
execute
operating
Example:
system("Pause");
causes program execution to pause until
we
5-25
press any key.
stdlib.h: rand()
rand() and srand() are for generating
random integers.
The function rand() generates a random
integer within the range: 0 to 32767 (This
maximum value is defined as a macro
RAND_MAX in stdlib.h).
5-26
Program 5.3 (rand())
/* Example on the use of rand() */
#include <stdio.h>
#include <stdlib.h> //Library for rand()
int main(void)
{
printf("Three random integers are:\n %d
%d %d\n", rand(), rand(), rand());
return 0;
}
5-27
Program 5.3 (rand())
Output:
Three random integers are:
6334 18467 41
The program always produces the same output
when the program is run repeatedly. This is
normally not satisfactory. To make the result
unpredictable, we need to provide a “seed” to
the random number generator in rand().
Programmers frequently use the time, in
seconds, provided by the computer clock as this
seed number.
*Seed: A integer used to set the starting point
for generating a series of random
numbers.
5-28
Program 5.4 (srand())
/* Example on the use of srand() */
#include <stdio.h>
#include <stdlib.h>
#include <time.h> //Library for time()
int main(void)
{
srand((unsigned) time(NULL));
printf("Three random integers are:\n
%d %d %d\n", rand(),rand(),rand());
return 0;
}
5-29
Program 5.4 (srand())
Output (different each time the program is run):
Three random integers are:
12066 20374 22199
time(NULL) returns the current calendar time.
Value is in terms of number of seconds elapsed,
usually since midnight January 1, 1970 GMT).
srand() takes an unsigned integer argument
as seed, time(NULL)in this example, and rand()
will generate random numbers based on seed
5-30
Summary
1. stdio.h
•
See Slide 5-7 for list of IO functions
2. math.h
•
See Slide 5-18 and 19
mathematical functions
for
list
of
3. ctype.h
•
See Slide 5-22 for
handling functions
list
of
character
4. stdlib.h
•
See Slide 5-25 for list of miscellaneous
functions
5. time.h –
time (NULL) function
5-31
IE1005 From Computational
Thinking to Programming
Lesson 6
Decision Making
(Reference: Harry H. Cheng, Chapter 5)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
Three Basic Program Structures
1. Sequence
Statements are
sequential order.
executed
line
by
line
in
2. Selection
Sequence of program execution may be altered
based on some conditions.
3. Repetition
A group of statements is repeated a certain
number of times.
6-2
Relational Operators
In programming, we frequently need to check
expressions to see whether they are true or not.
If true, the program flow follows one path, and if
false, it follows another path.
For example:
Is exam_mark greater than 80?
If say exam_mark = 70, result of evaluating the
above returns False. Other examples:
Is
getchar() == '\n' ?
Does the integer n lie in the interval
6-3
[0,10]?
Relational Operators in C
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
==
Equal to
!=
Not equal to
We will use the above operators in
expressions, for checking whether
they return True or False.
6-4
Example:
An expression containing a relational operator
returns value 1 (TRUE) or 0 (FALSE).
For real x;
x*x >= 0 is always true.
The C expression
(x*x >= 0) returns a value 1!
x = -5;
printf("The expression x*x >= 0 has value
%d", x*x>=0);
Returns a value 1!
6-5
Example (Continued):
Output:
The expression x*x >= 0 has value 1
-----------------------------------On the other hand,
printf("The expression x*x < 0 has
value %d", x*x<0);
Output:
The expression x*x < 0 has value 0
x*x < 0 is always False (0)
6-6
Note:
Do not confuse == (equality) with = (assignment)
a==b Checks whether values of a and b are equal.
a=b
Value of b is assigned to a. There is change
of data in variable a.
Suppose a = 1, b = 5
printf("The value of a==b is %d", a==b);
a==b is False (0)
printf("The value of a=b is %d", a=b);
a=b = 5
6-7
Note:
In C, any non-zero numeric value can also
represent TRUE.
Example:
a = 15;
if (a) printf("%d", a);
As
a is not zero (which means TRUE),
printf() will be executed.
If a is 0 (which means FALSE), printf() will
not be executed.
6-8
Note:
Suppose we write the statement as
if (a = 15) printf("%d", a);
Interpretation:
Return value of expression (a = 15) is 15.
Result of (a = 15) is TRUE (non-zero).
printf() will be executed.
6-9
Note:
What will be shown on screen after running:
int a = 15;
if (a = 0)
printf("%d\n", a);
a is set to zero (FALSE) so printf() will
NOT be executed
if (a == 0) printf("%d\n", a);
a is set to zero in the previous
statement. Now (a==0) is TRUE so
printf() will be executed
6-10
Remark on the Example about isdigit()
For Slide 5-24, Original Form:
char ch='1';
if (isdigit(ch) != 0) //isdigit() is TRUE (non-
zero)
printf("%c is a digit.", ch);
else
printf("%c is not a digit.", ch);
Simpler Form:
if (isdigit(ch)) //isdigit() is TRUE (non-zero)
printf("%c is a digit.", ch);
else
printf("%c is not a digit.", ch);
6-11
Comparing Characters
Characters can be compared using relational
operators.
Is
'B' > 'A'?
Is
'1' > 'A'?
Basis for comparison?
Using characters’ ASCII values (slide 317)
6-12
Example
Expression
'9' >= '0'
(57)
Value
1 (TRUE)
(48)
'B' <= 'A'
0 (FALSE)
'A' <= 'a'
1 (TRUE)
(65) (97)
'a' <= '$'
0 (FALSE)
6-13
Logical Operators (&&, ||, !)
AND, OR, NOT
Symbols
&&
||
!
These are needed to form complex conditions.
They enhance the decision-making capabilities
of our C programs.
&& and || are binary operators because they
act on 2 expressions.
! is unary (act on 1 expression).
6-14
Examples
(temperature > 90.0) && (humidity > 0.9)
(x >= 1) || (x < 0)
(x >= 1) && (x < 0)
- Is it possible that x is greater than or equal
to 1 AND less than 0 at the same time?
!((x >= 1) && (x < 0))
('A' <= ch) && (ch <= 'Z')
- Check whether value of ch is between [A, Z]
6-15
Truth Values and Truth Table
The truth value (True or False) of a logical
expression is determined by a Truth Table. In
the table below, P and Q are relational
expressions.
P
Q
P && Q
P || Q
!P
F
F
F
F
T
F
T
F
T
T
T
F
F
T
F
T
T
T
T
F
6-16
Logical Assignment
We may even assign return value (either 0 or 1)
of logical expressions evaluation to variables.
even = (n%2 == 0);
- (n%2 == 0)returns true (1) if n divided by 2
gives zero remainder
in_range = (n > -10 && n < 5);
- (n > -10 && n < 5) returns true (1) if n is
between -10 and 5, excluding -10 and 5
is_letter = ('A' <= ch && ch <= 'Z') || ('a'
<= ch && ch <= 'z');
- Above returns true (1) if ch is an alphabet
6-17
i.e. ch is within [A, Z] or [a, z]
More about the if statement
if (expression)
{
statement_1;
.......
statement_n;
}
As we have seen in Lesson 2, if expression is true,
the statement block within {} is executed. Otherwise,
the block is skipped.
If there is only 1 statement to be executed, {} can be
excluded i.e. we can just write
if (expression)
6-18
statement_1;
Program 6.1 (Quadratic Equation)
a*x*x + b*x + c = 0
Program 2.4 (Slide 2-27 and 28) fails if the user
enters 0 for the coefficient a.
We should test for a non-zero value of a given by
the user.
if (a != 0)
//can be written as if (a)
{ root1 = (-b + sqrt(b*b-4*a*c))/(2*a);
root2 = (-b - sqrt(b*b-4*a*c))/(2*a);
}
6-19
The else clause
The if structure is very frequently used with the
optional else:
if (expression)
{
. . . . . . .
}
else
{ . . . . . . .
}
If there is only 1 statement to be executed, {} can be
excluded i.e. we can just write
if (expression)
one_statement;
else
6-20
another_one_statement;
Program 6.2 (quadratic equation)
if (a == 0) //if a is zero, only 1 root
{
printf("You input a = 0.\n");
printf("Only one root: %8.3f", -c/b);
}
else //else if a is non-zero, there
will be 2 root values
{ root1 = (-b + sqrt(…))/(2*a);
. . .
}
6-21
Refinements
How do you handle the following situations?
• a = 0 and b = 0, but c not 0
• a = b = c = 0
A good program must take into account these
possibilities (or all possibilities).
6-22
Nested if statements
These are if statements that contain other if
statements.
In the quadratic equation problem, what if
b*b - 4*a*c < 0 ?
We’ll use a nested if to deal with this.
6-23
Program 6.3
Brown if-else
statements
are NESTED
within Black
if-else
statements
if (a == 0) { . . .}
else
{
if (b*b-4*a*c < 0)
printf("Complex roots.\n")
else //2 real roots
{
root1 = (-b + sqrt() . . .);
. . .
}
}
6-24
Give it a Try Yourself!
Modify Program 6.3 so that it appears to be
capable of handling complex roots. How?
A little cheating!
Suppose the complex roots are
 + i,
 - i
Compute  and  separately, and in the output
insert the strings “+ i” and “- i”.
6-25
if..else if..else if..
Program Fragment 6.4:
if (quiz_mark >= 80) //if mark is 80 or
higher
grade = 'A';
else //else if mark is 70 or higher, but
lower than 80
if (quiz_mark >= 70)
grade = 'B';
else //else if mark is 60 or higher,
but lower than 70
if (quiz_mark >= 60)
grade = 'C';
else . . .
6-26
An Equivalent Form
if (quiz_mark >= 80)
grade = 'A';
else if (quiz_mark >= 70)
grade = 'B';
else if (quiz_mark >= 60)
grade = 'C';
else if
. . .
6-27
Review
• Rewrite the Program 6.4 so that the program
tests for 'F' grade (quiz_mark<50) first, then
'D' (50≤quiz_mark<60), etc.
• Question: Suppose we rewrite Program
Fragment 6.4 using separate if statements:
if (quiz_mark >= 80)
grade = 'A';
if (quiz_mark >= 70)
grade = 'B';
if (quiz_mark >= 60)
grade = 'C';
.
.
.
.
.
.
Are the 2 ways of writing equivalent?
6-28
Discussion
• The 2 ways of writing are different!
•For the original Program 6.4 on slide 6-26 or
27, once a condition is satisfied (TRUE),
evaluation will STOP!
•E.g. by assigning 75 to quiz_mark in the
beginning,
the
first
if-statement
for
(quiz_mark >= 80) will be evaluated. This will
return FALSE.
•Next, (quiz_mark >= 70) will be evaluated.
This returns TRUE, so grade = 'B', and
program will JUMP OUT of the if..else if..else if..
6-29
structure.
Discussion
• Consider now the separate if-statements. Each
if-statement WILL be evaluated regardless of the
value of quiz_mark. Using quiz_mark = 75 again,
if (quiz_mark >= 80)
grade = 'A';
- returns FALSE so grade is not assigned
if (quiz_mark >= 70)
grade = 'B';
- returns TRUE so grade is B
if (quiz_mark >= 60)
grade = 'C';
- returns TRUE also so grade is now C
- if this is the last if-statement, grade
is ‘C’, not ‘B’!
6-30
Program 6.5
Purpose: To construct a menu of choices, which
looks like the following:
Select the form of Ohm’s Law:
[A] Voltage [B] Current [C] Resistance
Your Selection (A, B, C) =>
6-31
Program 6.5 (Continued)
char selection;
printf("Select form of Ohm’s Law.\n");
printf("[A] V, [B] I, [C] R \n");
printf("Your selection => ")
scanf("%c", &selection);
// user’s choice will be stored in
variable selection
6-32
Program 6.5 (Continued)
if (selection == 'A')
printf("V = I*R");
else if (selection == 'B')
printf("I = V/R");
else if (selection == 'C')
printf("R = V/I");
else
printf("Wrong selection");
6-33
The switch statement
Too many if-else statements can be confusing.
In this case, we may use the switch statement.
switch (expression)
{
case value_1: statement(s)
case value_2: statement(s)
. . . . . .
case value_n: statement(s)
default:
}
statement(s)
6-34
The switch statement (Continued)
The expression MUST
(including char) value.
return
an
integer
The computer compares this returned value
against the value following each case label, i.e.
value_1, value_2...
• If there is a match, the statement(s) following
the case label will be executed.
• If no match at all, the statement(s) following
the default label (optional) will be executed.
• If there is no match and no default label, then
exit statement block for switch.
6-35
The break statement
If a match is found, the remaining cases WILL
be executed, without the case values being
checked unless there is a break statement (See
Program 6.6a).
The
break statement is used to exit from the
switch structure (See Program 6.6b).
6-36
Program 6.6a (without ‘break’)
switch (selection)
{case 'A': printf("V = I*R");
//selection=‘B’ does not match ‘A’ so printf()is
not executed
case 'B': printf("I = V/R");
//selection=‘B’ matches ‘B’ so I = V/R is printed
case 'C': printf("R = V/I");
//once a match is found, statement R = V/I will be
printed
default: printf("Wrong selection.");
//once
a
match
is
found,
selection. will be printed
statement
Wrong
}
If user picks 'B', selection=‘B’, output is:
I = V/R R = V/I Wrong selection.
6-37
Program 6.6b (with ‘break’)
switch (selection)
{case 'A': printf("V = I*R");
break;
//selection=‘B’ does not match ‘A’ so printf()and
break are not executed
case 'B': printf("I = V/R");
break;
//selection=‘B’ matches ‘B’ so I = V/R is printed.
Since is break present, the remaining statements
below are ignored
case 'C': printf("R = V/I");
break;
default: printf("Wrong selection. ");
}
If user again picks 'B', selection=‘B’, output is:
I = V/R
6-38
The Conditional Operator (?:)
This is a ternary operator acting on 3 operands. It
is related to if-else.
expr1 ? expr2 : expr3
which is equivalent to
if (expr1) expr2
else expr3
If expr1 is true,
return expr2.
Else, return expr3
status = (mark >= 50) ? 'P' : 'F';
expr1
expr2
If mark ≥ 50, return ‘P’ to status. Else,
return ‘F’ to status.
expr3
6-39
Summary
1. Relational operators (> >= < <= == !=)
2. Logical operators (&& || !)
3. if, if-else, nested if
4. switch-case and break
5. conditional operator (?:)
6-40
IE1005 From Computational
Thinking to Programming
Lesson 7
Loops
(Reference: Harry H. Cheng, Chapter 5)
Dr. Tan Chee Wah, Wesley (School of EEE)
Email: wesleytan@ntu.edu.sg
Office: S1-B1b-54
Phone:6790 6009
“Be Prepared, Give Feedback”
What are Loops?
Other names: Repetition, Iteration.
A group of statements is repeatedly executed
either
(i) a fixed number of times, or
(ii) until a condition becomes false.
Computers are very good in doing such
repetitive work, very fast and accurately.
7-2
Three Loop Structures
• while
• for
• do-while
They are all related in some ways.
7-3
The while statement
Syntax:
while (loop repetition condition)
{
statement;
. . . . .
statement;
}
The statement block within {} will be executed as
long as the loop repetition condition is true.
7-4
Infinite/Endless Loop
It is important to make sure that the loop
repetition condition can become false inside the
while structure or statement block .
If the condition is always true, we’ll get an
infinite/Endless loop.
Example:
while (1)
printf("I must do well in FE1008 \n");
1 is a constant TRUE value, so printf()
will be repeated endlessly.
7-5
Pseudocode for Program 7.1
To calculate the average of a list of n user-input
numbers.
INPUT n //no. of user-input values
SET counter = 1
As long as counter ≤ n,
statements before END
SET sum = 0
WHILE are executed
WHILE counter <= n
INPUT number //get a number
SET sum = sum + number //add to sum
SET counter = counter+1 //increment
counter to get next number
END WHILE
SET average = sum/n //compute average
OUTPUT sum, average
7-6
Program 7.1: Average of
n user-input numbers
int n, counter = 1;
double number, sum = 0, average;
printf("How many numbers to process? ");
scanf("%d", &n); //get number of user’s input
while (counter <= n)
{ printf("Input a number: ");
scanf("%lf", &number); //get a number
from a user
sum += number; //add to sum
counter++; //increment counter
}
average = sum/n; //compute average 7-7
Counter-controlled Loop
The while loop in previous slide has a control
variable (counter) which determines
whether the loop body is to be repeated. Such
a loop is known as a counter-controlled
loop.
Three steps:
1. Initialization (counter
2. Testing (counter
= 1)
<= n)
3. Incrementing (counter++)
7-8
Program 7.2
/* To calculate the sum of all integers
from 1 to 100 */
int num = 1, sum = 0; //initialize num = 1
while (num <= 100) //while num ≤ 100
{ sum += num; //integers from 1 to 100 are
added into sum
num++; //increment num
}
printf("sum = %d", sum);
7-9
Try the Following Yourself!
1. Modify Program 7.2 to calculate the sum of
all odd integers from 1 to 100.
(Hint: to get odd integers, use % to check
remainder)
2. Write a program to calculate the product of
the integers: 1, 2, 3, …, 20.
Verify your program output!
7-10
Example (while):
use in replacement of fflush(stdin)
in MAC OS X Environment
while (getchar() != '\n');
The computer will wait until the user presses the
ENTER key.
When '\n' is encountered, (getchar() !=
'\n')will return FALSE and exit while loop
The above while loop is without a body, and is
the same as the below (with empty body)
while (getchar() != '\n')
{
}
7-11
Program 7.3 (Quadratic Equation)
Program 2.5 terminates
quadratic equation.
after
solving
one
Suppose we wish to let the user solves many
equations without re-running the program until
the user decides to quit.
How?
• Use a while loop.
• Loop repetition condition?
7-12
Program 7.3 (Quadratic Equation)
#include <ctype.h> //in order to use toupper
char do_again;
do_again = 'Y';
while (do_again == 'Y')
/* repeat computation while (do_again == 'Y')
is true */
{ . . . //statements for computation
printf("Solve again (y/n)? ");
fflush(stdin);
do_again = toupper(getchar()); /* get input
– check if user wants to compute? */
7-13
}
Comments on Program 7.3
(1) We use fflush(stdin) to flush away the ENTER
character present in the input buffer (from the
previous input statement like scanf() or
getchar()) before calling current getchar().
(2) The program uses toupper to convert 'y' to 'Y'.
Thus, (do_again == 'Y') will return true and
looping occurs when 'y' or 'Y' is entered.
(3) Any other response will result in (do_again ==
'Y') returning false and quitting the loop.
(4) You need to modify the program so that it will
only accept: 'y', 'Y', 'n', 'N'. User is requested
to re-enter again if any other characters are
entered (see Extra Practical 6 Exercise 2). 7-14
Program 7.4
To reverse the digits in a positive integer.
Suppose int num = 123
while (num > 0) //while number is positive
{
printf("%d", num%10);
num = num/10;
}
num%10
First iteration
123%10=3
Second iteration 12%10 = 2
Third iteration
1%10 = 1
printf
3
32
321
num/10
123/10=12
12/10=1
1/10=0
7-15
Sentinel-Controlled Loop
Such a loop continues execution until a special
value (the sentinel value) is encountered.
This sentinel value depends on the application,
e.g.
• a negative value for “mark”, which makes it an
invalid mark, when processing exam marks;
• 0.0 for price to indicate end of input (See
Program 7.5).
7-16
Program 7.5: Total Price
//This program requests a price and adds to
total until price of zero value is entered
double price, total = 0.0;
printf("Enter price (Type 0 to quit): ");
scanf("%lf", &price); //request a price
while (price != 0) //while price is not 0
{ total += price; //add price to total
printf("Price = ");
scanf("%lf", &price); //request
another price
7-17
}
do - while
This is a variant of the while statement:
do
{
statements
} while (expression);
Checking of expression is done at the end.
Statements in Body of loop are executed at
least once since statements in body are
executed before any checking of expression
can be carried out.
7-18
Program 7.5a: Total Price using do-while
double price, total = 0.0;
printf("Type 0 to quit\n");
do
{ printf("Price = ");
scanf("%lf", &price); //request a
price
total += price; //add price to total
} while (price != 0); //while price is
not 0
7-19
Program 7.6: Input Checking
// This program keeps asking for an
integer until a value < 5 is entered
int input;
do
{
printf("Input an integer < 5: ");
scanf("%d", &input); //Request an integer
< 5
if (input >= 5)
printf("Too large. Try again.\n");
} while (input >= 5); /* repeat the request
while integer is ≥ 5 */
7-20
printf("Thank you!\n");
Try Yourself!
(a) Rewrite Program 7.6 using a while loop.
(b) Rewrite Program 7.6 to check for input to
be within the interval [0, 5]. (Hint: make
use of &&, >= and <= operators)
7-21
The for loop
A for loop is often used as a counter-controlled loop
but it can also be used as a sentinel-controlled loop.
for (expression1; expression2; expression3)
{
statements_in_body
}
expression1: initializes loop variable
expression2: loop condition
expression3: increments loop variable
Sequence of action:
expr1  expr2  statements_in_body  expr3
Loop continues until
expr2 is NOT satisfied!
7-22
Program 7.7 (Program 7.2 but using for)
int num, sum = 0;
for (num=1; num <= 100; num++)
sum += num; /*integers from 1 to 100
are added into sum */
printf("sum = %d\n", sum);
initialize:
Loop condition
increment:
num = 1; //start from num = 1
num <= 100; //as long as num
≤ 100
num++; //num incremented by 1
after
each
loop
is
7-23
completed
Program 7.8 : Counting Downwards
int num, sum = 0;
for (num = 100; num > 0; num--)
sum += num; /*integers from 100 down
to 1 are added into sum */
printf("sum = %d\n", sum);
initialize
num = 100; //start from num =
100
Loop condition
increment:
num > 0; //as long as num > 0
num--; //num decremented by 1
after
each
loop
is
7-24
completed
The for & while loops
These loops are closely related.
(a) Rewrite the for loop using a while
structure. See Extra Practical 6, Question
1.
(b) Rewrite Program 7.3 (Quadratic Equation)
using a for loop. See Extra Practical 6,
Exercise 2.
7-25
The for loop: the comma operator
Generally, two C expressions may be separated
by a comma operator:
expression1, expression2
The computer will evaluate expression1, followed
by expression2.
We can have more than one expression in a for
statement:
for (i=0, j=2; i<= 5; i++)
expression1, expression2
7-26
The for loop: the comma operator
Example
for(sum=0, num=1; num<= 100; num++)
sum += num; //sum of integers from 1 to 100
which can also be written
for (sum=0, num=1; num<= 100; sum += num,
num++);
sum
num
sum += num
num++
Iteration 1
0
1
0+1 = 1
1+1=2
Iteration 2
1
2
1+2 = 3
2+1=3
…
Iteration 100
4950 100
Sum of integers 1 to100
4950+100
=5050
100+1=101
7-27
The for loop: the comma operator
Example
for(sum=0, num=1; num<= 100; num++)
sum += num; //sum of integers from 1 to 100
but CANNOT be written as
for (sum=0, num=1; num<= 100; num++, sum +=
num);
sum
num
num++
sum += num
Iteration 1
0
1
1+1=2
0+2 = 2
Iteration 2
2
2
2+1=3
2+3 = 5
…
Iteration 100
5049 100
Sum of integers 2 to101
100+1=101
5049+101
7-28
=5150
The for loop: further information
Any or all of the expressions in a for statement
can be missing, but the two semicolons (;) MUST
remain.
• Missing initialization expression:
num=1;
sum = 0;
num and sum here provide
initial
values
to
for
statement!
for ( ; num<=100; num++)
sum += num;
7-29
The for loop: further information
• Missing initialization & increment expression:
num = 1;
sum = 0;
for ( ; num<=100; )
sum += num++;
Remember that sum += num++; is equivalent to:
sum += num;
num++; (post-increment)
Increment of sum and num are carried out here!
7-30
The for loop: further information
• Missing loop-continuation expression:
In this case, the test is always TRUE.
num=1;
sum = 0;
for ( ; ; )
sum += num++;
This is an infinite loop. Need an exit (like using
break – will discuss soon!) from within the loop
body.
7-31
Nested Loops
• The inner and outer loops need not be
generated by the same type of control
structure. For example, we may have a
while loop inside a for loop.
• No overlap allowed: one loop must be
completely embedded inside another.
• Each loop must be controlled by a different
loop control variable.
Outer
Loop
[
Inner
Loop
Nested Loops
[
7-32
Overlap loop
Program 7.9: Nested Loops
int i, j;
for (i=1; i <= 3; i++)
{ printf("i = %d ", i);
for (j=1; j <= 4; j++)
printf("j = %d ", j);
printf("\n");
}
For
3),
i =
i =
i =
each printed i value
print j value from 1
1 j = 1 j = 2 j =
2 j = 1 j = 2 j =
3 j = 1 j = 2 j =
Outer For
Loop
Inner For
Loop
(from 1 to
to 4
3 j = 4
3 j = 4 7-33
3 j = 4
Another Example of Nested Loops
Printing a multiplication table (Try this yourself!
Answer will be revealed in the next Lesson)
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
…
12
…
144
Hint: Like Program 7.9, use Inner Loop to print
values in each row. Outer Loop is used to print
7-34
the first value in each row.
Example: 3 Levels for Loops
for (i=1; i <= 3; i++)
for (j=1; j <= 3; j++)
for (k=1; k <= 3; k++)
i
j
k
3
x
3 matrix will be
created for the above
3
x
m x n x l THREE dimensional matrix
7-35
The break statement
We have seen that the break statement causes
an exit from a switch statement (Lesson 6).
It can also be used to exit from a loop. In a
nested loop, it exits only from the loop that
contains the break statement. E.g. if only
inner loop has the break statement, break (if
occurred) will cause exit from the inner loop only.
In Program 7.10, we repeatedly ask the user to
enter a number and calculate its square root until
the user decides to quit by entering a negative
number.
7-36
Program 7.10: Using break
float x;
while (1) //Always true - Not recommended
{
printf("Enter number, -ve to quit. ");
scanf("%f", &x);
if (x < 0.0) break;
// exit loop if x < 0
printf("%f\n", sqrt(x)); //Compute if
x ≥ 0
}
/* break causes exit from while loop and
jumps to this point here! */
7-37
The continue statement
The continue statement causes the current
iteration of a loop (for, while, do-while)
to stop execution and next iteration to begin
immediately, without exiting the loop.
The purpose of the next program (Program
7.11) is to calculate the sum of 25 marks,
rejecting invalid marks (negative marks and
marks > 100), i.e. excluding them from the
calculation of sum and incrementing of count.
7-38
Program 7.11: Using continue
int count = 1, sum = 0, mark;
while (count <= 25)
{ printf("Enter a mark => ");
scanf("%d", &mark);
if (mark <0 || mark > 100)
continue;
/* if mark <0 or mark>100, skip the
below in the body and continue
execution from the beginning of
while (count <= 25) statement */
sum += mark;
7-39
count++;
}
Summary
1. while loop
2. do-while loop
3. for loop
•
variations of the for-loop header/statement e.g.
use of comma operator or missing expressions in
for-loop header/statement
4. Counter-controlled
controlled loop
loop
vs
sentinel-
5. nested loop structure
6. break and continue
7-40
Download