Control Structures in C Overview 1)Logic & Logical Operators - - PDF document

control structures in c overview
SMART_READER_LITE
LIVE PREVIEW

Control Structures in C Overview 1)Logic & Logical Operators - - PDF document

Control Structures in C Overview 1)Logic & Logical Operators 2)Selection Mechanisms if elseif else switch 3)Loop Mechanisms 1 Logic and Selection In English (Natural Language) we can make statements such as: If it snows I stay


slide-1
SLIDE 1

1

Control Structures in C Overview

1)Logic & Logical Operators 2)Selection Mechanisms

– if elseif else – switch

3)Loop Mechanisms

slide-2
SLIDE 2

2

Logic and Selection

In English (Natural Language) we can make statements such as: If it snows I stay home otherwise I go out. If I feel energetic and it’s Tuesday I come to class.

  • Logical expression must be unambiguous

– Either do it – Or do not do it – No maybe

  • So we have logical expressions or

Boolean expressions which evaluate to true

  • r false
slide-3
SLIDE 3

3

Some logical expressions in c. Remember they have to have a value true or false. x > 7 salary < 1000 date ==30 note: equals is == letter != ‘c’ note != is not equals amount >= 3.50

Relational Operators: The operators that can be used to make simple logical expressions

slide-4
SLIDE 4

4

The “if” statement

int x=5; if ( x>3) printf(“x is greater than 3\n”); Effect: if x>3 is true it prints otherwise it just goes on to next statement Another Example

int main(void) { char character; printf("\n Please enter a single character\n"); scanf("%c",&character); if ( character == ‘y') printf("\n you typed the character '%c'\n",character); return 0; }

slide-5
SLIDE 5

5

Another Example

int main(void) { char character; printf("\n Please enter a single character\n"); scanf("%c",&character); if ( character == 121) printf("\n you typed the character '%c'\n",character); return 0; }

Logical Data

  • In C the Boolean type doesn’t exit.

– 0 is false – Everything else is true

slide-6
SLIDE 6

6

A common mistake which may drive you crazy. instead of if ( character == 'c')… you type if ( character = 'c')… This is legal but is wrongly evaluated (logically)

INDENTING

  • Note indentation of code is ignored by compiler
  • Essential for readability

char character; printf("\n Please enter a single character\n"); scanf("%c",&character); if ( character == 'c') printf("\n you typed the character '%c'\n",character); return 0;

slide-7
SLIDE 7

7

So the general form of the if is:

if ( logical expression) statement;

Note no semi-colon on the “if”. The whole thing is one statement.

if-else

General format: if ( logical statement) statement; /* if true….note indent*/ else statement; /* if false….note indent*/

slide-8
SLIDE 8

8

int main(void) { char character; printf("\n Please enter a single character\n"); scanf("%c",&character); if ( character == ‘y') printf("\n you typed a '%c'\n",character); else printf("\n I did not expect a %c\n",character); return 0; }

Syntax : if-else

slide-9
SLIDE 9

9

Flow charts- a graphical view

  • f if-else

Compound statements. “if”

if ( condition) if ( x>5) statement; x++; if ( condition) if (i ==10) { statement; { x = x+5; statement; y = x = 5; } }

slide-10
SLIDE 10

10

Compound statements if -else

if ( condition) { statement; statement; } else {statement; statement; } Note that no braces are needed for a single statement.

#include <stdio.h> int main ( void ) { const float min_pst= 4.00; const float gst = 0.05; /*2008 rates */ const float pst = 0.08; /*2008 rates */ float bill, total; printf("Please input the amount of the bill\n"); scanf("%f",&bill); if (bill < min_pst) total = bill * (1.0 + gst); else total = bill * (1.0 + gst + pst); printf ("The total bill is: %10.2f\n",total); return 0;}

slide-11
SLIDE 11

11

#include <stdio.h> int main ( void ) { const float min_pst= 4.00; const float gst = 0.05; /*2008 rates */ const float pst = 0.08; /*2008 rates */ float bill, total; printf("Please input the amount of the bill\n"); scanf("%f",&bill); if (bill < min_pst) total = bill * (1.0 + gst); else printf(“in else statement bill=%f\n”,bill); total = bill * (1.0 + gst + pst); printf ("The total bill is: %10.2f\n",total); return 0;}

Another Example - Multiple ifs

#include <stdio.h> /* calculate the maximum value of three numbers */ int main ( void ){ int number1, number2, number3; int max; printf(“Please input three numbers:\n”); scanf(“%d%d%d”,&number1,&number2,&number3);

slide-12
SLIDE 12

12

Another Example - Multiple ifs

max = number1; /* From Previous Slide */ if ( number2 > max) max = number2; if (number3 > max) max = number3; printf("The maximum of the three numbers: %d,%d,%d is = %d\n", number1, number2, number3, max); return(0); }

Selecting from among many things. Example: If I type in a letter grade, namely A,B,C,D,F, I want to print out the range of numerical equivalences. e.g. C is between 60 and 69.9% We can do this correctly but not in the best way as follows:

slide-13
SLIDE 13

13

#include <stdio.h> int main(void){ char grade; printf("please enter a letter grade\n"); scanf("%c",&grade); if (grade =='A') printf("your grade is between 80 and 100%%\n"); if (grade =='B') printf("your grade is between 70 and79.9%%\n") if (grade =='C') printf("your grade is between 60 and69.9%%\n"); if (grade =='D') printf("your grade is between 50 and59.9%%\n"); if (grade =='F') printf("your grade is less than 50%%\n"); return 0;

Expanding the logical expression

There are 3 more boolean or logical operators Which allow for more complicated expressions. They are: || logical OR && logical AND ! Logical NOT

slide-14
SLIDE 14

14

These allow for making compound logical expressions. Is x between 2 and 5 inclusive? 2 5 (x>=2) && (x<=5) Note: for the AND to be true both propositions must be true. The && (AND) Proposition1 && Proposition2 Proposition1 Proposition2 RESULT True True True True False False False True False False False False So for the result to be true both propositions must be true

slide-15
SLIDE 15

15

Logical Operators Operators : “Short Circuit”

slide-16
SLIDE 16

16

Another Example - Multiple ifs

#include <stdio.h> // Assign a letter grade to a mark out of 100 : Inefficient*/ int main ( void ){ int grade; char letter_grade; printf("Please enter a mark out of 100: "); scanf(“%d”,&grade); if ( grade >= 80 ) letter_grade = 'A'; /* Continues on Next Slide */ if ( grade >= 70 && grade < 80 ) /*After Previous Slide */ letter_grade = 'B'; if ( grade >= 60 && grade < 70 ) letter_grade = 'C'; if ( grade >= 50 && grade < 60 ) letter_grade = 'D'; if (grade < 50) letter_grade = 'F'; printf(" A mark of %d is an %c\n”, grade, letter_grade); return(0); }

slide-17
SLIDE 17

17

Same Example - ifs and elseifs

#include <stdio.h> /* Assign a letter grade to a mark out of 100 */ /* Efficient using nested ifs (else if's) ; Note indenting */ int main ( void ) { int grade; char letter_grade; printf("Please an integer mark out of 100: "); scanf(“%d”, &grade); if (grade > 100 || grade <0) printf(" I'm afraid you have made an error in input \n"); else if ( grade >= 80) letter_grade = 'A'; /* Continues on Next Slide */

Same Example - ifs and elseifs

else if ( grade >= 70) /* After Previous slide */ letter_grade = 'B'; else if ( grade >= 60) letter_grade = 'C'; else if ( grade >= 50 ) letter_grade = 'D'; else letter_grade = 'F'; if (grade >= 0 && grade <= 100 ) printf(" A grade of %d is an %c\n”, grade, letter_grade); return(0); }

slide-18
SLIDE 18

18

Compound logical expressions with || (OR). Is today the first or 15th of the month? (dayOfMonth == 1) || (dayOfMonth == 15) This is true is either propostion is true: Obviously in this case both can’t be true. The || (OR) Proposition1 || Proposition2 Proposition1 Proposition2 RESULT True True True True False True False True True False False False So for the result to be false both propositions must be false.

slide-19
SLIDE 19

19

The NOT operator (!) inverts the value of a logical expression. It is a unary operator. x=7; The expression !(x==7) is False since the expression (x==7) is true. The NOT is usually confusing and should be used sparingly

Nested if else “an if within an if”

slide-20
SLIDE 20

20

Example: Printing out the number of days in each

  • month. Assume that the months are integers from

1 to 12. For now just do february. int year, month, numberOfdays; if (month == 2) {if ((year%4) == 0) numberOfDays=29; else numberOfDays=28; }

Dangling elses…..danger

Suppose I write the last code without braces:To which if does the else belong. The indenting is irrelevant if (month == 2) if ((year%4) == 0) numberOfDays=29; else numberOfDays=28; Rule: the else belongs to the nearest if. Better use braces For nested ifs

slide-21
SLIDE 21

21

Suppose I write this without braces: if (expression) if ( expression) statement; else statement; In fact this means the same as before so use braces. if (expression) {if ( expression) statement;} else {statement;} Unambiguous to user.

slide-22
SLIDE 22

22

Next slide: If you enter a month and year how many days in the month. Solution: the 1,3,5,7,8,10,12th month are 31 the 4, 6, 9, 11th month are 30 february is 28 except on a leap year when it is 29.

#include <stdio.h> int main(void){ int month, year, numberOfDays; printf("please enter month and year as integers\n"); scanf("%d%d",&month,&year); if ((month == 1) || (month == 3)|| (month == 5)|| (month == 7) || (month == 8) || (month == 10)|| (month == 12)) {numberOfDays=31;} if ((month == 4) || (month == 6)|| (month == 9)|| (month == 11)) {numberOfDays=30;} if (month == 2) {if ((year%4) == 0) numberOfDays=29; else numberOfDays=28; } printf("\nthe number of days is: %d\n\n", numberOfDays); return 0;}

slide-23
SLIDE 23

23

switch statement switch statement

slide-24
SLIDE 24

24

switch statement

/* program fragment to demo switch*/ switch (printflag) { case 1: printf(“this is case 1\n”); case 2: printf(“this is case 2\n”); default: printf(“this is default\n”); } /* switch */

Semantics : switch

slide-25
SLIDE 25

25

Semantics : switch ; break Example - Case Statement

#include <stdio.h> /*Interpreting Letter Grades */ int main( ) { char letter_grade; printf(“Enter your letter grade and press return: “); scanf(“%c”, letter_grade); switch (letter_grade) { case 'A': printf(”Your mark is between 80 and 100\n"); break; /*Continues on Next slide */

slide-26
SLIDE 26

26

Example - Case Statement

case 'B': /* After Previous Slide */ printf(" Your mark is between 70 and 79\n"); break; case 'C': printf("Grade is between 60 and 69\n"); break; case 'D': printf("Grade is between 50 and 59\n"); break; /* Continues on Next Slide */

Example - Case Statement

case 'F': /* After Previous Slide */ printf("Grade is below 50\n"); break; default: printf("You have typed in an illegal letter\n"); } return 0; }

slide-27
SLIDE 27

27

Looping Looping : Various Schemes

slide-28
SLIDE 28

28

Looping : Types of Loops

Three main types of looping in C:

  • for

(pretest)

  • while (pretest)
  • do …while (posttest)

The “for” Loop

slide-29
SLIDE 29

29

Example 1 : For Loops

Example: Output integers from 1 to 3 #include <stdio.h> int main(void) { int i; for (i=0; i<3;i++) printf("count=%d\n", i ); /* Note the Output */ return 0 ; } Output : count = 0 count = 1 count = 2

Example 2 : For Loops

Example: Average of Group of Numbers #include <stdio.h> int main () { int count, sum, number, i; printf(" How many numbers are to be averaged?\n"); scanf(“%d”, &count); sum = 0; for (i=1; i<=count; i++) { printf("Enter the next number in the list %d: "); scanf(“%d”, &number); sum += number; /* Continues on Next Slide */

slide-30
SLIDE 30

30

Example 2 : For Loops

sum += number; /* From Previous Slide */ printf(“\n”); } printf("The average is: %f\n", (sum / (double) count )); /* note casting to double */ return(0); }

while

slide-31
SLIDE 31

31

Syntax : “while” Loops

while (boolean-expression) { body of the loop; /*Note the Indenting */ } Important Remarks :

  • While Loops may do the loop zero times.
  • This is an indeterminate loop.
  • Something must change in the loop or it is an infinite loop.

Syntax : “while” Loops

So a typical use is: Initialize conditions while (condition is true) { body of the loop; /* Note the Indenting */ change condition inside loop; }

slide-32
SLIDE 32

32

Example 1 : while Loops

Modify the average program to prompt for integers repeatedly. Stops when a negative number is entered. What about case where the first number = -1??? #include <stdio.h> int main ( void ) { int count, sum, anInteger; printf("Enter the integers and terminate with -1\n"); count 0; sum = 0; /*Continues on Next Slide */

Example 1 : while Loops

printf(“Enter number %d:”, count+1); /*After Prev. Slide */ scanf(“%d”, &anInteger); while (anInteger >= 0) { sum += anInteger; count++; printf(“Enter number %d:”, count+1); scanf(“%d”, &anInteger); } /*Continues on Next Slide */

slide-33
SLIDE 33

33

Example 1 : while Loops

if (count != 0) /*After Previous Slide */ printf("The average is %f\n", sum / (double) count); else printf("You entered no numbers\n"); return(0); }

Example 2 : while Loops

Modify the initial values of count and anInteger Make sure that it goes into the loop Only do the prompting within the loop. #include <stdio.h> int main ( void ) { int count, sum, anInteger; printf("Enter integers; terminate with -1\n"); count = 0; sum = 0; /*Continues on Next Slide */

slide-34
SLIDE 34

34

Example 2 : while Loops

sum = 0; /*From Previous Slide */ anInteger = 0; /* Note the initializing condition */ while (anInteger >= 0) { sum += anInteger; count++; printf(“Enter number %d: “, count); scanf(“%d”, &anInteger); } /*Continues on Next Slide */

Example 2 : while Loops

if (count-1 != 0) /*After Previous Slide */ printf(“The average is %f\n", sum /( double) --count); else printf(“You entered no numbers”); return(0); }

slide-35
SLIDE 35

35

The “do while” stmnt. do while

slide-36
SLIDE 36

36

Syntax : “do-while” Loops

do { body of the loop; } while (check-expression); Note that

  • Loop executed at least once
  • Must change expression or it is an infinite loop
  • Does not need initializing before loop is entered

Syntax : “do-while” Loops

Example: Use for checking for correct input do { input data; } while (data is incorrect);

slide-37
SLIDE 37

37

Syntax : “do-while” Loops

Use this construct to prompt for a positive number ? If a negative number is entered, then prompt again.... int anInteger=0; do { printf(“Enter a positive integer: “); scanf(“%d”, &anInteger); } while (anInteger < 0); Note: The terminating condition is the integer itself.