C语言第三章ControlFlowIfElse.ppt_第1页
C语言第三章ControlFlowIfElse.ppt_第2页
C语言第三章ControlFlowIfElse.ppt_第3页
C语言第三章ControlFlowIfElse.ppt_第4页
C语言第三章ControlFlowIfElse.ppt_第5页
已阅读5页,还剩68页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Control Flow- If-Else,Judy Wang Computer Department Spring 2008,Before the class correct the error before,Return type of main function New Standard Before main() Now-Whats void? Whats return? void main() /*main function is the beginning of a program*/ return; /*the end of a program*/ ,Problems in Co

2、ursework 1 - Software,Software VC+ 6.0 Whats workspace for? Whats project for? One workspace could have several project, but one project has only one main function, since the main function is the beginning of a program. How to activate one project when the workspace has many projects. How to delete

3、a project or a file? Good programming habit give a proper name to the variables, files, projects, and workspace. Whats the benefits? How to find out the error check the debug window first before ask teacher. Where is the debug window How to read the error It could be difficult at the beginning,Probl

4、ems in Coursework 1 Writing Style,Writing Style easy to find the error Write the coupled symbol, e.g. (), at one time in case the other part may be forgotten. Its important in the case like 2nd question in coursework1. One line, one statement Use a blank line between different blocks A proper variab

5、le name Never forget “ ; ” Include the right header file Why we need to include the header file Where to find the definition of the library,Right attitude do a program,Have a clear idea before writing the code. Dont think about what functions could be used before you get the algorithm whats algorith

6、m? not the code , but idea in the mind Write down the structure of the program in your notebook We are going to talk about it for detail in the analysis of question 3,Tips for programming - 1,Process of programming,Analyze the problem,Got the plan - Algorithm,Write down the structure - key,Write the

7、 program,Run the program,Analyze the result,If the answer is wrong, modify the program,If the answer is right. The program is down.,Tips for programming - 2,Separate a big problem into several smaller parts The structure is clear Its easy for programmers to meet every point Easy for checking Easy to

8、 change the code and fix the errors. Algorithm of choosing_student program,Statements and Blocks,An expression such as x=0 or printf(“”) become a statement when it is followed by a semicolon ,as in x = 0; i+; printf(“ ”); In C , the semicolon is a statement terminator. Braces and are used to group d

9、eclarations and statements together into a compound statement, or block, so that are syntactically equivalent to a single statement.,Branching Mechanisms,So far all our programs runs from start to end We need to a way to choose which code to run C provides branching (think tree) mechanisms for the p

10、urpose: if-else statement switch statement,If-else Statement,Choose one of two statements based on the conditional expression Examples: if ( Hours 40 ) grossPay = rate*40 + 1.5*rate*(Hours - 40); else grossPay = rate*Hours;,If-else Statement - Formal Syntax,if () else ,Example- whats the output?,voi

11、d main() int num1 = 2, num2 = -1, num3 = 2; if ( num1 num2 ) num3=0; else num3+=1; printf(“num3=%dn, num3); getch(); return; So far theres only one statement We need to do more than one,Is it true? True: num3 = 0; False: goto else num3 += 1;,Output: z=3,Compound/Block Statement,Only get one statemen

12、t per branch Must use block statement for multiples Also called compound statement Example: if ( Hours 40 ) grossPay = rate*40 + 1.5*rate*(Hours - 40); Printf( “Youve worked more than 40hrs.Here is your pay %fn”, grossPay); else grossPay = rate*Hours; Printf( “Youve worked less than 40hrs.Here is yo

13、ur pay %fn”, grossPay); ,Compound Statement in Action,if (myScore yourScore) printf( “I win!n”); printf( “I win!n”); else printf (“I wish these were golf scores.n”); wager = 0; ,Common Pitfall: = vs =,= means “assignment” “=“ means “equality” These two are very different in C+ Example: if (x = 12) a

14、+; else a-;,Never gets executed,The Optional else,else clause is optional If, in the false branch (else), you want nothing to happen, leave it out Example: if (sales = minimum) salary = salary + bonus printf(“Salary = %d”, salary );,Nested Statements,if-else statements contain smaller statements Com

15、pound or simple statements (weve seen) Can also contain any statement at all, including another if-else statement! Example: if (speed 55) if (speed 80) printf(“Youre really speeding!n”); else printf(“Youre speeding n”);,Multi-Way if-else Statement,Not new, just different indenting Avoids excessive i

16、ndenting Syntax:,Multi-Way if-else - Example,Example: if(temperature=-10*/ printf(Dress warm); else printf(Work hard and play hard); The Boolean expressions are checked in order until the first true Boolean expression is encountered, and then the corresponding statements are executed. If none of the

17、 Boolean expressions is true, then the Statement_For_All_Other_Possibilities is executed.,The switch statemnt - Syntax,The switch statement - Example,void main() int vehicleClass; double toll; printf(Enter vehicle class: ); scanf(%d, ,If you forget this break, then passenger car will pay $1.5,Whats

18、output of the program?,void main() char score; scanf(%c, ,What happened if I typed in A? Whats the output supposed to be?,Actual answer! Whats wrong!,Modified program,void main() char score; scanf(%c, ,Try again!,Switch - Multiple Case Labels,Execution falls thru until break switch provides a point

19、of entry Example: case A: case a: printf( “Excellent: you got an A!n”); break; case B: case b: printf ( “Good: you got a B!n”); break;,Switch - Pitfalls,Forgetting the break; No compiler error Execution simply falls thru other cases until break; Break only breaks same level block,Return and Break,Di

20、fference between return and break Return is the end of the program Break breaks one block and only one block,Goto and Labels:,So far the programs we learn always run by sequentially, what if the program need to jump some parts in certain specified condition? We need Goto and Label example: What s th

21、e output? void main() int num1=1, num2=2, num3=3; printf(num1 = %d n, num1); printf(num2 = %d n, num2); goto end; printf(num3 = %d n, num3); end: getch(); return; ,Label,Jump to the label end,This statement has been skipped,The output is : num1 = 1 num2 = 2,Goto Labels Syntax,Forward jump goto label

22、; . . . label: statement;,Backward jump - loop label: statement; . . . goto label;,Dont miss the :,Goto for loop Backward jump,What is the program for? void main() int i=1,sum=1; /*sum for sumary*/ add: i+=1; /* i = i + 1 */ if (i=10) /*if i=10 do the loop*/ sum+=i ; /* sum = sum + i */ goto add; pr

23、intf(The answer is sum = %dn, sum); getch(); return; ,This program is to get the answer of 1+2+3+10,Conditional Operator (? and :),Also called ternary operator Allows conditional in expression shorthand if-else operator Example: if (n1 n2) max = n1; else max = n2; Can be written: max = (n1 n2) ? n1

24、: n2;,Group activity Case study,5.10 p144 text book,Course work 2,Q1:5.1 p142 text book Q2: Its the salary list of X department. Write a program get the title and the salary when type in the level. The output is like Q3: Use GOTO make the Q2 to be a loop. That means we could use the system to requir

25、e the staff more than one time.,Control Flow- Loop,Judy Wang Computer Department Spring 2008,Overview of Loops,Loops are circles where code is executed over and over. Each time through the loop is called an iteration Three general types of loops in C while No restriction do-while Always does the bod

26、y of the loop at least once for Natural “counting” loop,From if-goto TO While,The program done by if-goto void main() int n=0,sum=0; loop: if (n100) goto end; sum+=n; +n; goto loop; end: printf(“sum = %dn”,n); getch(); return; ,The program done by While void main() int n=0,sum=0; while (n=100) sum+=

27、n; +n; printf(“sum = %dn”,n); getch(); return; ,Write a program to get the answer of 1+2+3+n,Syntax of While while( boolean_expression) statement; ,Body of the loop,Argument about GoTo,Approval benefits Abandon processing in some deeply nested structure, such as breaking out of two or more loops at

28、once. the break only exits from the innermost loop. error handling. Disapproval It impact the readability Its difficult the handle structure when the fresh programmer us the GOTO Impact compiling speed performance Requirement of the class dont use the Goto in this C class since its hard for the fres

29、hman to handle it in complicated programming.,while-Loop Example,int count = 0; / Initialization while ( count 3 ) / Test condition printf(“Hi”); / Loop Body count+; / Update expression How many times does the loop body execute? Whats the output? What if count is initialized to 3? What if we change

30、“Hi ” to “Hin”? What is we delete the count+ ?,while-Loop Question,Write a program to list all integers could be divided by 4 exactly between 0 and 100. learn to read the questions in English.,Dead loop,If the boolean_expression of while(boolean_expression) is always true, the loop could not be ende

31、d, and we call this situation to be Dead Loop or Dead Circle. Example: whats output of the program int num=1; while(i=4) i+; printf(“loop!n”); printf(“It could not be ended!n”); Why it is harmful? The variable used to control the loop could have a simple name, like i in the former case.,Its always T

32、RUE,What if change it to be while (i0),Save the file ! before execution,Break and Continue,Break a break causes the innermost enclosing loop or switch to be exited immediately. Continue is related to break but less often used. It cause the next iteration of the loop to begin. Tips: A continue inside

33、 a switch inside a loop causes the next loop iteration. while(expression_1) if(expression_2) continue; statement; ,If the expression_2 is true, goto while and check again,If the expression_2 is false, do the following statements,Question whats the output,void main() int i=0; while (i5) if(i3) i+=2;

34、printf(%dn,i); continue; else printf(%dn, +i); break; printf(bottom of the loopn); return; ,Hint: Whats the value of i in each iteration?,Do-While statement,On some occasions it might be necessary to execute the body of loop before the test is performed. Such situation can be handled with the help o

35、f the Do-While statement Example int num; do printf(“nInput a number:”) number=scanf(“%d”, ,Do-While - Syntax,do statements; while (boolean_expression) ;,Never forget this Semicolon ;,Do- While Example,Example what s the output of the code void main() int num,digit; printf(“Please enter an integer:

36、”); scanf(“%d”, What if the input is 12345?,When to use Do - While,On some occasion it might be necessary to execute the body of the loop before the test is performed. choosing student system, question 3 of last coursework, etc. The body of the loop is at least executed once.,Do-while Question,Write

37、 a program that require the users to enter the password. The password is composed of all digits and the format is like xxx-xxxx. The users are allowed to enter the password 3 times.,int password1,password2; int pw1_real=123; int pw2_real=4567; int count=0; do printf(Please enter the password in the

38、format xxx-xxxx: ); scanf(%d-%d,The password is 123 4567,Password typed in by users,How to use getch() for this question? Whats the features of getch()?,Scanf vs. %c in loop,Why it happened? it only happen when the data type is char. n is also consider as a character: char a=n; read from buffer, and

39、 there is already a n there before typing in the answer. The n is considered as the result of the input. Solution get away the n scanf(“%c”, More,For-loop,for (expr1; expr2; expr3 ) statement;,expr1;while(expr2)statement;expr3;,Equal to,Example: for(i=0;i100;i+) statements; ,i=0; while(i100) stateme

40、nts; i+; ,Previous Example i =1+2+3+4+99+100 (i=1100) int i , s=0; for (i=1;i=100;i+) s=s+i; printf(“Sum=%dn”,s); ,For-loop Example 1,int count; for ( count = 0; count 3 ; count+ ) printf( “Hi theren”); / Loop Body How many times does the loop body execute? Whats the output? What if count is initial

41、ized to 3? What if “count 3” is changed to “count = 3”? What if “count+” is changed to “+count”? What if “count+” is changed to “count+=1”?,For-loop Nested loop,Whats the output? void main() int row, column; for(row=1; row6; row+) for(column=1;column=row;column+) printf(*); printf(n); getch(); retur

42、n; ,Course work 3,Use the while loop or do while loop to rewrite the program of 3rd question of cw2 Use the for loop to get the output like,Control Flow- Case study,Judy Wang Computer Department Spring 2008,Dead loop in application How to make it,Boolean expression. Whats the output of the program #

43、include #incldue void main() int big=5, small=3; printf(53? : %dn,bigsmall); printf(53? : %dn,bigsmall); getch(); return; How to make a dead loop according to the previous program. while(0) vs while(1),Dead loop in application why we need it,Question 1 in course work 3 More examples: Computer Game,

44、ATM query system, replay of a flash,Error Processing,Make the user interface friendly. Make it easy to use your program Make sure the program could also run even the user give the wrong answer What could happen to the question 1 in cw3,Example scanf %c,Whats the ouput? #include #include void main()

45、int integer1, integer2; char character1,character2; scanf(%d%d, ,Scanf and n,The problem with %c in scanf, where to put the getchar(); Difference between getch() and getchar() The bug of getchar() if the answer is 4d in level choosing or ysdfd in answer. Solutions: Use getch() ,How to analyze simpli

46、fy the question, , ,Part 1,The problem now is simplified to be How to get the part 1,The code to get part 1,What the relationships among stars inside part 1? The code is: for(row=0;rowstars;row+) for(column=0;columnstars-row;column+) printf(“* ”); printf(“n”); , ,The code of 2nd question in cw3,void

47、 main() int row, column, stars; printf(How many stars would you like?: ); scanf(%d, ,More cases,Another shape,While loop to For loop,Question: 1+2+3+10,void main() int count=1,sum=0; while(count!=11) sum+=count count+ getch(); return; ,void main() int count, sum; for(count=1,sum=0;count!=11;count+)

48、sum+=count; getch(); return; ,void main() int count=1,sum=0; for( ;count!=11; ) sum+=count; count+; ,For loop to While loop,Enquire block of a Game to ask if the users like to play again or not.,char answer; for(i=0;i=1;i+) statements; printf(“Play again? y/n: ”); answer = getch(); if(answer = y) i

49、- - ; ,char answer = y; while (answer!=y) statements; printf(“Play again? y/n”); answer = getch(); ,While loop vs For loop,When the number of iterations is fixed, uses for loop, otherwise ,use while loop., srand(time(NULL); /*Make sure numbers are different every time*/ printf(nWould you like to sta

50、rt your try:(y/n); answer=getch(); while(answer=y) num=rand()%10; /*Get the random numbers*/ printf(nnThe number you get is : %d,num+=1); printf(nWould you like to choose another student?(y/n); answer=getch(); printf(nnIts the end of the programn); return; ,This program is to get a random number between 0 to 11 each time the users type in y.,Another way to get random numbers,#include #include /*Its for get the r

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论