とらりもんHOME  Index  Search  Changes  Login

とらりもん - C intro 4. if satement Diff

  • Added parts are displayed like this.
  • Deleted parts are displayed like this.

{(fontc("if statement", red)}} is used to judge the condition and branch the process. As an example, here is a program which judges whether the given integer is an even number or an odd number. First, input this, compile it and run it!

    1. /* iftest.c */
    2. /* compile: $ gcc iftest.c -o iftest */
    3. /* 2017/02/18 K. Nasahara */
    4. # include <stdio.h>
    5. main()
    6. {int x;
    7. printf("Give me a number!\n");
    8. scanf("%d", &x);
    9. if (x%2==0) printf("%d is an even number!\n", x);
   10. else printf("%d is an odd number!\n", x);
   11. }

$ gcc iftest.c -o iftest
$ ./iftest
Give me a number!
4
4 is an even number!
$ ./iftest
Give me a number!
7
7 is an odd number!
$

Let's focus on the syntax if (...) in the line 9. If (...) is true, it processes the next commands (which is on the same line as the if statement, or the command in the next line after the if statement, or in the {} block after the if statement). If the condition does not hold, execute the processing after the statement "else".

 ここで, ifの中の
    x%2
は、xを2で割った余りを求める計算である。こういう計算を{{fontc(剰余計算, red)}}(modulo calculus)という。剰余計算はプログラミングでよく使う。また,
    x%2==0
の, 等号を2つ連続させることには大切な意味がある。これが=というふうにひとつだけだとうまくいかない。

'''課題4-1''' 上のプログラムの9行目の==を=にすると, 何が起きるか? (やってみよ)

'''課題4-2''' 上のプログラムの10行目を削除すると, 何が起きるか? (やってみよ ... ていうか, 以後, 「やってみよ」と書かれてなくても, こういうときは自分から実際に手を動かしてやってみてね! やらずに考えるだけじゃダメだよ。)

 別の例を挙げよう。次のプログラムは、「3では割り切れるが2では割り切れない数」を判定する:

     1. /* iftest2.c */
     2. /* compile: $ gcc iftest2.c -o iftest2 */
     3. /* 2017/02/18 K. Nasahara */
     4. # include <stdio.h>
     5. main() //プログラム本体のはじまり
     6. {
     7. int x;                          //変数x の宣言。
     8. printf("Give me a number!\n");  //メッセージをコンソールに表示。
     9. scanf("%d", &x);                //ユーザーから変数xに値を代入する。
    10. if (x%3==0 && x%2!=0) //条件の設定。
    11. printf("It's my favorite number!\n");  //メッセージをコンソールに表示。
    12. else printf("I don't like it...\n");   //条件が成り立たない場合の処理。メッセージをコンソールに表示。
    13. }

注意: 左端の数字(6.など)は打ち込まないで良い。

$ ./iftest2
Give me a number!
9
It's my favorite number!
$ ./iftest2
Give me a number!
7
I don't like it...
$ ./iftest2
Give me a number!
6
I don't like it...
$

 この10行目がポイントである。2つの条件の「両方を満たすこと」を条件にしたい場合は, それらを「 && 」でつなぐのだ。1個だけの&ではダメである。

また, x%2!=0というのもポイントである。「!=」というのはどういう意味を持つか, 考えてみよ(わかるよね)。

'''課題4-3''' 上のプログラムの&&を||に書き換えてみよ。何が起きるか? そこから, ||の意味を推測せよ。

'''課題4-4'''
昔, 「世界のナベアツ」という芸人が, 「3の倍数と3がつく数でアホになり, 5の倍数で犬っぽくなります」という芸を[[やっていた|https://www.youtube.com/watch?v=3YDuhXp9S7s]]。それをプログラミングせよ。すなわち, 以下のような出力をするプログラムである:
1:
2:
3: Aho
4:
5: Inu
6: Aho
7:
8:
9: Aho
10: Inu
11:
12: Aho
13: Aho
14:
15: Aho Inu
16:
17:
18: Aho
19:
20: Inu
21: Aho
22:
23: Aho
24: Aho
25: Inu
26:
27: Aho
28:
29:
30: Aho Inu
31: Aho
32: Aho
33: Aho
34: Aho
35: Aho Inu
36: Aho
37: Aho
38: Aho
39: Aho
40: Inu


<[[C言語入門]]に戻る>