Gaining Control in C
Gaining Control in C
CSI 2101
September, 2013
GAINING CONTROL in C
Lecture Outline: 1. 2. 3. 4. 5. 6. Expressions and statements, Blocks & Compound statements, Flow- Control Constructs Nested Constructs Using logical operators Using Relational operators
N.B.: There is no semicolon after the right (closing) bracket that ends a block.
Page 1 of 11
CSI 2101
September, 2013
3. Control-Flow Constructs
Control-flow constructs are statements which specify the order in which instructions are performed. There are three control types of control constructs in C: 1. Sequential The next instruction to be executed comes immediately after the preceding statement. 2. Selection The next instruction to be executed is determined by the result of some decision 3. Repetition One or more instructions are executed repeatedly while some condition remains true. Execution of the instruction(s) stops when the condition becomes false.
3.1.
3.2.
These include: if if-else and else-if ?: switch 3.2.1. The if statement tests the numeric value of an expression if not followed by a bracketed code block, only the first statement immediately after the if statement is executed in relation to the if statement once it evaluates to true The syntax:
Page 2 of 11
CSI 2101
September, 2013
NB: in the example above, the indented printf statement corresponds to the if statement. The second printf will execute regardless of the condition of the if statement. 3.2.2. The if-else statement The syntax:
if (expression) statement1 else statement2
Examples:
if(siblings >= 1) { printf(How many brothers do you have?\n); scanf(%d,&bro); printf(\nHow many sisters do you have?\n); scanf(%d,&sis); } else printf(Seems like youre an only child.); printf(This is not related to the previous if-else statement).
if(progNum == 0715) printf(You are a UG Computer Science student doing your diploma.); else if(progNum == 0719) printf(You are a UG Computer Science student doing your degree.); else printf(Youre not in the UG Computer Science department.\n). printf(This is not related to any of the previous if statements).
Page 3 of 11
CSI 2101
September, 2013
N.B.: use indentations to show the relationship of sequential-flow statements to their corresponding if-else statements. Use brackets to surround multiple statements that are associated with the if-else statements. 3.2.3. The ternary operator ? :
This is an alternate way to write an if-else statement.
The conditional expression exp1 is evaluated first. If it is non-zero (true), then exp2 is evaluated, otherwise, exp3 is evaluated. E.g. If-else statement
if( a > b) max = a; else max = b;
Page 4 of 11
CSI 2101
September, 2013
The syntax:
switch ( expression ) { case value1: Code to execute if expression == value1 break; case value2: Code to execute if expression == value2 break; default: Code to execute if expression does not match any of the values following any of the cases break; } Example:
/* A simplified calculator */
int operand1, operand2; int result = 0; char operation; printf(Enter first operand: ); scanf(%d,&operand1); printf(Enter operation to perform ( +, -, *, /,): ); scanf(\n%c,&operation); printf(Enter second operand: ); scanf(%d,&operand2); /* Perform the calculation */ switch(operation) { case +: result = operand1 + operand2; break; case -: result = operand1 - operand2; break; case *: result = operand1 * operand2; break; case /: if( operand2 !=0) // error checking result = operand1 / operand2; else printf(Divide by 0 error!\n); break; default: printf(Invalid operation entered); break;
Page 5 of 11
CSI 2101
September, 2013
If the case matches the expression, execution starts at that case. All case expressions must be different. Each case must end with a break statement. Break is a keyword that breaks execution out of the current code block. It causes an immediate exit from the switch construct and redirects the program flow to the statement after the closing brace of the switch. The case labeled default is optional. It executes if the switch expression matches none of the case constants. If it isnt there and the expression matches none of the case constants then none of the cases within the switch are executed.
3.3.1. The while statement Tests a termination condition at the beginning of the loop. The while loop repeats the execution of the statements in its code block while the condition is true.
The syntax:
while (expression) { statements }
Example: int x = 1; int a = 0; printf(The first three even whole numbers are: ); while( x <= 3) { printf(%d , a); a+=2; x=x+1; } printf(\nmoving on\n);
Page 6 of 11
CSI 2101
September, 2013
Note: Execution proceeds as follows: 1. The expression is evaluated. 2. If expression is true (nonzero), the body of the while statement is executed and the process is repeated beginning at step 1. If expression is false, the body of the while statement is never executed, and control passes to the next statement after the closing brace of the while statement. 3.3.2. The do-while statement Tests a termination condition at the end of the loop. The do-while loop always performs at least one iteration of the its code block and repeats the execution its code block while the condition expression is true. It is equivalent to the Pascal repeat-until statement. NB: the do-while expression terminates with a semicolon.
The syntax: do { statements } while (expression); Example: int x, a; a = 0; printf("How many results do you want to see?"); scanf("%d",&x); printf("The first %d even whole numbers are:",x); do { printf("%d ", a); a+=2; x=x-1; } while( x > 0); printf("\nmoving on...\n"); Note: Execution proceeds as follows: 1. The statement body is executed.
Page 7 of 11
CSI 2101
September, 2013
2. Next, expression is evaluated. If expression is false, the do-while statement terminates and control passes to the next statement in the program. If expression is true (nonzero), the code block is repeated. 3.3.1. The for statement The for statement allows you to repeat a code block a specified number of times. It tests a termination condition at the beginning of the loop.
The syntax: for ( init-expression opt ; cond-expression opt ; loop-expression opt ) { statements } Example: int x = 1; int a = 0; printf("The first three even whole numbers are: "); for(x=1; x <= 3; x=x+1) { printf("%d ", a); a+=2; } printf("moving on ..."); Note: Execution proceeds as follows: 1. The init-expression, if any, is evaluated. This specifies the initialization for the loop. There is no restriction on the type of init-expression. 2. The cond-expression, if any, is evaluated. It is evaluated before each iteration. Three results are possible: o If cond-expression is true (nonzero), the statement block is executed; then loopexpression, if any, is evaluated. The loop-expression is evaluated after each iteration. There is no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation of cond-expression. o If cond-expression is omitted, cond-expression is considered true, and execution proceeds exactly as described in the previous paragraph. A for statement without a cond-expression argument terminates only when a break or return
Page 8 of 11
CSI 2101
September, 2013
statement within the statement body is executed, or when a goto (to a labeled statement outside the for statement body) is executed. If cond-expression is false (0), execution of the for statement terminates and control passes to the next statement in the program.
4. Nested Constructs When we compose a construct that contains another construct it is referred to as nesting. Example: if(n>0) for( i=0; i<n; i++) { if(0==i%2) { printf(i is %d and even\n,i); }else printf(i is %d and odd\n,i); } else printf(error! Negative number entered\n);
5. Using Logical Operators Used to form complex conditions by combining simple conditions In C, a nonzero value (i.e. a value other than zero) is logically true. A zero value is logically false.
Example !x x && y x || y
Page 9 of 11
CSI 2101
September, 2013
6. Using Relational Operators Used to test the relationship between two values. If the condition evaluates to true then 1 is the value after execution otherwise the condition evaluates to 0 when false. The Relational operators in C: Operator Operation > greater than >= Greater than or equal < Less than <= Less than or equal == Equal != Not equal
Example
x x x x x x > y >= y < y <= y == y != y
Example:
if (tankLevel == 0) Printf(Warning: Tank Empty!!\n);
Another example:
int h = 0; int f = 7; int g = 8; h = f <= g; /* h will be assigned 1*/
NB: in the example above the expression f<=g is evaluated first since it is on the right-hand side of the assignment operator (=). Because this expression evaluates to true, the value 1 is assigned to h
Page 10 of 11
CSI 2101
September, 2013
Exercises: 1. Write a program that reads the prices of 10 items and their item number. The program should print the name of the item with the highest price. Assume that the items dont have the same price. 2. Write a program to read eleven numbers find their average and print it. The program should also print the number of times the number 6 occurs. 3. Write a program to validate a date in the twenty-first century. It should check that the number of months in a year cannot exceed 12, and that the number of days in each month has not been exceeded. The program should also report on Leap years. Hint: Implement this program using a switch statememt.
Page 11 of 11