More Loops Topics Relational Operators Logical Operators for Loops.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Advertisements

11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
CMSC 104, Version 8/061L11Relational&LogicalOps.ppt Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else.
CMSC 104, Lecture 171 More Loops Topics l Counter-Controlled (Definite) Repetition l Event-Controlled (Indefinite) Repetition l for Loops l do-while Loops.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
CMSC 104, Version 9/011 More Loops Topics Counter-Controlled (Definite) Repetition Event-Controlled (Indefinite) Repetition for Loops do-while Loops Choosing.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
CMSC 104, Version 9/011 Relational and Logical Operators Topics Relational Operators and Expressions The if Statement The if-else Statement Nesting of.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
ECE Application Programming
Lesson #5 Repetition and Loops.
UMBC CMSC 104 – Section 01, Fall 2016
Lecture 7: Repeating a Known Number of Times
Lesson #5 Repetition and Loops.
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Introduction to C Topics Compilation Using the gcc Compiler
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Relational & Logical Operators
The while Looping Structure
Arrays, For loop While loop Do while loop
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Relational and Logical Operators
Lesson #5 Repetition and Loops.
2008/10/22: Lecture 12 CMSC 104, Section 0101 John Y. Park
Relational and Logical Operators
A First Book of ANSI C Fourth Edition
Chapter 4 - Program Control
1) C program development 2) Selection structure
3 Control Statements:.
The while Looping Structure
Introduction to C Topics Compilation Using the gcc Compiler
Creating your first C program
Chapter 2.1 Repetition.
Computing Fundamentals
UMBC CMSC 104 – Section 01, Fall 2016
Relational & Logical Operators, if and switch Statements
Relational and Logical Operators
Computer programming Lecture 3.
Introduction to C Topics Compilation Using the gcc Compiler
More Loops Topics Counter-Controlled (Definite) Repetition
More Loops Topics Counter-Controlled (Definite) Repetition
Lesson #5 Repetition and Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Relational and Logical Operators
More Loops Topics Counter-Controlled (Definite) Repetition
Loops.
More Loops Topics Counter-Controlled (Definite) Repetition
Relational and Logical Operators
More Loops Topics Counter-Controlled (Definite) Repetition
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
The while Looping Structure
Relational and Logical Operators
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Programming
Incremental Programming
The while Looping Structure
More Loops Topics Counter-Controlled (Definite) Repetition
ICS103: Programming in C 5: Repetition and Loop Statements
More Loops Topics Counter-Controlled (Definite) Repetition
Presentation transcript:

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

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.

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

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.

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

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) )

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

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

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

Truth Table for ! Expression ! Expression 0 1 nonzero 0

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

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

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 + 1 - b == 0) || (b = 5)

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

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.

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?

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)

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

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?

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

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.

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.

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 ; }

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.

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.

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.

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?

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.

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 ; }

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 134518316. <--- Wrong output, because we need to put a “&” before grade on line 8. Try to FIX all the warning messages before testing your program.

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.

Second Step - The C Program 2. 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 ;

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.

Third Step - The C Program 3. 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 ;

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

Fourth Step - The C Program 4. 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 ;

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.

Fourth Step - The C Program 4. 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 ;

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]%

Fifth Step - The Final C Program 5. Finalize the program with proper documentation and programming style. /************************************************************************************** ** Course: CMSC 104, Section 0301 ** Project: average.c ** Date: 10/21/2002 ** Author: Li-Chuan Chen ** SSN: xxx-xx-0301 ** E-mail: lichen@umbc.edu ** ** 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.

Fifth Step - The Final C Program ** ** Pseudocode: ** 1. 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. ** 2. 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 ** 3. Compute average grade. ** 4. Output average grade to user. /************************************************************************************

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 ;

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 ;

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]%

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]%

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]%

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 100. Go back and fix the code.

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 0 - 100. 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 ;

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 0 - 100. Enter a grade : 10 Enter a grade : 110 Grade must beween 0 - 100. Enter a grade : 200 Grade must beween 0 - 100. Enter a grade : 300 Grade must beween 0 - 100. Enter a grade : 20 Enter a grade : 30 Enter a grade : 40 Average grade is 25. umbc7[49]%

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.

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.

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

Assignment and Next Read our class website for submitting Project 1 instructions tomorrow, 10/22. Read Sections 2.6, 4.10 - 4.11, 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 3.11-3.12, 3.4 - 3.6, 4.7, 4.9