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.

Presentation on theme: "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."— 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4318061/slides/slide_26.jpg", "name": "The : operator #include int main(void) { int i, j, min; printf( Please enter two numbers: ); scanf( %d%d , &i, &j); min = i

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

Download ppt "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."

Similar presentations