Chapter 6 : C Control Statements : Looping - Review Questions

8. Given the input Go west, young man!, what would each of the following programs produce for output? (The ! follows the space character in the ASCII sequence.)

a .

#include <stdio.h>


int main(void) {
    char ch;

    scanf("%c", &ch);
    while (ch != 'g') {
        printf("%c", ch);
        scanf("%c", &ch);
    }
    return 0;
}

Go west, youn!

b. 

#include <stdio.h>

int main(void)
{
    char ch;

    scanf("%c", &ch);
    while ( ch != 'g' )
    {
        printf("%c", ++ch);
        scanf("%c", &ch);
    }
    return 0;
}

Hp!xftu-!zpvo

c. 

#include <stdio.h>

int main(void)
{
    char ch;
    do {
        scanf("%c", &ch);
        printf("%c", ch);

    } while ( ch != 'g' ); 
    return 0;
}

Go west, young

d.

#include <stdio.h>

int main(void) {
    char ch;

    scanf("%c", &ch);
    for (ch = '$'; ch != 'g'; scanf("%c", &ch))
        printf("%c", ch);
    return 0;
}

$o west, youn


9. What will the following program print?

#include <stdio.h>

int main(void) {
    int n, m;

    n = 30;
    while (++n <= 33) printf("%d|", n);

    n = 30;
    do
        printf("%d|", n);
    while (++n <= 33);

    printf("\n***\n");

    for (
            n = 1;
            n * n <
            200; n += 4)
        printf("%d\n", n);

    printf("\n***\n");

    for (
            n = 2, m = 6;
            n < m;
            n *= 2, m += 2)
        printf("%d %d\n", n, m);

    printf("\n***\n");

    for (
            n = 5;
            n > 0; n--) {
        for (
                m = 0;
                m <=
                n;
                m++)
            printf("=");
        printf("\n");
    }
    return 0;
}

 

31|32|33|30|31|32|33|

*** 1

5

9

13

 

*** 2 6

4 8

8 10

 

***

======

=====

====

===

==


13. Define a function that takes an int argument and that returns, as a long, the square of that value.

long square(int num) {
    return ((long) num) * num;
}

14. What will the following program print?

#include <stdio.h>

int main(void) {
    int k;

    for (k = 1, printf("%d: Hi!\n", k); printf("k = %d\n", k), k * k < 26; k += 2, printf("Now k is %d\n", k))
        printf("k is %d in the loop\n", k);
    return 0;
}

1: Hi!

k = 1

k is 1 in the loop Now k is 3

k = 3

k is 3 in the loop Now k is 5

k = 5

k is 5 in the loop Now k is 7

k = 7

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

「已注销」

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

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

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

打赏作者

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

抵扣说明:

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

余额充值