550 likes | 557 Views
Learn about conditional execution, loops, nested code, jumps, and the true and false representation in C programming. Get insights on if statements, nested ifs, conditional expressions, and switch statements. Enhance your C programming knowledge now!
E N D
Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps
True and False in C • False is represented by any zero value. • The int expression having the value 0. • The floating expression having the value 0.0. • The null character ‘\0’. • The NULL pointer (for pointer see chap. 8). • True is represented by any nonzero value. A logical expression, such as a<b, is either true or false. • This expression yields the int value 1 if it istrue or the int value 0 if it is false.
Examples int i=1, j=2, k=3; double x=5.5, y=7.7, z=0.0; i<j-k i<(j-k) 0 -i+5*j>=k+1 ((-i)+(5*j))>=(k+1) 1 x-y<=j-k-1 (x-y)<=((j-k)-1) 1 x+k+7<y/k ((x+k)+7)<(y/k) 0 i!=j 1 !!5 !(!5) 1 !i-j+4 ((!i)-j)+4 2 x||i&&j-2 x||(i&&(j-2)) 1
Selection • if • switch
if statement • Conditional Execution: if (Boolean expression) statement; else statement; Where a statement may consist of a single statement, a code block, or empty statement. The else clause is optional.
Yes- For a Semi-colon if – logic: if (Boolean Expression) statement_1; If-else-logic: if (Boolean Expression){ compound_1 } else{ compound_2 } • Conditional execution allows you write code that reacts to tested conditions. No Semi-colon
Example #include <stdio.h>WHY? int main ( ) { double salary, payrate; int hours, union; printf (“Please enter hours worked, payrate”, “ and union status”);
printf (“Enter 1 if a union member, 0 if not”); scanf (“%d%lf%d”, &hours, &payrate, &union); if(hours > 40 && union = = 1) salary = (40 * payrate) + ((1.5 * payrate) * (hours - 40)); else salary = payrate * hours; printf (“Salary is: $ % 6.2 f”, salary); }
Nested ifs Nested: One statement coded within another statement. Nested ifs: An nested if is an if that is the target of another if or else. Why Nested ifs? Needed to handle tasks where we have 3 or Moreoptions that are mutually exclusive. ANSI C specifies that at least 15 levels of nesting must be supported by the compiler.
The if-else-if ladderLinear nested If • General form: OLD STYLE if (expression) statement;else if (expression) statement;else if (expression) statement; . . . else statement;
The conditions are evaluated from the topdownward. • As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed. • If none of the conditions are true, the final else is executed. That is, if all other conditional tests fail, the last else statement is performed. • If the final else is not present, no action takes place if all other conditions are false.
Example E.g. You are a salesperson for the Widget Manufacturing Co. You will earn a salary bonus according to the following rules: Sales > = $50,000 earn $5,000 Sales > = $100,000 earn $15,000 Sales > = $150,000 earn $30,000
double sales, bonus; printf (“please enter total sales”); scanf (“%lf”, &sales); if (sales < 50000) bonus = 0; else if (sales < 100000) bonus = 5000; else if (sales < 150000) bonus = 15000; else bonus = 30000;
In a nested if, an else always refers to the nearest if that is within the same block as the else and that is not already associated with an else. if(i) {if(j) dosomething1();if(k) dosomething2(); /* this if */else dosomething3(); /* goes with this else */ }else dosomething4(); /* associated with if(i) */
Conditional Expression • The expressions must simply evaluate to either a true or false (zero or nonzero) value. • The expressions are not restricted to involving the relational and logical operators.
The ?: Alternative Exp1 ? Exp2: Exp3 x = 10; if(x>9) y = 100;else y = 200; x = 10; y = x>9 ? 100 : 200;
#include <stdio.h> int f1(int n);int f2(void); int main(void){ int t; printf("Enter a number: "); scanf("%d", &t); t ? f1(t) + f2() : printf("zero entered."); printf("\n"); return 0;}
/* Divide the first number by the second. */ #include <stdio.h> int main(void){ int a, b; printf("Enter two numbers: "); scanf(''%d%d", &a, &b); if(b)printf("%d\n", a/b); VALID? else printf("Cannot divide by zero.\n"); return 0;}
switch statement • switch is a multiple-branch selection statement, which successively tests the value of an expression against a list of integer or character constants (floating point expression, for example, are not allowed). • When a match is found, the statements associated with that constant are executed.
General Form switch (expression) {case constant1: statement sequencebreak;case constant2: statement sequencebreak; . . default:statement sequence } //ANSI C - at least 257 case constants.
Execution • The value of the expression is testedagainst theconstants specified in the case statements in a top-down order.. • When a match is found, the statement sequenceassociated with that case is executed until the break statement or the end of the switch statement is reached. • When break is encountered in a switch, program execution "jumps" to the line of code following the switch statement. • The default statement is executed if no matches are found. • The default is optional.
The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression. • No two case constants in the same switch canhave identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are in common. • If character constants are used in the switch statement, they are automatically converted to integers (as is specified by C's type conversion rules).
The switchstatement is often used to process keyboard commands, such as menu selection. The followingfunction will when called: display the options, allow the user to make a selection, and then evoke the appropriate function to perform the task selected. void menu(void){ char ch; printf("1. Check Spelling\n"); printf(''2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf("Strike Any Other Key to Skip\n"); printf(" Enter your choice: "); ch = getchar(); /* read the selection from the keyboard */
switch(ch){case '1': check_spelling ();break; case '2': correct_errors ();break; case '3': display_errors ();break; default : printf("No option selected");}}
int flag, k; /* Assume k is initialized */ flag = -1; switch(k) { case 1: /* These cases have common */ case 2: /* statement sequences. */ case 3: flag = 0;break; case 4: flag = 1; case 5: error(flag);break; default: process(k); } • The break inside the switch is optional. • If the break isomitted, execution will continue on into the next case until either a break or the end of the switch is reached.
Nested Switch • You can have a switch as a part of the statement sequence of an outer switch. • Even if the case constants of the inner and the outer switch contain common values, no conflict arise.
switch(x) { case 1: switch(y) { case 0: printf(''Divide by zero error.\n"); break; case 1: process(x, y); break; } break; case 2: ….
Iteration • Iteration statements (also called loops) allow a set of instructions to be repeatedly executed until a certain condition is reached. • This condition may be predetermined (as in the for and whileloop) or open ended (as do-whileloops).
for loop for (initialization; testing; increment) Loop Body; • The initialization is an assignment statement that is used to set the loop control variable. • The testing is a relational expression that determines when the loop exits. • The incrementdefines how the loop control variable changes each time the loop is repeated.
Execution • The for loop continues to execute as long as the condition is true. • Once the condition becomes false, program execution resumes on the statement following the body of the for loop.
#include <stdio.h> int main(void){ int x;for(x=1; x <= 100; x++) printf("%d ", x); return 0;} for(x=100; x != 65; x -= 5) { z = x*x; printf(''The square of %d, %d", x, z);}
The Elements of the For-loop • The initialization, testing and incrementation can be any valid C expression. for (x=0; Ajax>Manchester; Ajax=Q*7/i) • Common use as a counting loop. for (count=0; count <n; count=count+1)
Pieces of the loop definition need not be there. • The incrementation of the loop control variable can occur outside the for statement. for(x=0; x != 123; ) scanf("%d", &x); for( x=1 ; x < 10; ) { printf("%d", x);++x;}
The Infinite Loop • Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. for( ; ; ) printf("This loop will run forever.\n"); for( ; ; ) { ch = getchar(); /* get a character */ if(ch == 'A') break; /* exit the loop */} printf("you typed an A"); • Terminate the infinite loop
For Loops With No Bodies • A loop body may be empty. • This fact is used to simplify the coding of certain algorithms and to create time delay loops. • Does what? for(t=0; t < SOME_VALUE; t++ ) ;
Declaring Variables within a For Loop • A variable so declared has its scopelimited to the block of code controlled by that statement. /* i is local to for loop; j is known outside loop.*/int j; for( int i = 0; i<10; i++) j = i * i; i = 10; /*** Error ***-- i not known here! */ Not Working!!!
While Loop • General form: while(condition) statement; • Execution: • Check the test condition at the top of the loop. • The loop iterates while the condition is true. • When the condition becomes false, program control passes to the line of code immediately following the loop.
Example char wait_for_char(void){ char ch; ch = '\0'; /* initialize ch */while(ch != 'A') ch = getchar(); return ch;} while((ch=getchar()) != 'A') ;
For loop Vs While LoopA-(Assignment), T-(testing), I-(Increment) A; While (T) { Body; I; } for (A; T; I) { Body; }
NESTED LOOPS Nested 1 loop syntax coded inside another Loop syntax. Why?- Single -Loop? Have a statement or statements that you want to repeat. A repetitive task that you must solve. Why? - Nested-Loops? You have a single - repetitive task - THATYOU MUST REPEAT i.e., a repetition of an already repetitive task.
General Format: while (boolean expression){ while (boolean expression) { } } You may have any combination of the 3 loop syntax inside each other. The problem dictates what combination should be used.
/* Find triples of integers that add up to n. */ #include <stdio.h> #define N 7 main() { int cnt = 0, j , k , m; for(j = 0; j <= N; ++j) for( k = 0; k <= N; ++k) for( m = 0: m <= N; ++m) if ( j + k + m == N) { ++cnt; printf(“%d%d%d”, j , k , m); } printf(“\n Count: %d\n”, cnt); }
How many times will “if” be executed? 512 times j range 0 7 k range 0 7 m range 0 7 8 * 8 * 8 = 512
What will the values of j, k, and m be in sequence JK M 0 0 0 0 0 1 0 0 2 0 0 7 0 1 0 0 1 1 0 1 2 0 1 7
Cont... 0 2 0 0 2 1 0 2 7 . . .
do-while Loop • General form: do {statement; } while(condition); • Execution: • Always executes at least once. • Iterates until condition becomes false. do { scanf(''%d", &num);} while(num > 100);
The most common use of the do-while loop is in a menu selection function. void menu(void){ char ch; printf("1. Check Spelling\n"); printf("2. Correct Spelling Errors\n"); printf("3. Display Spelling Errors\n"); printf(" Enter your choice: ");
do { ch = getchar(); /* read the selection from the keyboard */ switch(ch) { case '1': check_spelling(); break; case '2': correct_errors(); break; case '3': display_errors(); break;} } while(ch=='1' || ch=='2' || ch=='3');}
Jump • break • continue • return (will be introduced in Ch. 4, Functions).
break Statement #include <stdio.h> int main (void){ int t; for(t=0; t < 100; t++) { printf(''%d ", t); if(t == 10) break; } return 0;} 0 1 2 3 4 5 6 7 8 9 10 Two uses: You can use it to terminate a case in the switch statement. You can also use it to force immediate termination of a loop, bypassing the normal loop conditional test.