Вы находитесь на странице: 1из 27

2/3/2015

Review of C
Week 2

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

A C Program
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

A C Program
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);

Preprocessor Directives

/* Convert the distance to kilometers. */


kms = KMS_PER_MILE * miles;

/* Display the distance in kilometers. */


printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

Preprocessor Directives
A C program line beginning with the #
symbol that provides an instruction to the
preprocessor.
Preprocessor a system program that modifies
a C program prior to its compilation
Two most common directives:
#include
#define
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

The #include Directive


This directive identifies that the program will be using
functions and/or symbols that are located in a
library file. The directive will cause the preprocessor
to include the definitions prior to compilation.
In the C language, libraries of common functions are
called Header Files and their names end with the
symbols .h.
For example:
<stdio.h>
<string.h>
<math.h>
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

The #define Directive


This directive associates a meaningful name to
a constant value to be used throughout your
program.
These meaningful names are called
Constant Macros and greatly assist us in
understanding the logic in the program.
For example:
#define PI 3.141593
#define US_LIFE_EXPECTANCY 77.7
#define US_AVG_INCOME 50233.00
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

A C Program
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

A C Program
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);

Comments

/* Convert the distance to kilometers. */


kms = KMS_PER_MILE * miles;

/* Display the distance in kilometers. */


printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Program Comments
Programmers can add additional descriptions
and explanations on their processes via
Comments inside of their code.
The /* and */ symbols are used to identify
the comment. Text between these symbols
is ignored by the Preprocessor & Compiler.
For example:
/* This will be ignored during the compile. */
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

Program Comments (cont.)


An alternative to using the start and stop
symbols, is to use the single line comment
symbol of //.
When using this symbol, the text written on the
same line in your source code is ignored by
the Preprocessor & Compiler.
For example:
// This will be ignored during the compile.
This will not be ignored during the compile.
// This will also ignored during the compile.
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Comments
/*
* Programmer: Troy Zinderman
* Date Completed: September 23, 2005
* Class: INSS209
*
* Calculates final grade of students based
* on assignment weights
*
Must be included in all
*/
project source code
submissions.

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

A C Program
/*
* Converts distance in miles to kilometers.
*/
#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

A C Program
/*
* Converts distance in miles to kilometers.
*/

Main Function

#include <stdio.h>
#define KMS_PER_MILE 1.609
int
main(void)
{
double miles,
kms;

/* printf, scanf definitions */


/* conversion constant
*/

/* input - distance in miles.


/* output - distance in kilometers

*/
*/

/* Get the distance in miles. */


printf("Enter the distance in miles> ");
scanf("%lf", &miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %f kilometers.\n", kms);
return (0);
}

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Main Function
Every C program contains a main
function. This marks where the
program execution begins.
A function body is comprised of 2 parts:
Declarations
Executable Statements

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Function Components
Declarations is the part of a program
that tells the compiler the name of
memory cells in the program.
Executable Statements program lines
that are converted to machine
language instructions and executed
by the computer.

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

Function Punctuation & Symbols


Functions use punctuation & symbols to
identify specific elements or actions
inside the code.
Commas (,) separate items in lists
Semicolon (;) identify the end of a
statement
Braces ({}) mark the beginning &
end of the function
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Reserved Words
A word that has special meaning in the
C language and can not be used for
any other purpose. Some examples:
Basic coding instructions
if, else, break, switch

Part of declarations
float, int, double
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Standard Identifiers
A word that has special meaning but
one that can be redefined by a
programmer (not a good idea).
Common functions from libraries
printf, scanf

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

User-Defined Identifiers
Words that programmers can assign to
memory cells to hold data & program
results.
User-Defined Identifiers make
programmers easier to construct,
read, & debug.
There are syntactical rules &
recommendations for their use.
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

User-Defined Identifier Rules &


Recommendations
1.

An identifier must consist of only letters, digits, &


underscores (e.g. ABC_123)

2.

An identifier cannot begin with a digit


(e.g. 1DIGIT)

3.

A C reserved word cannot be used as an identifier


(e.g. void)

4.

It is recommended that an identifier defined in a


C standard library should not be redefined
(e.g. printf)

5.

It is recommended that an identifier be not longer


than 31 characters in length
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Back to Declarations
Most declarations in a program are for the
assignment of variables.
Variable a name associated with a memory
cell whose value can change.
Variable Declaration a statement that
communicates to the complier the name
of a variable in the program and the kind if
information stored in the variable.

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

Variable Declaration
Variable Identifier
(Name)
double miles,
kms;

/* input - distance in miles.


/* output - distance in kilometers

Variable Data Type

*/
*/

Comments describing
variable purpose

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Data Types
A set of values and operations that can
be performed on those values
Standard Data Type a data type that is
predefined to the C language.
Enumerated Data Type a data type
that is defined by the programmer
(to be address later in the semester).
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

The Integer Data Type (int)


An integer is the set of natural numbers
(including 0) and their negatives.
The set of integers used inside of a language is
limited by the finite size of a memory cell.
The ANSI C standard require that the data type
of int must at least include numbers
-32767 through 32767.
Examples: -12453, -54, 0, 4325, 32211
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

The Double Floating-Point Data


Type (double)
A form used to represent numbers with
fractional components.
An abstraction for real numbers since the finite
size of a memory cell limits total inclusion.
The ANSI C standard require that the data type
of double must at least include numbers
10-37 through 1037.
Examples: 3.14159, 1010.10, 123.0, 1.32e-9
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

The Character Data Type (char)


Represents a single character value, to
include a letter, a number, or a symbol.
In a C program, character values are
enclosed by the apostrophe symbol
(single quotes).
However char data type variables should not
have them.
Examples: A, 3, *, $, e
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

On to Executable Statements
Assignment Statement an instruction
that stores a value or a
computational result in a variable.
Variable Identifier

kms = KMS_PER_MILES * miles;


Assignment
Operator (=)

Constant Macro

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

2/3/2015

Before & After States

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Assignment Statements
(continued)

sum = sum + item;

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Executable Statements
(continued)
Input Operation an instruction that copies data from
an input device into memory.
Output Operation an instruction that displays
information stored in memory.
In the C language, most of the common input/output
functions are supplied in the standard
input/output library (stdio.h)
Access to the library is acquired through a preprocessor directive:

#include

<stdio.h>

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

10

2/3/2015

The Print Formatted Function


(printf)
A standard function that allows a
programmer to display a line of
program output.
A program must make a function call to
activate the function.
printf(That equals %f kilometers.\n, kms);

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

printf Function Components


Format String
Function Name

printf(That equals %f kilometers.\n, kms);

Function Argument

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

printf Function Components


Print List

printf(That equals %f kilometers.\n, kms);

Placeholder

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

11

2/3/2015

Placeholders used in printf


Placeholder a symbol beginning with a
% in a format string that indicates
where to display the output value.
Characters (char data type)
%c
Integers (int data type)
%d
Double Float (double data type)
%f
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Escape Sequences
A series of characters used to change
the state of computers and their
attached peripheral devices .
An escape character is used to identify
an alternative interpretation of the
next character in the character
sequence.

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Newline Escape Sequence


A character sequence that is used in a
format string to terminate an output
line.
In the C language, the sequence \n is
typed to terminate a line of output
printf(That equals %f kilometers.\n, kms);

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

12

2/3/2015

The Scan Format Function


(scanf)
A standard function that allows a
programmer to capture data from an
input device to be stored into
memory.
A program must make a function call to
activate the function.
scanf(%lf, &miles);
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

A Note on scanf
Microsoft has depreciated the use of
scanf within newer versions of Visual
Studio. For students using versions
above 2010, you will have to switch
to using scanf_s or add the following
line as the first preprocessor directive:
#define _CRT_SECURE_NO_WARNINGS

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Placeholders used in scanf


Uses the same placeholders as printf
for characters & integers. Uses a
different placeholder for double
floats.
Characters (char data type)
%c
Integers (int data type)
%d
Double Float (double data type)
%lf
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

13

2/3/2015

scanf Function Components


Variable

Placeholder

scanf(%lf, &miles);
Address-of
operator

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Address-of Operator
A operator (&) that precedes a variable
declared in the scanf function. Its
purpose is to store where the data is
stored in memory (not what is stored
in the variable).

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Effect of scanf

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

14

2/3/2015

How a data line is scanned

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

The Return Statement


The return statement transfers control
from a function back to the activator
of the function.
For function main, control is returned to
the operating system.
return (0);

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Arithmetic Expressions
Operator

Meaning

Addition

Subtraction

Multiplication

Division

Remainder
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

15

2/3/2015

Evaluation Tree for area

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Step-by-Step Expression Evaluation

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

v = (p2 - p1) / (t2 - t1)

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

16

2/3/2015

z - (a + b / 2) + w * -y

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Control Structures
Control Structure a combination of
individual instructions into a single logical
unit with one entry point and one exit
point.
Compound Statement a group of
statements bracketed by { and } that
are executed sequentially.

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Compound Statement
{
statement1;
statement2;
statement3;
.
.
.
.
.
statement n;
}
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

17

2/3/2015

Conditions
Condition an expression that is either
false (represented by 0) or true
(represented by 1).

rest_heart_rate > 75

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Relational & Equality


Operators
Most conditions take one of these forms:
variable relational-operator variable
variable relational-operator constant
variable equality-operator variable
variable equality-operator constant

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Relational & Equality Operators


Operator

Meaning

Type

<

Less than

Relational

>

Greater than

Relational

<=

Less than or
equal to
Greater than or
equal to

Relational

==

Equal to

Equality

!=

Not equal to

Equality

>=

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Relational

Copyright 2009 Troy A. Zinderman

18

2/3/2015

Logical Operators
Logical Expression an expression that
uses one or more of the logical
operators && (and), || (or), ! (not).
n >= 0 && n <= 100
salary < min || dependants > 5

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Logical Complement
The complement of a condition has the
value 1 (true) when the conditions
value is false; the complement of a
condition has the value of 0 (false) when
the conditions value is nonzero (true).
!(0 <= n && n <= 100)

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Operator Precedence
Operator

Precedence

Function Calls
! + - & (unary operators)

highest

* / %
+ < <= >= >
== !=
&&
||
=
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

lowest
Copyright 2009 Troy A. Zinderman

19

2/3/2015

Short-Circuit Evaluation
Stopping evaluation of a logical
expression as soon as its value can be
determined.

x = 0
x > 2
x > 2

y = 6
&&
||

y > 5
y > 5

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Comparing Characters
Expression

Value

9 >= 0

1 (true)

a < e

1 (true)

B <= A

0 (false)

Z == z

0 (false)

a <= A

System dependant

a <= ch && ch <= z

1 (true) if ch is lowercase

Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

Logical Assignment
Assigning the response of a logical
expression to a variable (used to identify
a true or false condition).
in_range = 1;
n = 99;
in_range = ( n > -10 && n < 10);

in_range = 0
Structured Programming Using Procedural Languages  I NSS 225  Ov erview of C

Copyright 2009 Troy A. Zinderman

20

2/3/2015

Selection
if statement allows the value of an
expression to select a course of action.
if (rest_heart_rate > 56)
printf(Keep up your exercise program./n);
else
printf(Your heart is in excellent health./n);

Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

Types of Selection
One alternative:
if (condition)
statement;
Two alternatives:
if (condition)
statement;
else
statement;
Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

Compound Statements within


if Statements
if (condition)
{
statement1;
statement1;
statement1;
}
else
{
statement1;
statement1;
statement1;
}
Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

21

2/3/2015

Nested if Statements
An if statement with another if
statement as its true task or false task.
if (x > 0)
num_pos = num_pos + 1;
else
if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;

Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

ifs in Sequence
if (x > 0)
num_pos = num_pos + 1;
if (x < 0)
num_neg = num_neg + 1;
if (x == 0)
num_zero = num_zero + 1;

Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

Multiple-Alternative Decision Form


if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
else
statement;
Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

22

2/3/2015

The switch Statement


switch (controlling expression) {
label set:
statements;
break;
label set:
statements;
break;
label set:
statements;
break;
default:
statements;
}
Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

The switch Statement


switch (watts) {
case 25:
life = 2500;
break;
case 40:
case 60:
life = 1000;
break;
case 75:
case 100:
life = 750;
break;
default:
life = 0;
}
Structured Programming Using Procedural Languages  I NSS 225  Selection Structures

Copyright 2009 Troy A. Zinderman

Repetition in Programs
Loop a control structure that
repeats a group of steps in a
program.
Loop Body the statements that
are repeated in the loop body.
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

23

2/3/2015

Kinds of Loops
Kind

When Used

Counting Loop

We can determine before loop execution


exactly how many loop repetitions will be
needed to solve the problem

Sentinel- Controlled
Loop

Input of a list of data of any length ended


by a special value

Endfile-Controlled
Loop

Input of a single list of data of any length


from a data file

Input Validation
Loop

Repeated interactive input of a data value


until a value within the range is entered

General Conditional
Loop

Repeated processing of data until a


desired condition is met

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Counting Loops
Counter-controlled loop a loop whose
required number of iterations can be
determined before loop execution begins.
Set loop control variable to an initial
value of zero
While loop control variable < final value
Statement1
Statement2
Statement3
:
Increase loop control variable by 1
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

The while Statement


No Employees
Processed Yet

count_emp = 0;
while (count_emp < 7)
{
printf("Hours> ");

Testing
Condition

scanf("%d", &hours);
printf("Rate> ");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1;
}

Increment
Control Variable

printf("\nAll employees processed\n");

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

24

2/3/2015

The Infinite Loop


a loop that executes forever due
to an erroneous control
condition evaluation or an
erroneous incrementing of the
control variable.
while ( 1 != 2 )
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Computing Sums or Products


Loops are often used to accumulate a
sum or a product of an unknown
number of inputs.
Accumulator a variable used to store a
value being computed in increments
during the execution of a loop

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Computing Sums or Products


total_pay = 0.0;
No Pays
Calculated Yet
count_emp = 0;
while (count_emp < number_emp) {
printf("Hours> ");
scanf("%lf", &hours);
printf("Rate > $");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n\n", pay);
total_pay = total_pay + pay;
Pay Accumulator
count_emp = count_emp + 1;
Variable
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

25

2/3/2015

Compound Assignment Operators


An alternate way of writing assignment
operators that combine the mathematic
calculation with the assignment character.
Favored by programmers since it is a more
concise way to write the process.
variable = variable operator expression
count_emp = count_emp + 1;
variable operator = expression
count_emp += 1;
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Compound Assignment Operators


time = time - 1;
time -= 1;
total_time = total_time + time;
total_time += time;
product = product * item;
product *= item;
n = n * (x + 1);
n *= x + 1;
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

The for Statement


an alternate form of loop structure that
gives a more concise way to address
the 3 portions of loop control.
for (
initialization of the loop control variable,
test of the loop repetition condition,
change (update) of the loop control variable,
)
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

26

2/3/2015

The for Statement


loop control variable

total_pay = 0.0;
initialization
for (
count_emp = 0;
count_emp < number_emp;
loop repetition
count_emp += 1
condition test
)
{
printf("Hours> ");
loop control
variable change
scanf("%lf", &hours);
printf("Rate > $");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n\n", pay);
total_pay = total_pay + pay;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Increment & Decrement Operators


Operators used to increment or decrement
variables by values of 1.

operator variable
++counter
Side Effect a change in the value of a
variable as a result of carrying out an
operation.
Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

Placement of Increment or
Decrement Operators
Where the operator is placed upon the variable set
the time of Increment or Decrement.
Prefix Increment the expressions value is calculated
(up or down) and then used.

++variable

--variable

Postfix Increment the expressions value is used and


then calculated (up or down).

variable++

variable--

Structured Programming Using Procedural Languages  I NSS 225  Repetition & Loop Statements

Copyright 2009 Troy A. Zinderman

27

Вам также может понравиться