For loops For loops are controlled by a counter variable. for( c =init_value;c<=fin_value;c+=increment_value) { loop body; } c is a counter. c is a incremented.

Slides:



Advertisements
Similar presentations
BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Advertisements

Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 4 (Conditional Statements) © CPCS
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
C programming: Variables, Expressions part II. Data Types of Arithmetic Expressions Relational Expressions Logical Expressions Multiple Assignments Compound.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Real World Applications: Generating Prime Numbers  Problem Write a program that prints all positive prime integers less than or equal to n. A positive.
Incremental operators Used as a short-hand i++ or ++i  ==  i = i + 1 i-- or --i  ==  i = i – 1 i += a  ==  i = i + a i -= a  ==  i = i - a i *=
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
1 C Programming Week 2 Variables, flow control and the Debugger.
Chapter 5: Structured Programming
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Chapter 5: Structured Programming
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Repetition and Iteration ANSI-C. Repetition We need a control instruction to allows us to execute an statement or a set of statements as many times as.
CSCI 171 Presentation 5. The while loop Executes a block as long as the condition is true general form: while (condition) { statement 1; statement 2;
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Application development with Java Lecture 6 Rina Zviel-Girshin.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
C++ Laboratory Instructor: Andrey Dolgin
Chapter 4 – C Program Control
Chapter 5: Structured Programming
CSE 220 – C Programming Loops.
Chapter 4 (Conditional Statements)
Chapter 4 - Program Control
Week 4 – Repetition Structures / Loops
Loops Chapter 6 Copyright © 2008 W. W. Norton & Company.
Control Structures Lecture 7.
INC 161 , CPE 100 Computer Programming
Looping.
- Additional C Statements
Chapter 4 - Program Control
Exam 1 Date: Feb. 2nd, 2015 during class time (50 minutes) Coverage
Program Control Topics While loop For loop Switch statement
Incremental operators
REPETITION STATEMENTS
More Loops Topics Counter-Controlled (Definite) Repetition
Dale Roberts, Lecturer IUPUI
Chapter 4 - Program Control
More Loops Topics Counter-Controlled (Definite) Repetition
Chap 7. Advanced Control Statements in Java
More Loops Topics Counter-Controlled (Definite) Repetition
Programming Language  C Control Flow
REPETITION Why Repetition?
Presentation transcript:

For loops For loops are controlled by a counter variable. for( c =init_value;c<=fin_value;c+=increment_value) { loop body; } c is a counter. c is a incremented after every iteration (can also be decreased!)

The factorial example again, this time using for #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; }

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } --- i 3 n 1 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 1 i 3 n 1 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 1 i 3 n 1 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 2 i 3 n 1 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 2 i 3 n 2 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 3 i 3 n 2 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 3 i 3 n 6 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 4 i 3 n 6 fact

Factorial with for – step by step #include int main(void) { int i,n,fact = 1; printf("Enter a number\n"); scanf("%d", &n); for(i=1;i<=n;i++) fact *= i; printf("the factorial is %d\n", fact); return 0; } 4 i 3 n 6 fact

For loops (cont.) Equivalent to while… Any for loop can be converted to while loop and vice versa But some applications are more natural to for, and others to while. If we want to perform something for a predefined number of times, better use for. If we just wait for something to happen (not after a certain number or iterations), better use while.

Incremental operators Used as a short-hand for incrementing (or decrementing) variables. i++ or ++i  ==  i = i + 1 i-- or --i  ==  i = i – 1 i += a  ==  i = i + a i -= a  ==  i = i - a i *= a  ==  i = i * a i /= a  ==  i = i / a

Example – fahrenheit-celsius conversion table /* Print a Fahrenheit-to-Celsius conversion table */ #include int main (void) { int fahr; double celsius; int lower = 0, upper = 300; int step = 20; for(fahr=lower ; fahr<=upper ; fahr += step) { celsius = 5.0*(fahr -32.0)/9.0; printf("%d\t%g\n", fahr, celsius); } return 0; }

Nested for loop – rectangle example /* Print a rectangle of *. The height and width are defined by the user */ #include int main(void) { int i,j; int height, width; printf("Please enter the two box dimensions: \n"); scanf("%d%d",&height,&width); for (i = 1; i <= height; i++) { for(j = 1; j <= width; j++) printf("*"); printf("\n"); }

Exercise Write a program that prints an upside- down half triangle of *. The height of the pyramid is the input. ***** *** ** **** *

Solution #include int main(void) { int i, j, size; printf(“Please enter a size:\n”); scanf(“%d”,&size); for (i = 1; i <= size; i++) { for(j = i; j <= size; j++) printf("*"); printf("\n"); } return 0; }

Exercise Write a program accepts a number from the user, and prints out all of the prime numbers up to that number. (Hint – first write a program that checks whether a given number is prime)

Solution #include int main(void) { int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i = 2; i <= last; i++) { for(j = 2 ; j < i; j++) if (i % j == 0) break; if (j == i) printf("the number %d is prime\n", i); } return 0; }

Exercise Change the former program, so that is displays only the largest prime number which is smaller than or equal to the user’s input.

Solution 1 #include int main(void) { int i, j, last; int found = 0; /* This indicates whether we found the largest prime */ printf("enter a number\n"); scanf("%d", &last); i = last; while (!found) /* Loop until we find our guy */ { for(j = 2 ; j <= i; j++) if (i % j == 0) break; if (j > i) /* If this is true then i is prime */ found = 1; else i--; } printf("The largest prime not larger than %d is %d.\n", last, i); return 0; }

Solution 2 (with break) #include int main(void) { int i, j, last; printf("enter a number\n"); scanf("%d", &last); for(i=last;i>1;i--) { for(j = 2 ; j <= i; j++) if (i % j == 0) break; if (j == i) /* i is prime. We found our guy */ break; } printf("The largest prime not larger than %d is %d.\n", last, i); return 0; }

Do while loops do { statement(s) } while (expression); Similar to while loops Except the condition is evaluated after the loop body The loop body is always executed at least once, even if the expression is never true (equals zero)

Example – waiting for legal input #include int main(void) { int i; printf("Please enter a positive number.\n"); do { scanf("%d", &i); if (i<=0) printf("That's not a positive number! Try again.\n"); } while (i<=0); /* The program continues.... */ return 0; }

The ?: operator expr 1 ? expr 2 : expr 3 If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated

The ?: operator #include int main(void) { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = i<j ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }

The switch statement a multiway conditional statement similar to the if-else if-else "statement" allows the selection of an arbitrary number of choices based on an integer value switch (expression) { case const-expr: statements case const-expr: statements … default: statements }

The switch statement expression must have an integral value when the switch statement is executed: the expression is evaluated if a case matches the value of the expression, the program jumps to the first statement after that case label otherwise, the default case is selected the default is optional

That grade example again switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); break; case 7: printf ("C\n"); break; case 6: printf ("D\n"); break; default: printf ("F\n"); }

Give me a break when the switch transfers to the chosen case, it starts executing statements at that point it will “fall through” to the next case unless you “break” out it causes the program to immediately jump to the next statement after the switch statement

Riddle me this Suppose a program’s execution reaches the following line – scanf(“%d%c”, &i, &ch); And suppose the user input is – 100 b What will be the contents of i and ch? Answer i == 100 ch == ‘ ‘ (there’s a space in there)

Spaces in scanf One way to overcome this problem is to introduce a space before the %c – scanf(“%d %c”, &i, &ch); The space tells scanf to ignore all whitespace characters that come after the %d is read

Example – mass conversion Write a program such that – Input – A positive number indicating mass One of the following characters – o, c, k, p, indicating measurement unit (ounce, carat, kilogram, or pound Output – The same mass expressed in grams convert_gr.c

Exercise Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin 1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar Remember to check for the validity of the input!

Solution Coins.c

A cooler exercise Write a program that accepts an real number, followed by an arithmetical operator (+, -, *, /) and then a second real number The program will calculate the result of the expression and present it on the screen Example – for the input 10-8, the output will be – 10-8 = 2

Solution Operation.c