ICE 0125 Programming Fundamentals II CC Lab 2
ICE 0125 Programming Fundamentals II – C/C++ Lab 2: C Program Control n n Review Lab assignments
Syntax for Switch n switch Useful when a variable or expression is tested for all the values it can assume and different actions are taken Format n Series of case labels and an optional default case n switch ( value ){ n case '1': n actions n case '2': n actions n default: n actions n } n break; exits from statement n n
Types of Loops n n Pretest - a logical condition is checked before each repetition to determine if the loop should terminate n while loop n for loop Posttest - a logical condition is checked after each repetition for termination n do-while loop
Pre. Test vs. Post. Test Loops
Pretest Loop: While Syntax: while (condition) statement;
Example of While int counter = 0; while (counter < 5) { printf(“*n”); counter++; }
Posttest Loop: Do-While n Syntax: do { statement(s) } while (condition);
Using the Do-While n n do { printf(“n Enter id# and salary: “); scanf(“%d %f”, &id, &salary); printf(“n You entered id#%1 d”, id); printf(“ and salary $%. 2 f, ”, salary); printf(“ Is this correct? (Y/N) ” ); scanf(“ %c”, &ans); } while ((ans != ‘Y’) && (ans != ‘y’)); Loop always executes at least once
Pretest Loop: For n Syntax: for ( init ; condition ; update ) statement; n n Init: assignments to counter variables Update: changes to counter variables
For Example n Printing vertical line of stars: for (counter = 0; counter < 5; counter++) { printf(“*n”); }
break statement n n The break statement can be used to halt a loop. do { scanf(“%d”, &num); if (num < 0) break; /* Loop ends */ } while (num != 0);
continue statement n n A continue statement says jump past any remaining statements Example: for (I = 0; I < 100; I++) { if ((I % 2) == 1) continue; printf(“%d is even”, I); // continue goes to here: end of // statements }
Logical operators © Copyright 1992– 2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Lab assignments n Chapter 4 n n Solve problem: 4. 11 Solve problem: 4. 27
- Slides: 14