3 Loops
3 Loops
Weng Kai
2020 Fall
Greatest Common Divisor
• Problem: Find the greatest common divisor of two
positive integers u and v.
• Write a program asks for two integers and print out their
gcd.
#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
while ( 1 ) {
if ( b == 0 ) {
break;
}
int r = a%b;
a = b;
b = r;
}
printf("%d\n", a);
}
Opening Question
• PTA W3开课
}
For
==
For Loop
• 则循环的次数是n,⽽循环结束以后,i的值是n。循环的控
制变量i,是选择从0开始还是从1开始,是判断i<n还是判断
i<=n,对循环的次数,循环结束后变量的值都有影响
variants of for loops
• multiple expressions
• But it is in that for loop only and not available after the
loop.
Factorial
• n! = 1×2×3×4×…×n
• variable:
• PTA W2课内7-2
• 如何⽤1⻆、2⻆和5⻆的硬币凑出10元以下的⾦额呢?
Break
• PTA W3课内7-3