とらりもんHOME  Index  Search  Changes  Login

C intro 4. if statement

When you want to make a judgment, you can do it by if statement. Here is an example, which judges whether a given number is even or odd. Let's input, compile, 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. }

Note: You must not input the numbers at the head of each line.

$ 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!
$ 

Now let's interpret the codes. What is important is "if ( ... )" in line 9. This investigates a condition specified in "( )" and, if true, it goes on to the following commands (which exists on the same line as if statement, or the lines in "{ }" just after the if statement). If not true, it jumps to the commands after "else".

Now please watch

x%2 

in the "if" statement. It gives you a residue of division. For example, 5%2=1. For another example, 8%3=2. This calculus is called modulo. We use modulo in many places in the programming.

Please watch

== 

in "x%2==0". The meaning of "double equal" is important. If it is a single equal "=", it does not work as you wish.

Exercise 4-1 Try to replace "==" with "=" in line 9. What happens?

Exercise 4-2 Try to delete line 10. What happens?

Next example. This is a program which finds "a number which can be divided by 3 but not by 2":

    1. /* iftest2.c */
    2. /* compile: $ gcc iftest2.c -o iftest2 */
    3. /* 2017/02/18 K. Nasahara */
    4. # include <stdio.h>
    5. main() //start of the main part
    6. {
    7. int x;                          // declare a variable x
    8. printf("Give me a number!\n");  // display a message
    9. scanf("%d", &x);                // Get a value for x from a user
   10. if (x%3==0 && x%2!=0) // judge condition
   11. printf("It's my favorite number!\n");  // in case of true
   12. else printf("I don't like it...\n");   // in case of false
   13. }

$ ./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...
$ 

Watch the line 10. When we want both of two conditions must me true, we combine them by "&&". A single "&" does not work.

Watch "x%2!=0", too. Consider the meaning of "!=". You are smart enough to find the answer by guessing.

Exercise 4-3 Try rewriting "&&" with "||". What happens? Guess the meaning of "||".

[Go back to C language introduction]

Last modified:2018/10/22 10:07:26
Keyword(s):
References:[C language introduction]