week7-loop
week7-loop
Loop
Topic of this week
• Loop
• for Repetition Structure
• Notes and Observations
• Programming Exercises
• Structure
for(initialization; loopContinuationTest; increment)
statement
Example:
for( counter = 1; counter <= 10; counter++ )
printf( "%d\n", counter );
No
• Prints the integers from one to ten. semicolon
after last
expression
• Arithmetic expressions
• Initialization, loop-continuation, and increment can
contain arithmetic expressions.
if x = 2 and y = 10
for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
#include <stdio.h>
int main()
{
int i;
return 0;
}
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
Exercise 7.2
int main()
{
int i, j;
#include <stdio.h>
int main() {
int i, j;
for(i = 2; i <= 100; i ++)
{
for(j = 2; j < i; j++)
{
if(i % j == 0) break;
}
if(j == i)
printf("%d\n", i);
}
return 0;
}
#include <stdio.h>
int main()
{
int i, j; /* loop control variables */
printf(” i j\n"); /* prints column labels */
for (i = 1; i < 4; i = i + 1) /* heading of outer for loop */
{
printf("Outer %6d\n", i);
for (j = 0; j < i; j = j + 1) /* heading of inner loop */
{
# include <stdio.h>
int main ()
{
int i, n, f;
printf ("Enter n: ");
scanf ("%d", &n);
f = 1; /* 0! */
for (i = 1; i <= n; ++i) {
f *= i; /* Now , f = i! */
}
printf ("%d! = %d\n", n, f);
return 0;
}
#include <stdio.h>
int main()
{
int count=0, number;
int n500, n200, n100, n50, n20, n10, n5;
printf("Input the amount you want to withdraw:");
scanf("%d", &number);
for(n500=0; n500<=number/500000; n500++)
for(n200=0; n200<=(number-500000*n500)/200000; n200++)
for(n100=0; n100<=(number-500000*n500-200000*n200)/100000; n100++)
for(n50=0; n50<=(number-500000*n500-200000*n200-100000*n100)/50000; n50++)
for(n20=0; n20<=(number-500000*n500-200000*n200-100000*n100-50000*n50)/20000; n20++)
for(n10=0; n10<=(number-500000*n500-200000*n200-100000*n100-50000*n50-
20000*n20)/10000; n10++){
}
TRƯỜNG CÔNG NGHỆ THÔNG TIN VÀ TRUYỀN THÔNG
School of Information and Communication Technology
Exercise 7.9
char ch=‘y’;
for ( ; ch==‘y’ || ch!=‘Y’; ){
// do something
Withdrawal program
1. List all possibilities
2. List all possibilities that use the smallest number of
banknotes
3. Exit
What is your selection: