NJUPT-“C Language“ experiment report 3

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;
}

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高教百科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值