C Course - Lecture 4 - Making Decisions
C Course - Lecture 4 - Making Decisions
Lecture 4
Lecture 4: Outline
Making Decisions [chap 6 Kochan]
The if Statement The if-else Construct Logical Operators Boolean Variables Nested if Statements The else if Construct The switch Statement The Conditional Operator
Character Input/Output
The if statement
if ( expression ) program statement
If expression is true (non-zero), executes statement. If gives you the choice of executing statement or skipping it.
no
Example - if
// Program to calculate the absolute value of an integer int main (void) { int number; printf ("Type in your number: "); scanf ("%i", &number); if ( number < 0 ) number = -number; printf ("The absolute value is %i\n", number); return 0; }
yes
expression
no
Program statement 1
Program statement 2
Example: if-else
// Program to determine if a number is even or odd #include <stdio.h> int main () { int number_to_test, remainder; printf ("Enter your number to be tested: "); scanf ("%i", &number_to_test); remainder = number_to_test % 2; if ( remainder == 0 ) printf ("The number is even.\n"); else printf ("The number is odd.\n"); return 0; }
if ( remainder == 0 ) printf ("The number is even.\n"); else printf ("The number is odd.\n"); if ( x == 0 ); printf ("The number is zero.\n");
Logical operators
Operator AND OR NOT Symbol && || ! Meaning X && y is true if BOTH x and y are true X || y is true if at least one of x and y is true !x is true if x is false
Logical values as operands or in tests: true = non-zero, false=zero Logical values returned as results of expressions: true = 1, false=zero Example: 5 || 0 is 1
Example
Program to generate a table of all prime numbers up to 50
Boolean variables
// Program to generate a table of prime numbers #include <stdio.h> int main (void) { A flag: assumes only int p, d; one of two different int isPrime; values. The value of a for ( p = 2; p <= 50; ++p ) { flag is usually tested in isPrime = 1; the program to see if it for ( d = 2; d < p; ++d ) is on (TRUE) or off if ( p % d == 0 ) (FALSE) isPrime = 0; if ( isPrime != 0 ) printf ("%i ", p); } Equivalent test: printf ("\n"); (more in C-style): return 0; if (isPrime) }
Boolean variables
// Program to generate a table of prime numbers - rewritten #include <stdio.h> #include <stdbool.h> int main (void) { int p, d; bool isPrime; for ( p = 2; p <= 50; ++p ) { isPrime = true; for ( d = 2; d < p; ++d ) if ( p % d == 0 ) isPrime = false; if ( isPrime ) printf ("%i ", p); } printf ("\n"); return 0; }
Precedence of operators
Precedence
*, /, %
+, <, <=, >, >=, ==, != && || =
Example for operator precedence: a > b && b > c || b > d Is equivalent to: ((a > b) && (b > c)) || (b > d)
Because the order of evaluation for the <= operator is left-to-right, the test expression is interpreted as follows: (5<= x) <= 10 The subexpression 5 <= x either has the value 1 (for true) or 0 (for false). Either value is less than 10, so the whole expression is always true, regardless of x !
This works for character codes such as ASCII, in which the codes for consecutive letters are consecutive numbers. A more portable way: <ctype.h> : toupper(c), tolower(c)
Nested if statements
if (number > 5) if (number < 10) printf(1111\n"); else printf(2222\n"); Rule: an else goes with the most recent if, unless braces indicate otherwise
Example: else-if
// Program to implement the sign function #include <stdio.h> int main (void) { int number, sign; printf ("Please type in a number: "); scanf ("%i", &number); if ( number < 0 ) sign = -1; else if ( number == 0 ) sign = 0; else // Must be positive sign = 1; printf ("Sign = %i\n", sign); return 0; }
if
else if else
negative
zero
if ( expression 1) program statement 1 else if ( expression 2) program statement 2 else program statement 3
positive
Program style: this unindented formatting improves the readability of the statement and makes it clearer that a three-way decision is being made.
Example: else-if
// Program to categorize a single character // that is entered at the terminal #include <stdio.h> int main (void) { char c; printf ("Enter a single character:\n"); scanf ("%c", &c); if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) printf ("It's an alphabetic character.\n"); else if ( c >= '0' && c <= '9' ) printf ("It's a digit.\n"); else printf ("It's a special character.\n"); return 0; }
Example - switch
/* Program to evaluate simple expressions of the form value operator value */ #include <stdio.h> int main (void) { float value1, value2; char operator; printf ("Type in your expression.\n"); scanf ("%f %c %f", &value1, &operator, &value2); switch (operator) { case '+': printf ("%.2f\n", value1 + value2); break; case '-': printf ("%.2f\n", value1 - value2); break; case '*': printf ("%.2f\n", value1 * value2); break; case '/': if ( value2 == 0 ) printf ("Division by zero.\n"); else printf ("%.2f\n", value1 / value2); break; default: printf ("Unknown operator.\n"); break; } return 0; }
The switch test expression must be one with an integer value (including type char) (No float !). The case values must be integertype constants or integer constant expressions (You can't use a variable for a case label !)
switch (operator) { ... case '*': case 'x': printf ("%.2f\n", value1 * value2); break; ... }
Standard input/output
The C language itself does not have any special statements for performing input/output (I/O) operations; all I/O operations in C must be carried out through function calls. These functions are contained in the standard C library. #include <stdio.h> Formatted I/O: scanf(), printf() Character I/O: getchar(), putchar()
Arguments: variable names prefixed with the address operator (&) Example: scanf(%i %i,&x,&y);
The exceptions: in the case of the %c format characters the next character from the input, no matter what it is, is read scanf ("%f %c %f", &value1, &op, &value2);
3 <space> + <space> 5 <enter> 3 <space> + <space> <space> <enter> 5 <enter>
Any nonformat characters that are specified in the format string of the scanf call are expected on the input. scanf ("%i:%i:%i", &hour, &minutes, &seconds);
3:6:21<enter> 3<space>:<space>6<space>:<space>21<enter> 3<space>6<space>21<space> => NOT OK !
The next call to scanf picks up where the last one left off. scanf ("%f", &value1); User types: 7 <space> 8 <space> 9 <enter> 7 is stored in value1, rest of the input chars remain waiting in buffer scanf ("%f", &value2); 8 from buffer is stored in value2, rest of the input remains waiting
Example: getchar()
#include <stdio.h> int main(void) { char ch; while ((ch = getchar()) != '#') putchar(ch); return 0; }
Buffered input: the characters you type are collected and stored in a buffer. Pressing Enter causes the block of characters you typed to be made available to your program
getchar returns the next input character each time it is called, or EOF when it encounters end of file. EOF is a symbolic constant defined in <stdio.h>. (The value is typically -1) EOF from the keyboard: Ctrl+Z
Exercise: getchar()
/* Read characters from input over several lines until EOF. Count lines and characters in input */ #include <stdio.h> int main(void) { int c, nl, nc; nl = 0; nc = 0; while ((c = getchar()) != EOF) { nc++; if (c == '\n') nl++; } printf("Number of lines in input: %d\n", nl); printf("Number of characters in input: %d\n", nc); return 1; }