Programming Notes
description
Transcript of Programming Notes
-
2/3/2015
1
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Review of CReview of C
Week 2Week 2
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
A C ProgramA C Program
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
/** Converts distance in miles to kilometers.*/
/* printf, scanf definitions *//* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
#include #define KMS_PER_MILE 1.609
A C ProgramA C Program
Preprocessor Directives
#include #define KMS_PER_MILE 1.609
-
2/3/2015
2
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Preprocessor DirectivesPreprocessor 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The #include DirectiveThe #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:
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:
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The #define DirectiveThe #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
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
-
2/3/2015
3
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
A C ProgramA C Program
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
/* printf, scanf definitions *//* conversion constant */
/* input - distance in miles. *//* output - distance in kilometers */
/* Get the distance in miles. */
/* Convert the distance to kilometers. */
/* Display the distance in kilometers. */
/** Converts distance in miles to kilometers.*/
#include #define KMS_PER_MILE 1.609
intmain(void){
double miles,kms;
printf("Enter the distance in miles> ");scanf("%lf", &miles);
kms = KMS_PER_MILE * miles;
printf("That equals %f kilometers.\n", kms);
return (0);}
/** Converts distance in miles to kilometers.*/
A C ProgramA C Program
Comments
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Program CommentsProgram 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. */
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. */
-
2/3/2015
4
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Program Comments (cont.)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.
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.
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
CommentsComments
/*
* Programmer: Troy Zinderman
* Date Completed: September 23, 2005
* Class: INSS209
*
* Calculates final grade of students based
* on assignment weights
*
*/
/*
* 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.
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
A C ProgramA C Program
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
intmain(void){
double miles, /* input - distance in miles. */kms; /* 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);}
-
2/3/2015
5
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
/** Converts distance in miles to kilometers.*/
#include /* printf, scanf definitions */#define KMS_PER_MILE 1.609 /* conversion constant */
/* input - distance in miles. *//* output - distance in kilometers */
/* Get the distance in miles. */
/* Convert the distance to kilometers. */
/* Display the distance in kilometers. */
printf("Enter the distance in miles> ");scanf("%lf", &miles);
kms = KMS_PER_MILE * miles;
printf("That equals %f kilometers.\n", kms);
return (0);}
intmain(void){
double miles, kms;
A C ProgramA C Program
Main Function
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Main FunctionMain 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Function ComponentsFunction 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.
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.
-
2/3/2015
6
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Function Punctuation & SymbolsFunction 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Reserved WordsReserved 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Standard IdentifiersStandard 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
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
-
2/3/2015
7
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
User-Defined IdentifiersUser-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.
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.
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
User-Defined Identifier Rules & Recommendations
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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Back to Declarations 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.
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.
-
2/3/2015
8
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Variable DeclarationVariable Declaration
double miles, /* input - distance in miles. */kms; /* output - distance in kilometers */
double miles, /* input - distance in miles. */kms; /* output - distance in kilometers */
Variable Identifier
(Name)
Variable Data TypeComments describing
variable purpose
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Data TypesData 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).
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).
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Integer Data Type (int)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
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
-
2/3/2015
9
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Double Floating-Point Data Type (double)
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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Character Data Type (char)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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
On to Executable StatementsOn to Executable Statements
Assignment Statement an instruction
that stores a value or a
computational result in a variable.
kms = KMS_PER_MILES * miles;
Assignment Statement an instruction
that stores a value or a
computational result in a variable.
kms = KMS_PER_MILES * miles;
Constant Macro
Variable Identifier
Assignment
Operator (=)
-
2/3/2015
10
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Before & After StatesBefore & After States
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Assignment Statements (continued)
Assignment Statements (continued)
sum = sum + item;sum = sum + item;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Executable Statements (continued)
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 pre-processor directive:
#include
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 pre-processor directive:
#include
-
2/3/2015
11
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Print Formatted Function (printf)
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);
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);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
printf(That equals %f kilometers.\n, kms);printf(That equals %f kilometers.\n, kms);
printf Function Componentsprintf Function Components
Function Name
Function Argument
Format String
printf(That equals %f kilometers.\n, kms);printf(That equals %f kilometers.\n, kms);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
printf(That equals %f kilometers.\n, kms);printf(That equals %f kilometers.\n, kms);
printf Function Componentsprintf Function Components
Print List
Placeholder
-
2/3/2015
12
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Placeholders used in printfPlaceholders 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Escape SequencesEscape 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.
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.
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Newline Escape SequenceNewline 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);
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);
-
2/3/2015
13
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Scan Format Function (scanf)
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);
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);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
A Note on scanfA 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Placeholders used in scanfPlaceholders used in scanf
Uses the same placeholders as printffor 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
Uses the same placeholders as printffor 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
-
2/3/2015
14
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
scanf(%lf, &miles);scanf(%lf, &miles);scanf(%lf, &miles);
scanf Function Componentsscanf Function Components
VariablePlaceholder
Address-of
operator
scanf(%lf, &miles);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Address-of OperatorAddress-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).
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).
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Effect of scanfEffect of scanf
-
2/3/2015
15
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
How a data line is scannedHow a data line is scanned
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
The Return StatementThe 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);
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);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Arithmetic ExpressionsArithmetic Expressions
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
-
2/3/2015
16
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Evaluation Tree for areaEvaluation Tree for area
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
Step-by-Step Expression EvaluationStep-by-Step Expression Evaluation
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
v = (p2 - p1) / (t2 - t1)v = (p2 - p1) / (t2 - t1)
-
2/3/2015
17
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Overview of C
z - (a + b / 2) + w * -yz - (a + b / 2) + w * -y
Copyright 2009 Troy A. Zinderman
Control StructuresControl 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.
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 INSS 225 Overview of C
Copyright 2009 Troy A. Zinderman
Compound StatementCompound Statement
{statement1;
statement2;
statement3;
.
.
.
.
.
statement n;}
{statement1;
statement2;
statement3;
.
.
.
.
.
statement n;}
Structured Programming Using Procedural Languages INSS 225 Overview of C
-
2/3/2015
18
Copyright 2009 Troy A. Zinderman
ConditionsConditions
Condition an expression that is either false (represented by 0) or true
(represented by 1).
rest_heart_rate > 75
Condition an expression that is either false (represented by 0) or true
(represented by 1).
rest_heart_rate > 75
Structured Programming Using Procedural Languages INSS 225 Overview of C
Copyright 2009 Troy A. Zinderman
Relational & Equality Operators
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
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 INSS 225 Overview of C
Copyright 2009 Troy A. Zinderman
Relational & Equality OperatorsRelational & Equality Operators
Operator Meaning Type
< Less than Relational
> Greater than Relational
= Greater than or equal to
Relational
== Equal to Equality
!= Not equal to Equality
Structured Programming Using Procedural Languages INSS 225 Overview of C
-
2/3/2015
19
Copyright 2009 Troy A. Zinderman
Logical OperatorsLogical Operators
Logical Expression an expression that uses one or more of the logical operators && (and), || (or), ! (not).
n >= 0 && n 5
Logical Expression an expression that uses one or more of the logical operators && (and), || (or), ! (not).
n >= 0 && n 5
Structured Programming Using Procedural Languages INSS 225 Overview of C
Copyright 2009 Troy A. Zinderman
Logical ComplementLogical 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
-
2/3/2015
20
Copyright 2009 Troy A. Zinderman
Short-Circuit EvaluationShort-Circuit Evaluation
Stopping evaluation of a logical expression as soon as its value can be
determined.
x = 0 y = 6
x > 2 && y > 5
x > 2 || y > 5
Stopping evaluation of a logical expression as soon as its value can be
determined.
x = 0 y = 6
x > 2 && y > 5
x > 2 || y > 5Structured Programming Using Procedural Languages INSS 225 Overview of C
Copyright 2009 Troy A. Zinderman
Comparing CharactersComparing Characters
Expression Value
9 >= 0 1 (true)
a < e 1 (true)
B
-
2/3/2015
21
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
SelectionSelection
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);
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);
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
Types of SelectionTypes of Selection
One alternative:
if (condition)
statement;
Two alternatives:
if (condition)
statement;
else
statement;
One alternative:
if (condition)
statement;
Two alternatives:
if (condition)
statement;
else
statement;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
Compound Statements within if Statements
Compound Statements within if Statements
if (condition){
statement1;statement1;statement1;
}else{
statement1;statement1;statement1;
}
if (condition){
statement1;statement1;statement1;
}else{
statement1;statement1;statement1;
}
-
2/3/2015
22
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
Nested if StatementsNested 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;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
ifs in Sequenceifs 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;
if (x > 0)
num_pos = num_pos + 1;
if (x < 0)
num_neg = num_neg + 1;
if (x == 0)
num_zero = num_zero + 1;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
Multiple-Alternative Decision FormMultiple-Alternative Decision Form
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
else
statement;
if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
else
statement;
-
2/3/2015
23
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
The switch StatementThe switch Statement
switch (controlling expression) {label set:
statements;break;
label set:statements;break;
label set:statements;break;
default:statements;
}
switch (controlling expression) {label set:
statements;break;
label set:statements;break;
label set:statements;break;
default:statements;
}
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Selection Structures
The switch StatementThe 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;
}
switch (watts) {case 25:
life = 2500;break;
case 40:case 60:
life = 1000;break;
case 75:case 100:
life = 750;break;
default:life = 0;
}
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Repetition in ProgramsRepetition 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.
Loop a control structure that repeats a group of steps in a program.
Loop Body the statements that are repeated in the loop body.
-
2/3/2015
24
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Kinds of LoopsKinds 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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Counting LoopsCounting 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
The while StatementThe while Statement
count_emp = 0;
while (count_emp < 7)
{
printf("Hours> ");
scanf("%d", &hours);
printf("Rate> ");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1;
}
printf("\nAll employees processed\n");
count_emp = 0;
while (count_emp < 7)
{
printf("Hours> ");
scanf("%d", &hours);
printf("Rate> ");
scanf("%lf", &rate);
pay = hours * rate;
printf("Pay is $%6.2f\n", pay);
count_emp = count_emp + 1;
}
printf("\nAll employees processed\n");
No Employees
Processed Yet
Testing
Condition
Increment
Control Variable
-
2/3/2015
25
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
The Infinite LoopThe 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 )
a loop that executes forever due to an erroneous control condition evaluation or an
erroneous incrementing of the control variable.
while ( 1 != 2 )
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Computing Sums or ProductsComputing 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
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
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Computing Sums or ProductsComputing Sums or Products
total_pay = 0.0;
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;
count_emp = count_emp + 1;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);
total_pay = 0.0;
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;
count_emp = count_emp + 1;
}
printf("All employees processed\n");
printf("Total payroll is $%8.2f\n", total_pay);
No Pays
Calculated Yet
Pay Accumulator
Variable
-
2/3/2015
26
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Compound Assignment OperatorsCompound 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;
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;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Compound Assignment OperatorsCompound 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;
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;
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
The for StatementThe 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,
)
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,
)
-
2/3/2015
27
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
The for StatementThe for Statement
total_pay = 0.0;for (
count_emp = 0; count_emp < number_emp; count_emp += 1
) {
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;
}printf("All employees processed\n");printf("Total payroll is $%8.2f\n", total_pay);
total_pay = 0.0;for (
count_emp = 0; count_emp < number_emp; count_emp += 1
) {
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;
}printf("All employees processed\n");printf("Total payroll is $%8.2f\n", total_pay);
loop control variable
initialization
loop repetition
condition test
loop control
variable change
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Increment & Decrement OperatorsIncrement & 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.
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.
Copyright 2009 Troy A. ZindermanStructured Programming Using Procedural Languages INSS 225 Repetition & Loop Statements
Placement of Increment or
Decrement Operators
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--
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--