Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.
-
Upload
sean-lindsey -
Category
Documents
-
view
221 -
download
1
Transcript of Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.
Unit 4
“To Be or Not To Be”Programming Decisions
Introduction toC Programming
Review of Unit 3
Unit 4: Review of Past Material
Review of Past Concepts#include <stdio.h>#include <math.h>
typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t;
int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res;
res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0);}
Review - Expressions and Assignments#include <stdio.h>#include <math.h>
typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t;
int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res;
res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0);}
Review - Use of <math.h> Functions
#include <stdio.h>#include <math.h>
typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t;
int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res;
res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0);}
Review - The enum Data Type
#include <stdio.h>#include <math.h>
typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t;
int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res;
res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0);}
Review - Printf formatting#include <stdio.h>#include <math.h>
typedef enum { BLACK, BROWN, RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET, GRAY, WHITE } colorbands_t;
int main(void) { colorbands_t firstBand = ORANGE; colorbands_t secondBand = RED; colorbands_t thirdBand = BROWN; double res;
res = (firstBand * 10 + secondBand) * pow(10, thirdBand); printf("Resistance is %.f\n", res); return (0);}
Conditional Operators & Expressions
Unit 4: Conditional Expressions
Conditional ValuesAnother form of expression is a conditionalA conditional results from a comparison of two
valuesThe result of the conditional is 'true' or 'false'Boolean values
A boolean value is either 'true' or 'false'Many languages have a separate boolean data typeHowever, the C language does not have a boolean
typeC uses the int type
0 is interpreted as 'false'1 is interpreted as 'true' (or any other non-zero value)
Relational and Equality Operators
Table 4.1
Sample ConditionsGiven these values
x = -5 power is 1024 MAX_POW is 1024y is 7 item is 1.5 MIN_ITEM is -999.0num is 999 mom_or_dad is 'M' SENTINEL is 999
Table 4.2
Logical Operators
Used to modify and combine conditional expressions
&& means 'and'(temperature > 90) && (humidity > 0.90)
|| means 'or'(salary < MIN_SALARY) || (dependents > 5)
! means 'not'!(0 <= n && n <= 100)
Operator PrecedenceTable 4.6
Character Comparisons
Characters are encoded as numerical values
Therefore, the numerical values can be compared
Table 4.8
The 'if' Statement
Unit 4: Decision Structures
Single-Sided Branch (Flowchart Review)
The 'if' StatementBegins with keyword ifFollowed by conditional expression in
parenthesesConditional expression represents the question
A statement follows the conditionThe statement is only executed if the condition
is trueThe affected statement is indented
if (taxRate != 0.0)tax = price * taxRate;
The Compound StatementTo conditionally execute multiple statements
at onceEnclose them in bracesThis forms a compound statement
if (stopButtonPressed)
{
motor = 0; /* Stops motor */
alarmLight = 1; /* Lights alarm lamp */
}
Double-sided Branch (Flowchart Review)
The 'if-else' StatementBegins with keyword if, followed by
condition, and statement or compound statement
Next comes keyword elseFinally, another statement or compound
statementIf the first statement is not executed,
the statement following else is executed (one or the other)
if (x != 0)y = z / x;
elseprintf("Can't divide by zero!\n");
The 'if-else' With Compound Statements
if (ctri <= MAX_SAFE_CTRI){
printf("Car #%d: safe\n", auto_id);safe = safe + 1;
}else{
printf("Car #%d: unsafe\n", auto_id);
unsafe = unsafe + 1;
}
Example 4.13 p 175
Alternate Denser Formatting
if (condition){ statement; statement;}else{ statement; statement;}
if (condition) { statement; statement;} else { statement; statement;}
Nested if Statements (Version 1)
if (x > 0)num_pos = num_pos + 1;
else {
}
if (x < 0)num_neg = num_neg + 1;
else /* x equals 0 */num_zero = num_zero + 1;
Example 4.15 p 192
Nested if Statements (Version 2)
if (x > 0) {num_pos = num_pos + 1;
} else {
}
if (x < 0) {num_neg = num_neg + 1;
} else { /* x equals 0 */num_zero = num_zero + 1;
}
Cascaded if Statements
if (x > 0) {num_pos = num_pos + 1;
} else if (x < 0) {num_neg = num_neg + 1;
} else { /* x equals 0 */num_zero = num_zero + 1;
}
'if-else' Statement Example (cut-and-paste)
#include <stdio.h>
int main(void) {int number;printf("Enter a number: ");scanf("%d", &number);
if (number < 0){
printf("%d is negative\n", number);}else{
printf("%d is non-negative\n", number);}
return(0);}
Cascading 'if' Statement Example (cut-and-paste)
#include <stdio.h>
int main(void) {int number;printf("Enter a number: ");scanf("%d", &number);
if (number > 0) {printf("%d is positive\n", number);
} else if (number == 0) {printf("%d is zero\n", number);
} else {printf("%d is negative\n", number);
}
return(0);}
The 'switch' Statement
Unit 4: Decision Structures
Selection StructureSelection structure is an extension of the
branchAll branches must converge together at the
end
The 'switch' StatementBegins with keyword switch
Followed by parenthesized integer value and compound statement
Compound statement, called switch body, contains casesEach case keyword is followed by a constant value and a
colonTwo or more cases cannot have the same valueEach case contains statement(s) and ends with keyword break
If a case matches, its statements will be executedIf no case matches
The default case will be executedIf no default case, nothing is executed
Switch Statement Example (cut-and-paste)
#include <stdio.h>
int main(void) {int selection;printf("Enter selection: ");scanf("%d", &selection);
switch (selection) {case 1:
printf("ONE\n");break;
case 2:printf("TWO"\n");break;
default:printf("Not one or two\n");break;
}return (0);
}
Switch Statement Example (cut-and-paste)
#include <stdio.h>
int main(void) {int selection;printf("Enter selection: ");scanf("%d", &selection);
switch (selection) {case 1:
printf("ONE\n");break;
case 2:printf("TWO"\n");break;
default:printf("Not one or two\n");break;
}return (0);
}
Tips for Creating Good Programs
Unit 4: Programming Practices
Garbage In, Garbage Out
This well-known phrase captures the fact that programs do not produce good results when the input is “bad”
“Bad” input is input that does not meet the assumptions of the programmer
To counter this phenomenon, a program must performinput validation (checking of assumptions)
Input ValidationInput validation means checking input data for
“correctness”
Examples:A circle’s radius cannot be negativeNumbers cannot be arbitrarily largeA voltage may be negative, but a resistance cannot be
negative
The action taken for invalid data varies with the situationDon’t perform calculations with invalid dataProvide an error message that helps user correct the
problem
Example of Input Validation (cut-and-paste)
#include <stdio.h>
int main(void){
double dist_in_miles, dist_in_kms;
printf("Convert miles to kilometers\n");printf("Please enter the distance in miles: ");scanf("%lf", &dist_in_miles);
if (dist_in_miles < 0) {printf("A distance cannot be negative.\n");
} else {dist_in_kms = 1.609 * dist_in_miles;printf("The distance in kilometers is: ");printf("%f\n", dist_in_kms);
}
return (0);}
Using the C Language WiselyAlthough C permits an if-statement with
optional braces
if (condition)statement1;
next_statement;
It is wiser to always use the braces
if (condition) {statement1;
}next_statement;
That way, you will avoid …
A Common Programming ErrorWhen you add a statement and forget to add the
braces
if (condition)statement1;statement2; /* Added */
next_statement;
The statement2 looks like it is part of the if statement …
But, it is not! There are no braces!
Programs are changed all the time. Plan for maintenance!
Learning to Avoid and Correct Programming Errors
Unit 4: Programming Errors
Syntax Errors
• Code violates a grammar rule of C• Compiler locates syntax errors during
translation• Examples:– Missing semicolon– Undeclared or misspelled variables– Unclosed comments– Mismatched open and close braces, quotation
marks, or parentheses
Runtime ErrorDetected during program executionCaused by an attempt to perform an illegal
operationUsing invalid dataSending invalid data to library functionsExamples
Divide by 0 a / 0Remainder with 0 a % 0Logarithm of negative log(-5)
Logic Errors
Errors in the algorithm and/or flowchartCauses program to give incorrect resultsAvoid by desk-checking algorithm before
codingFinding a logic error can require
changing the algorithmand the program!
Beware These Common Errors!!Using int constants when double is intended
C = (5/9) * (F - 32);Since (5/9) is calculated as an int, it results in
0
Using assignment when equality is intendedif (x = 4) …
Equality is two equal signs, not one!The single equal sign causes assignment, x is
changed to 4!