I. Experimental purpose and experimental requirements
(1) Understand the concept of loop structure programming.
(2) Master while, do... Syntax format for while and for statements.
(3) Understand the use of break and continue and the difference between them.
(4) Flexible use of while, do... while and for statements solve real problems.
2. Experimental content
1, programming from the keyboard input integer n, output 1~n can be divided by 2 and 3 at the same time the number and the total number.
#include <stdio.h> int main() { int n, count = 0; printf("请输入一个整数n:"); scanf("%d", &n); printf("1~%d之间能被2和3同时整除的数有:\n", n); for (int i = 1; i <= n; i++) { if (i % 2 == 0 && i % 3 == 0) { count++; printf("%d ", i); } } printf("\n总个数:%d\n", count); return 0; }
2, programming to print the multiplication table in reverse order, requiring the use of loops to achieve.
#include <stdio.h> int main() { int i, j; for (i = 9; i >= 1; i--) { for (j = 9; j >= i; j--) { printf("%d * %d = %d\t", j, i, j * i); } printf("\n"); } return 0; }
3, programming implementation 1! + 2! + 3! +... The sum of the first 10 items requires the use of loops.
#include <stdio.h> int factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } int main() { int sum = 0; for (int i = 1; i <= 10; i++) { sum += factorial(i); } printf("前10项阶乘之和为:%d\n", sum); return 0; }
4, programming to determine whether the positive integer x read from the keyboard is prime, and output the judgment result.
#include <stdio.h> int isPrime(int n) { if (n <= 1) { return 0; } for (int i = 2; i <= n/2; i++) { if (n % i == 0) { return 0; } } return 1; } int main() { int x; printf("请输入一个正整数:"); scanf("%d", &x); if (isPrime(x)) { printf("%d 是质数。\n", x); } else { printf("%d 不是质数。\n", x); } return 0; }