Date post: | 14-Dec-2015 |
Category: |
Documents |
Upload: | stephen-isham |
View: | 226 times |
Download: | 2 times |
Making Choices in C
if/else statement
logical operators
break and continue statements
switch statement
the conditional operator
The if Statement
• Formatif ( condition )program statement;
orif ( condition ) {program statements;
}
• Flow
Condition true?
Program statements
Yes
No
Example
• Calculating the absolute value of an integer
number < 0
number = - number;
Yes
No
printf(“type in your number: “);scanf(“%i”, &number);
if ( number < 0 )number = -number;
printf(“\nThe absolute value is %i\n”, number);
The if-else Statement
• Formatif ( condition )
program statement 1;
else
program statement 2;
• Flow
condition true?
program statement 1
Yes
No
program statement 2
The else if Statement
• Formatif ( condition1 )
program statement 1;
else if (condition2)
program statement 2;
• Flow
condition1 true?
program statement 1
Yes
No
condition2 true?
No
program statement 2
Yes
One exampleif (condition1)
program statement 1;
else if (condition2)
program statement 2;
else
program statement 3;
condition1 true?
program statement 1
Yes
No
condition2 true?
No
program statement 3program
statement 2
Yes
Boolean Variables
• Declaration– Boolean variables are represented by integers
• Value– 0 represents false– 1 representing true, mostly
• Any nonzero value represents true in C
Logical Operators
• Why– Make a decision based on multiple conditions
• What are they
Operator Example Description
|| x < 0 || x > width logical OR
&& x >= 0 && x <= width logical AND
! !(x < 0) logical NOT
Logical OR
• Returns false only if both expressions are false
• Example:for (i=5 ; i<=95; i+=5) {
if((i < 35) || (i > 60)) {
printf(“%i”, i);
}
}
A B A || B
True True True
True False True
False True True
False False False
Logical AND
• Returns true only if both expressions are true
• Example:for (i=5 ; i<=95; i+=5) {
if((i > 35) && (i < 60)) {
printf(“%i”, i);
}
}
A B A && B
True True True
True False False
False True False
False False False
Logical NOT
• Inverts the Boolean value of an expression
• Example:
int a = 0;
if (!a) {
printf(“a is not 0\n”);
}
a = 1;
if (a) {
printf(“a is 1\n”);
}
A !A
True False
False True
Conditional Expressions
• Relational expression using ==, !=, >, >=, <, <=– The value of “relational expression” is 1 if the relation is true, and
0 if false.
• Operators can be combined with logical operators (with decreasing precedence):– ! (NOT)– && (AND)– || (OR)
• Rules:– && and || are evaluated left to right
• Example:c==' ' || c=='\t' || c=='\n'
Example: Giving Final Grade
A(100-90), B(89-80),C(79-70),D(69-60),F(59-0)
if (score >= 90) grade = ‘A ’;else if (score >= 80) grade = ‘B ’;else if (score >= 70) grade = ‘C ’;else if (score >= 60) grade = ‘D ’;else grade = ‘F ’;
Evaluate a simple expression
• Objective:– Evaluate expression and display results with
input in the form:number operator number
• Example– User input: 12 + 3– Program output: 15
Program#include <stdio.h>
int main(void){ float v1, v2; char operator;
printf("Type in your expression: \n"); scanf("%f %c %f", &v1, &operator, &v2);
if ( operator == '+' ) printf("%.2f\n", v1 + v2); else if ( operator == '-' ) printf("%.2f\n", v1 - v2); else if ( operator == '*' ) printf("%.2f\n", v1 * v2); else if ( operator == '/' ) printf("%.2f\n", v1 / v2);
return 0;}
Need to check v2 == 0?
Corrections
• Changeelse if ( operator == '/' )
printf("%.2f\n", v1 / v2);
toelse if ( operator == '/' )
if ( v2 == 0 )
printf(“Division by zero.\n”);
else
printf("%.2f\n", v1 / v2);
Watch Out for This!!!
• The assignment operator “=“ and the equality operator “==“ ARE VERY DIFFERENT, DO NOT CONFUSE THEM!
• This code compiles and runs, but does not do what you may expect:
if (x = 0) {
x = 1;
}
printf(“x = %i\n,x);
How to get out of a loop prematurely?
• Use the break statement– Skips all subsequent statements in the loop – Exits immediately from the current loop– Continues execution after the loop
• Or the continue statement– Skip subsequent statements in the current iteration– Continue execution with the next iteration
Example – summation of valid scores
int count, n = 10, sum = 0, score;
for (count = 0; count < n; count++){
scanf("%d", &score);
if (score < 0 || score > 100)
continue;
sum = sum + score;
}
Example – summation of valid scores
int count, n = 10, sum = 0, score;
for (count = 0; count < n, count++) {
scanf("%d", &score);
if (score < 0 || score > 100) {
printf(“Bad data. Exiting\n”);
break;
}
sum = sum + score;
}
The switch Statement• When to use
– The value of a variable successively compared against different values
• Formatswitch( expression ) {
case value 1: program statement 1; break;
case value 2: program statement 2; break; ׃׃
case value n: program statement n; break;
default : program statement n+1; break;
}
== value 1
evaluate expression
statement 1Y
N
== value 2
== value n
N
Nstatement n+1
Ystatement 2
Ystatement n
Example switch ( operator ) { case '+': printf("%.2f\n", v1 + v2); break; case '-': printf("%.2f\n", v1 - v2); break; case '*': printf("%.2f\n", v1 * v2); break; case '/': if ( v2 == 0 ) printf(“Division by zero.\n”); else printf("%.2f\n", v1 / v2); break; default: printf("Unknown operator!\n"); break; }
Another exampleswitch (month) { case 1: printf("January"); break; case 2: printf("February"); break; case 3: printf("March"); break; case 4: printf("April"); break; case 5: printf("May"); break; case 6: printf("June"); break; case 7: printf("July"); break; case 8: printf("August"); break; case 9: printf("September"); break; case 10: printf("October"); break; case 11: printf("November"); break; case 12: printf("December"); break; default: printf("Invalid month."); break; }
More on switch Statement
case value 1:
statement 1;
case value 2: statement 2;
break;
== value 1 statement 1Y
N
== value 2
N
Ystatement 2
Usually, this is a BUG! And one that is often very hard to find! “MISSING BREAK”