Download presentation
Presentation is loading. Please wait.
Published byBarnard Gilmore Modified over 9 years ago
1
Introduction to Computer Algorithmics and Programming Ceng 113 Program Control Statements
2
Selection –if and switch Iteration –while, for, do-while Jump –break, continue, return Label Expression Block –A block begins with a { and ends with a }.
3
Selection Statements The general form of the if statement is; if (expression) statement; else statement; A statement may consist of a single statement or a block of statements or nothing. The else clause is optional. /* Magic number program #1 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) printf(“** Right **”); }
4
Selection Statements /* Magic number program #2 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) printf(“** Right **”); else printf(“Wrong”); }
5
Nested ifs A nested if is an if that is the target of another if or else. if (i) { if (j) statement 1; if (k) statement 2; /* this if */ else statement 3; /* is associated with this else */ } else statement 4; /* associated with if(i) */
6
Selection Statements /* Magic number program #3 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else {printf(“Wrong, ”); if (guess > magic) printf(“too high \n”); else printf(“too low \n”); }
7
The if-else-if Ladder General form is; if (expression) statement; else if (expression) statement;.... else statement;
8
Selection Statements /* Magic number program #4 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else if (guess > magic) printf(“Wrong, too high \n”); else printf(“Wrong, too low \n”); }
9
The ? Alternative We can use the ? Operator to replace if-else statements of the general form: if (condition) expression; else expression; However, the ? is called ternary operator because it requires three operands. Exp1 ? Exp2: Exp3; x = 10; y = x>9 ? 100: 200; x = 10; if (x>9) y = 100; else y = 200;
10
Sample program /* Magic number program #5 */ #include “stdio.h” #include “stdlib.h” void main(void) { int magic; /*magic number */ int guess; /*user’s guess */ magic = rand(); /* generate the magic number */ printf(“guess the magic number: “); scanf(“%d”, &guess); if (guess == magic) { printf(“** Right **”); printf(“%d is the magic number \n”, magic); } else guess > magic ? printf(“High”) : printf(“Low”); }
11
Sample program /*This program uses the ? operator to square an integer value entered by the user but preserves the sign (10 squared is 100 and -10 squared is -100).*/ #include “stdio.h” void main(void) { int isqrd, i; printf(“enter a number :”); scanf(“%d”, &i); isqrd = i>0 ? i*i : -(i*i); printf(“%d squared is %d”, i, isqrd); }
12
Sample program #include “stdio.h” int f1(int n); int f2(void); void main(void) { int t; printf(“enter a number: “); scanf(“%d”, &t); /* print proper message */ t ? f1(t) + f2( ) : printf(“zero entered”); } f1(int n) { printf(“%d ”, n); return 0; } f2(void) { printf(“entered”); return 0; } if (t!=0) { f1(t); f2; } else printf(“zero entered”);
13
switch C has a built-in multiple branch selection statement, switch, which tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. switch (expression) { case constant1: statement sequence break; case constant2: statement sequence break;... default: statement sequence } The default statement is executed if no matches are found. The default is optional. A switch statement can be included maximum 257 case statements. When break statement is encountered in a switch, program execution “jumps” to the line of code following the switch statement.
14
switch menu() { 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 choise: ”); 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”); }
15
switch /*Process a value */ void inp_handler(int i) {int flag; flag = -1; switch(i) { case 1: case 2: case 3: flag= 0; break; case 4: flag= 1; case 5: error(flag); break; default : process(i); }
16
Nested switch statement switch(x) { case 1: switch(y) { case 0: printf(“divide by zero error”); break; default: process(x, y); } break; case 2:...
17
Example The programmer has given each medical plan a code: Plan1 = F, Plan2 = B, Plan3 = K and Plan4=E. The company pays for all of Plan1. The individual has to pay for part of the others. Plan2 = amount/4, Plan3 = amount/7, Plan4 = amount/5. Any other codes are considered in error. Write the algorithm and C code to calculate the total amount which the company will be paid to plans.
18
#include "stdio.h" main() {int total_investment=0, int amount_of_plan=0; char plan_code; printf("\n Enter the selected plan code (F, B, K, E) ="); scanf("%c", &plan_code); printf("\n Enter the amount of total investment for selected plan ="); scanf("%d", &total_investment); switch(plan_code) { case 'F': {amount_of_plan=total_investment; printf("\n The amount of this plan = %d", amount_of_plan); break;} case 'B': {amount_of_plan=total_investment / 4; printf("\n The amount of this plan = %d", amount_of_plan); break;} case 'K': {amount_of_plan=total_investment / 7; printf("\n The amount of this plan = %d", amount_of_plan); break;} case('E'): {amount_of_plan=total_investment / 5; printf("\n The amount of this plan = %d", amount_of_plan); break;} default: printf("\n You selected invalid plan code."); }
19
#include main() /* count digits, white space, others */ { char c; int i, nwhite, nother, ndigit[10]; nwhite = nother = 0; for (i = 0; i < 10; i++) ndigit[i] = 0; while ((c = getchar()) != ‘.’) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c-'0']++; break; case ' ': case '\n': case '\t': nwhite++; break; default: nother++; break; } printf("digits ="); for (i = 0; i < 10; i++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother); }
20
Iteration statements Iteration ( also called loops) statements allow a set of instructions to be performed until a certain condition is reached. This condition may be predifened as in the for loop, or open ended as in the while and do-while loops.
21
The for loop The general form of the for statement is; for (initialization; condition; increment) statement; The initialization is an assignment statement that is used to set the loop control variable. The condition is relational expression that determines when the loop exist. The increment defines how the loop control variable changes each time the loop is repeated. #include stdio.h main() { int x; for(x=1; x<=100;x++) printf(“%d “, x); }
22
The for loop Sample 1; for(x=100; x!=65; x-=5) { z = x*x; printf(“The square of %d, %d”, x, z); } Sample 2; x = 10; for(y=10; y!=x; y++) printf(“%d”, y); printf(“%d”, y); Sample 3; for(x=0; x!=123; ) scanf(“%d”, &x);
23
The for loop The infinity loop; You can make an endless loop by leaving the conditional expression empty; for( ; ; ) printf(“ this loop will run forever. \n”); Sample; ch = ‘\0’; for( ; ; ) { ch=getchar(); /* get a character */ if (ch==‘A’) break; /* exit the loop */ } printf(“you typed an A”);
24
Exercise Create a function which is convert the 0,5,10,15,20, 25, 30...,90, 95, 100 celsius to fahrenheight values in a table. F = ((C/5)*9+32)
25
Exercise /* This program convert to celsius to fahrenheight.*/ #include int main() { // Define variables int celsius, fahrenheight; // Print the table headers printf("\n Program will be list celcius and fahrenheight convertion table."); printf("\n CelciusFahrenheight"); // Convert the celsius to fahrenheight between 5 and 100. for (celsius = 0; celsius <=100; celsius +=5) { fahrenheight=((celsius/5) * 9 +32); printf("\n %d %d", celsius, fahrenheight); } printf("\n"); return 0; }
26
The while loop Its general form is; while(condition) statement; The loop iterates while the condition is true. When the condition becomes false, program control passes to the line after the loop code. wait_for_char(void) {char ch; ch = ‘\0’; /*initialize ch */ while(ch != ‘A’) ch = getchar(); return ch; }
27
The while loop /*add spaces to the end of string */ #include “stdio.h” #include “string.h” void main(void) {char str[40]; int k; strcpy(str, “this is a test”); k = strlen(str); printf(“%d”, k); while (k <40) {str[k] = ‘ ‘; k++; } str[k] = ‘\0’; /*strings need to be terminated in a null */ printf(“%d”, strlen(str)); } *
28
The do-while loop The do-while loop checks its condition at the bottom of the loop. A do- while loop always executes at least once. do { statement } while(condition); Sample; do { scanf(“%d”, &num); } while(num>100);
29
menu() { 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 choise: ”); 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; default : printf(“No option selected”); } } while(ch=‘1’ || ch =‘2’ || ch = ‘3’); }
30
Exercise Mr.Brown has given a test to his class. He would like to have the avarage score for the class, and the higest and lowest scores. Develop a solution to calculate and print out these values. ( Use a significant value to stop the processing of the loop).
31
# include void main () { int counter=0, avarage=0, lowest=100, higest=0, total_grades=0, grade; printf("\n Please enter -1 to terminate the program.\n"); printf("\n Enter a student grade ="); scanf("%d", &grade); while (grade != -1) { total_grades = total_grades + grade; counter++; if (lowest > grade ) lowest = grade; if (higest < grade ) higest = grade; printf("\n Enter a student grade ="); scanf("%d", &grade); } printf("\n The higest grade is %d", higest); printf("\n The lowest grade is %d", lowest); printf("\n The avarege grade is %d", (total_grades/counter)); } While loop!
32
# include void main () { int counter=0, avarage=0, lowest=100, higest=0, total_grades=0, grade; printf("\n Please enter -1 to terminate the program.\n"); do { printf("\n Enter a student grade ="); scanf("%d", &grade); if (grade != -1) { total_grades = total_grades + grade; counter++; if (lowest > grade ) lowest = grade; if (higest < grade ) higest = grade; } }while (grade != -1); printf("\n The higest grade is %d", higest); printf("\n The lowest grade is %d", lowest); printf("\n The avarege grade is %d", (total_grades/counter)); } Do-While loop!
33
Unconditional Branch The return statement; The return statement is used to return from a function. It is a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made. return expression; The expression is optional.
34
Unconditional Branch The break statement; This statement has two uses; 1. to terminate a case in the switch statement, 2. to force immediate terminator of a loop, bypassing the normal loop conditional test. #include “stdio.h” void main(void) { int t; for(t=0; t<100; t++) { printf(“%d”, t); if(t==10) break; } for(t=0; t<100; ++t) { count=1; for( ; ; ) { printf(“%d”, count); count++; if(count==10) break; }
35
Unconditional Branch The exit() function; You can break out of a program by using the standart library function exit().This function causes immediate termination of the entire program, forcing a return to the operating system. void exit(int return_code); The value of return_code is returned to the calling process, which is usually the operating system. Zero is generally used as a returned code to indicate normal program termination.
36
Unconditional Branch The continue statement; Continue forces the next iteration of the loop. * /*count spaces */ #include “stdio.h” main() { char s[80], *str; int space; printf(“enter a string: “); gets(s); str =s; for(space=0; *str; str++) { if(*str!=‘ ‘) continue; space++; } printf(“%d spaces \n”, space); }
37
Next Course Arrays and Strings –...
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.