Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Loops Topics Relational Operators Logical Operators for Loops.

Similar presentations


Presentation on theme: "More Loops Topics Relational Operators Logical Operators for Loops."— Presentation transcript:

1 More Loops Topics Relational Operators Logical Operators for Loops.
do-while Loops. Choosing an Appropriate Loop. Incremental Programming.

2 Relational Operators Relational expressions evaluate to the integer
< less than > greater than <= less than or equal to >= greater than or equal to == is equal to != is not equal to Relational expressions evaluate to the integer values 1 (true) or 0 (false). All of these operators are called binary operators because they take two expressions as operands.

3 Practice with Relational Expressions
int a = 1, b = 2, c = 3 ; Expression Value Expression Value a < c a + b >= c b <= c a + b == c c <= a a != b a > b a + b != c b >= c

4 Arithmetic Expressions: True or False
Arithmetic expressions evaluate to numeric values. An arithmetic expression that has a value of zero is false. An arithmetic expression that has a value other than zero is true.

5 Practice with Arithmetic Expressions
int a = 1, b = 2, c = 3 ; float x = 3.33, y = 6.66 ; Expression Numeric Value True/False a + b b - 2 * a c - b - a c - a y - x y - 2 * x

6 Logical Operators So far we have seen only simple conditions.
while ( count > 10 ) . . . Sometimes we need to test multiple conditions in order to make a decision. Logical operators are used for combining simple conditions to make complex conditions. && is AND if ( x > 5 && y < 6 ) || is OR if ( z == 0 || x > 10 ) ! is NOT if (! (x > 42) )

7 Truth Table for && Expression1 Expression Expression1 && Expression2 nonzero nonzero nonzero nonzero Exp1 && Exp2 && … && Expn will evaluate to 1 (true) only if ALL subconditions are true.

8 Truth Table for || Expression1 Expression Expression1 || Expression2 nonzero nonzero nonzero nonzero Exp1 || Exp2 || … || Expn will evaluate to 1 (true) if only ONE subcondition is true.

9 Example Use of ! if ( ! (x == 2) ) /* same as (x != 2) */ {
printf(“x is not equal to 2.\n”) ; }

10 Truth Table for ! Expression ! Expression nonzero

11 Operator Precedence and Associativity
Precedence Associativity ( ) left to right/inside-out ! right to left * / % left to right + (addition) - (subtraction) left to right < <= > >= left ot right == != left to right && left to right || left to right = right to left , (comma) right to left

12 Some Practice Expressions
int a = 1, b = 0, c = 7; Expression Numeric Value True/False a b c a + b a && b a || b !c !!c a && !b a < b && b < c a > b && b < c a >= b || b > c

13 More Practice Given int a = 5, b = 7, c = 17 ;
evaluate each expression as True or False. 1. c / b == 2 2. c % b <= a % b 3. b + c / a != c - a 4. (b < c) && (c == 7) 5. (c b == 0) || (b = 5)

14 The for Loop Repetition Structure
The initialization of the the loop control variable, the loop-continuation condition test, and increment of control variable are handled in the for loop structure. for ( expression1; expression2; expression3) { statement } initialization update of control variables loop-continuation test

15 for Loop Expression1 and expression 3 are typically either assignments or function calls, and expression2 is relational expression. A for loop performs initial expression1 just once, prior to loop execution. loop-continuation test is evaluated before each iteration of the loop. If false, the next statement after the loop is executed. Otherwise, the statement(s) inside of the for loop are executed. If the loop-continuation test is initially false, the loop is never entered. Increment or decrement the loop control variable at the very end of each iteration of the loop, and go back to loop-continuation test at the beginning of the loop.

16 Loop Design Considerations
How should the loop condition be initialized? What is the condition that ends the loop? How should the condition be updated? What is the process to be repeated? What is the state of the program when exiting the loop?

17 Example of for Loop Control variable can be incremented or decremented. Count up for ( i = 0; i < 10; i = i + 1 ) { printf (“%d\n”, i) ; } Count by 2 for ( i = 0; i < 10; i = i + 2 ) Count down for ( i = 9; i >= 0; i = i - 1 ) { printf (“%d\n”, i) ; } Count by expression, j=6 for ( i = 0; i < 10; i = i + j/2)

18 Example of for Loop Any of the three parts can be omitted except semicolon. Infinite loop - print 2 continuously, due to i was never incremented. for ( i=2;i < 4; ) { printf (“%d\n”, i) ; } Infinite loop - always true, print “Hi.” continuously. for (; ; ) printf (“Hi.\n”) ; IF OMITTED, NOTHING IS DONE. E.G. i IS NOT INITIALIZED or INCREMENTED

19 The do-while Repetition Structure
{ statement(s) } while ( condition ) ; The body of a do-while is ALWAYS executed at least once. Is this true of a while loop? What about a for loop?

20 Example do { printf (“Enter a positive number: “) ;
scanf (“%d”, &num) ; if ( num <= 0 ) printf (“\nThat is not positive. Try again\n”) ; } } while ( num <= 0 ) ;

21 An Equivalent while Loop
printf (“Enter a positive number: “) ; scanf (“%d”, &num) ; while ( num <= 0 ) { printf (“\nThat is not positive. Try again\n”) ; } Notice that using a while loop in this case requires a priming read.

22 An Equivalent for Loop printf (“Enter a positive number: “) ; scanf (“%d”, &num) ; for ( ; num <= 0; ) { printf (“\nThat is not positive. Try again\n”) ; } A for loop is a very awkward choice here because the loop is event-controlled.

23 Equivalent of for and while Loops
for ( exp1; exp2; exp3) { statement(s) ; } exp1 ; while ( exp2 ) { statement(s) ; exp3 ; } for ( i = 1; i < 5; i = i+1) { printf (“Hi.\n”) ; } i = 1 ; while ( i < 5 ) { printf (“Hi.\n”) ; i = i + 1 ; }

24 So, Which Type of Loop Should I Use?
Use a for loop for counter-controlled repetition. Use a while or do-while loop for event-controlled repetition. Use a do-while loop when the loop must execute at least one time. Use a while loop when it is possible that the loop may never execute.

25 Incremental Programming
Do not try to program everything at one time. Break your program into steps and concentrate on each step at a time. You might need to break each step into pieces. Get the piece working first before completing the whole step. Then build your code on top of existing code with next step. Continue this until you finish all the steps to complete the program. The idea is to have working version of the program at each step.

26 Incremental Programming
Here are general approaches: Declare variables, read input and display input data. May break this step into smaller pieces. Check validity of input (both valid and invalid data). Perform computation and display result. May break this step into smaller pieces. Finalized your program with proper documentation according to the C Coding Standard and Indentation Style. Final test run - test all the possible input data to make sure your program satisfy the project requirements.

27 Incremental Programming Example
Problem: Write a program that calculates the average exam grade for a class of 4 students. Input is student grades and output is average exam grade. Both grade and average exam grade are integer value from 0 to 100. Question: How do we separate this problem into different steps?

28 Breaking Program Into Steps
Declare Variables. Read one grade and output the input grade. Check validity of input grades (both valid and invalid). Read all input grades and compute total grade. Output the total grade. Compute average grade and output average grade. Finalize the program with proper documentation and programming style. Final test run.

29 First Step - The C Program
Use Xemacs to create our C program called grade1.c Declare variables. Read one input grade from user and output it to the user. #include <stdio.h> int main ( ) { int grade ; printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; printf (“Grade is: %d\n”, grade) ; return 0 ; }

30 First Step - Program Output
/* Project: grade1.c */ #include <stdio.h> int main ( ) { int grade ; printf (“Enter a grade : ”) ; scanf (“%d”, grade) ; printf (“Grade is: %d.\n”, grade) ; return 0 ; } linuxserver2[11] gcc -ansi -Wall grade1.c grade1.c: In function `main': grade1.c:8: warning: format argument is not a pointer (arg 2) linuxserver2[12] a.out Enter a grade: 95 Grade is <--- Wrong output, because we need to put a “&” before grade on line 8. Try to FIX all the warning messages before testing your program.

31 First Step - Program Output
/* grade1.c */ #include <stdio.h> int main ( ) { int grade ; printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; printf (“Grade is: %d.\n”, grade) ; return 0 ; } umbc7[13]% gcc -ansi -Wall grade1.c umbc7[14]% a.out Enter a grade: 95 Grade is 95.

32 Second Step - The C Program
Check validity of input data. Test all possible cases for input data. In this case it is Positive integer, e.g. 90, 0 Out of range data, e.g. 101, -10 #include <stdio.h> int main ( ) { int grade ; printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; while (grade < 0) { printf (“Grade must be >= 0. Enter a grade : ”) ; } printf (“Grade is: %d\n”, grade) ; return 0 ;

33 Second Step - Program Output
2. Check validity of input data. umbc7[15]% cp grade1.c grade2.c umbc7[16]% xemacs grade2.c (add error checking code.) umbc7[17]% gcc -ansi -Wall grade2.c umbc7[18]% a.out Enter a grade: -10 Grade must be >= 0. Enter a grade: -20 Grade must be >= 0. Enter a grade: -30 Grade must be >= 0. Enter a grade: 40 Grade is 40.

34 Third Step - The C Program
Read all input grades and compute total grade. Output total grade. #include <stdio.h> int main ( ) { int i, grade, totalGrade ; totalGrade = 0 ; for ( i = 1; i <= 4 ; i = i + 1 ) { printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; while (grade < 0) { printf (“Grade must be >= 0. Enter a grade : ”) ; } totalGrade = totalGrade + grade ; printf (“Total grade is %d\n”, totalGrade) ; return 0 ;

35 Third Step - Program Output
3. Read all input grades and compute total grade. Output total grade. umbc7[19]% cp grade2.c grade3.c umbc7[20]% xemacs grade3.c (add additional code as in 3.) umbc7[21]% gcc -ansi -Wall grade3.c umbc7[22]% a.out Enter a grade : 10 Enter a grade : 20 Enter a grade : 30 Enter a grade : 40 Total grade is 100

36 Fourth Step - The C Program
Compute average grade. Output average grade. #include <stdio.h> int main ( ) { int i, grade, totalGrade ; totalGrade = 0 ; for ( i = 1; i <= 4 ; i = i + 1 ) { printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; while (grade < 0) { printf (“Grade must be >= 0. Enter a grade : ”) ; } totalGrade = totalGrade + grade ; average = totalGrade / 4 printf (“Average grade is %d\n”, average) ; return 0 ;

37 Fourth Step - Program Output
4. Compute average grade. Output average grade. umbc7[23]% cp grade3.c grade4.c umbc7[24]% xemacs grade4.c (add code for average grade.) umbc7[25]% gcc -ansi -Wall grade4.c grade4.c: In function `main': grade4.c:20: `average' undeclared (first use in this function) grade4.c:20: (Each undeclared identifier is reported only once grade4.c:20: for each function it appears in.) Compilation Error! Forgot to declare variable “average” before using it.

38 Fourth Step - The C Program
Compute average grade. Output average grade. #include <stdio.h> int main ( ) { int i, grade, totalGrade, average ; totalGrade = 0 ; for ( i = 1; i <= 4 ; i = i + 1 ) { printf (“Enter a grade : ”) ; scanf (“%d”, &grade) ; while (grade < 0) { printf (“Grade must be >= 0. Enter a grade : ”) ; } totalGrade = totalGrade + grade ; average = totalGrade / 4 printf (“Average grade is %d\n”, average) ; return 0 ;

39 Fourth Step - Program Output
4. Fixed compilation error and recompile the code. Compute average grade. Output average grade. umbc7[26]% xemacs grade4.c (modify code to fix compilation error.) umbc7[27]% gcc -ansi -Wall grade4.c umbc7[28]% a.out Enter a grade : 10 Enter a grade : 20 Enter a grade : 30 Enter a grade : 40 Average grade is 25. umbc7[29]%

40 Fifth Step - The Final C Program
Finalize the program with proper documentation and programming style. /************************************************************************************** ** Course: CMSC 104, Section 0301 ** Project: average.c ** Date: /21/2002 ** Author: Li-Chuan Chen ** SSN: xxx-xx-0301 ** ** ** Description: This program computes the average grade ** of 4 students in a class. ** Input: Four grades. All grade are integers, range from 0 to 100. ** Output: Average grade in integer, range from 0 to 100.

41 Fifth Step - The Final C Program
** ** Pseudocode: ** Declare variables for grade, totalGrade, average, where ** grade = individual grade of a student ** totalGrade = total grade of all students ** average = average grade of the class ** Initialize variables for totalGrade. ** Get input from user and compute total grade. ** While ( more grades to read ) ** Prompt user to input grade. ** Read grade. ** Check if grade is within a valid range. ** Compute total grade, totalGrade = totalGrade + grade. ** End_While ** Compute average grade. ** Output average grade to user. /************************************************************************************

42 Fifth Step - The Final C Program
#include <stdio.h> int main ( ) { /* Variable Declarations */ int i ; /* loop counter */ int grade ; /* individual grade */ int totalGrade; /* total grade of all students */ int average ; /* average grade of the class */ /* Initializations */ totalGrade = 0 ;

43 Fifth “Clean” C Program (con’t)
/* Get input grades from user */ /* Compute total grade */ for ( i = 1; i <= 4; i = i + 1 ) { printf(“Enter grade: ”) ; scanf(“%d”, &grade) ; while ( grade < 0 ) { printf(“Grade must be >= 0. Enter grade: ”) ; } totalGrade = totalGrade + grade ; /* Compute the average grade */ average = totalGrade / 4 ; /* Output the average grade to user. */ printf (“Class average is: %d\n”, average) ; return 0 ;

44 Last Step - Final Test Run
6. Final Test Run with different possible input data set. umbc7[29]% cp grade4.c grade5.c umbc7[30]% xemacs grade5.c (Final touch up with documentation and programming style.) umbc7[31]% gcc -ansi -Wall grade5.c umbc7[32]% a.out Enter a grade : 10 Enter a grade : 20 Enter a grade : 30 Enter a grade : 40 Average grade is 25. umbc7[33]%

45 Last Step - Final Test Run (cont)
6. Final Test Run with different possible input data set. umbc7[34]% a.out Enter a grade : 0 Enter a grade : 100 Enter a grade : 50 Average grade is 37. umbc7[35]%

46 Last Step - Final Test Run (cont)
6. Final Test Run with different possible input data set. umbc7[36]% a.out Enter a grade : -10 Grade must be >= 0. Enter a grade : -20 Grade must be >= 0. Enter a grade : -30 Grade must be >= 0. Enter a grade : 100 Enter a grade : 90 Enter a grade : 80 Enter a grade : 70 Average grade is 85. umbc7[37]%

47 Last Step - Final Test Run (cont)
6. Final Test Run with different possible input data set. umbc7[40]% a.out Enter a grade : -10 Grade must be >= 0. Enter a grade : 10 Enter a grade : 110 Enter a grade : 200 Enter a grade : 300 Average grade is 155. umbc7[41]% Oops! Need to go back and fix the code. Grade also must be less than Go back and fix the code.

48 Fixing C Program /* Get input grades from user . */
/* Compute total grade */ for ( i = 1; i <= 4; i = i + 1 ) { printf(“Enter grade: ”) ; scanf(“%d”, &grade) ; while ( grade < 0 || grade > 100 ) { printf(“Grade must between Enter grade: ”) ; } totalGrade = totalGrade + grade ; /* Compute the average grade */ average = totalGrade / 4 ; /* Output the average grade to user. */ printf (“Class average is: %d\n”, average) ; return 0 ;

49 Last Step - Final Test Run (cont)
6. Final Test Run with different possible input data set. umbc7[48]% a.out Enter a grade : -10 Grade must beween Enter a grade : 10 Enter a grade : 110 Grade must beween Enter a grade : 200 Grade must beween Enter a grade : 300 Grade must beween Enter a grade : 20 Enter a grade : 30 Enter a grade : 40 Average grade is 25. umbc7[49]%

50 Increment Programming - Project 1
Don’t write the whole project at once. Here is a possible approach to implement your project: The first piece you normally write is simple input/output with basic C program skeleton code. Get this part working with variable declarations, read user’s input, display user’s input. Try with just reading one homework grade and display it. Add additional code to read all the homework grades, compute total homework grade, and display the result on the screen. Get this part working. Add additional code to compute average homework grade and display the result on the screen. Get this part working.

51 Increment Programming - Project 1
Repeat step 2 and 3 for additional code for project grades and exam grades, and finally compute the total grade for the course. (At this point, you can copy and paste from previous working code and change the variable names accordingly.) Get this part working. Finalize your program with proper documentation and programming style. Final Test run your program with all the possible input data, both valid and invalid data and make sure it satisfies all the requirements stated in the Project 1 handout.

52 Submit Project 1 Use submit command to submit your Project 1.
submit cs proj1 filename(s) Use submitls command to check status of your Project 1 submission. submitls cs proj1 Use submitrm command to remove files that have already been submitted for your Project 1. submitrm cs proj1 filename(s) Use submitproj command to list projects available for this course . submitproj cs

53 Assignment and Next Read our class website for submitting Project 1 instructions tomorrow, 10/22. Read Sections 2.6, , 4.4 – 4.6, 4.8. Exam 1 on Wed. 11/06. Next: Project 1 due Wed. 10/23, midnight. Assignment Operators, Selection Structures, break and continue Statements. Section , , 4.7, 4.9


Download ppt "More Loops Topics Relational Operators Logical Operators for Loops."

Similar presentations


Ads by Google