Control Structures in C Overview 1)Logic & Logical Operators - - PDF document
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
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
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
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; }
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
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;
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*/
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
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; } }
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;}
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);
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:
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
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
15
Logical Operators Operators : “Short Circuit”
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); }
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); }
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.
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”
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
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.
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;}
23
switch statement switch statement
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
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 */
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; }
27
Looping Looping : Various Schemes
28
Looping : Types of Loops
Three main types of looping in C:
- for
(pretest)
- while (pretest)
- do …while (posttest)
The “for” Loop
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 */
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
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; }
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 */
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 */
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); }
35
The “do while” stmnt. do while
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