Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

43
Unit 4 “To Be or Not To Be” Programming Decisions Introduction to C Programming

Transcript of Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Page 1: 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

Page 2: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Review of Unit 3

Unit 4: Review of Past Material

Page 3: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 4: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 5: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 6: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 7: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 8: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Conditional Operators & Expressions

Unit 4: Conditional Expressions

Page 9: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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)

Page 10: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Relational and Equality Operators

Table 4.1

Page 11: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 12: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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)

Page 13: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Operator PrecedenceTable 4.6

Page 14: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Character Comparisons

Characters are encoded as numerical values

Therefore, the numerical values can be compared

Table 4.8

Page 15: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

The 'if' Statement

Unit 4: Decision Structures

Page 16: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Single-Sided Branch (Flowchart Review)

Page 17: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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;

Page 18: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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 */

}

Page 19: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Double-sided Branch (Flowchart Review)

Page 20: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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");

Page 21: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 22: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Alternate Denser Formatting

if (condition){ statement; statement;}else{ statement; statement;}

if (condition) { statement; statement;} else { statement; statement;}

Page 23: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 24: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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;

}

Page 25: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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;

}

Page 26: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

'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);}

Page 27: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 28: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

The 'switch' Statement

Unit 4: Decision Structures

Page 29: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Selection StructureSelection structure is an extension of the

branchAll branches must converge together at the

end

Page 30: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 31: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);

}

Page 32: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);

}

Page 33: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Tips for Creating Good Programs

Unit 4: Programming Practices

Page 34: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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)

Page 35: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 36: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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);}

Page 37: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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 …

Page 38: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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!

Page 39: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

Learning to Avoid and Correct Programming Errors

Unit 4: Programming Errors

Page 40: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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

Page 41: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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)

Page 42: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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!

Page 43: Unit 4 To Be or Not To Be Programming Decisions Introduction to C Programming.

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!