MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

Case by case basis

Mapping to numbers
With the methods described so far, you can now make judgments on any condition.
However, let's also learn about another convenient conditional statement provided in C.

We often need to number things around us.
Let's consider, as one example, a class attendance roster at school.
Let's assume the attendance roster for a class in a school is as follows.

番号 名前 性別
1 野比のびBold 男性
2 源静香 女性
3 剛田武 男性
4 骨川スネ夫 男性

Please note that the above is merely an example for clarity and does not reflect the actual setting within the story.

Based on the above, let's create a program that displays the corresponding name when an attendance number is entered.
This can be easily achieved with the aforementioned else-if statement.

Source code
#include <stdio.h>

int main(void)
{
    int no;
    scanf("%d", &no);

    if (no == 1) {
        printf("野比のびBold\n");
    } else if (no == 2) {
        printf("源静香\n");
    } else if (no == 3) {
        printf("剛田武\n");
    } else if (no == 4) {
        printf("骨川スネ夫\n");
    } else {
        printf("そんな番号の人はいない\n");
    }

    return 0;
}


The program above functions correctly.
However, there are many else-if statements, and the program's input is a bit cumbersome.

A simpler way to write this is only when determining matches with multiple numbers.
You can write more beautifully by using a `switch` statement and `case` labels.
The usage of switch and case statements is as follows.

switch statement ~ how to use case
switch (条件式) {
case numerics:
    run文;
    break;
case numerics:
    run文;
    break;
}

A switch statement jumps to the case with a value matching the value of the specified condition expression.
At the jump destination, the statements following the `case` are executed until a `break` statement is encountered.
Exit from the curly braces {} after the switch statement.
The following program is an example rewritten using a switch-case statement.

Source code
#include <stdio.h>

int main(void)
{
    int no;
    scanf("%d", &no);
    
    switch (no) {
    case 1:
        printf("野比のびBold\n");
        break;
    case 2:
        printf("源静香\n");
        break;
    case 3:
        printf("剛田武\n");
        break;
    case 4:
        printf("骨川スネ夫\n");
        break;
    }

    return 0;
}

It's clearer and more aesthetically pleasing now, with better alignment to the numbers.
"Of course, entering a number will display the corresponding name."
Unlike if statements, you can place multiple statements without using {} brackets.

Programmers are artists.
先ほどから、美しく、などという言葉を使用していますが、
実は、プログラマーの間では意外にも普通に使用される言葉is.
プログラマーの仕事は単純な計算を複雑に組み合わせるパズルであり、
それはある側面では芸術に近いと言える部minuteもあります。

Handling cases that don't fit
Actually, when you execute the program with the switch statement and case statements mentioned in the previous section,
The result may differ when created with an else-if statement.

"When using an else-if statement, if a number not on the list is specified,"
"It incorrectly displayed that there was no one with that number, but..."
"The switch-case program isn't displaying anything."

"This allows you to execute a process when the value of another case doesn't match."
You can use the default.
The `default` can be used as an alternative to a `case` statement.
The `default` label is jumped to when no other `case` matches the value.

The following program has been modified with the default added.

Source code
#include <stdio.h>

int main(void)
{
    int no;
    scanf("%d", &no);
    
    switch (no) {
    case 1:
        printf("野比のびBold\n");
        break;
    case 2:
        printf("源静香\n");
        break;
    case 3:
        printf("剛田武\n");
        break;
    case 4:
        printf("骨川スネ夫\n");
        break;
    default:
        printf("そんな番号の人はいない\n");
        break;
    }

    return 0;
}

If you run this program and enter 10 as input, the result will be as follows:

Execution results
10 入力したデータ
そんな番号の人はいない

If you enter numbers 1 through 4, the corresponding names will be displayed correctly.
Group similar tasks.
Next, let's consider a program that displays gender using the roster we just created.
This is very simple, as it only involves rewriting the string.
The following program is a modified version of a string.

Source code
#include <stdio.h>

int main(void)
{
    int no;
    scanf("%d", &no);

    switch (no) {
    case 1:
        printf("男性\n");
        break;
    case 2:
        printf("女性\n");
        break;
    case 3:
        printf("男性\n");
        break;
    case 4:
        printf("男性\n");
        break;
    default:
        printf("そんな番号の人はいない\n");
        break;
    }

    return 0;
}

Once again, we'll be using a familiar approach, but looking at this program...
The word "male" is used three times, which is quite redundant.
Is there any way to get this done in one go?

In fact, it is possible to use multiple cases consecutively.
The `case` itself only signifies the jump location within a `switch` statement.
Connecting multiple cases does not affect the execution.
The following program is a concatenation of cases 1, 3, and 4.

Source code
#include <stdio.h>

int main(void)
{
    int no;
    scanf("%d", &no);

    switch (no) {
    case 1:
    case 3:
    case 4:
        printf("男性\n");
        break;
    case 2:
        printf("女性\n");
        break;
    default:
        printf("そんな番号の人はいない\n");
        break;
    }

    return 0;
}

In this program, when 1, 3, and 4 are entered,
All display as "male."

Beware of the break statement.
この例のように、break文を除けばcaseをつなげられるのですが、
逆に言えば、break文を忘れると関係ないcaseがつながってしまいます。
著名なAppsで、break文を忘れたことで、重大なバグが発生してしまったexamplesもあります。
break文には十minuteにCautionするようにしましょう。

Lack of judgment
As we've seen, using a switch statement with case labels...
It's easy to write programs with multiple branching paths.
However, the truth is that switch statements and their case clauses have very limited discernment.

In a switch statement, a case can only contain integer values.
"It's not possible to include real numbers, variables, or conditional statements."
"In other words, it's not possible to compare variables to each other, such as with an if statement, or to perform comparisons of greater than or less than."

"The switch statement and its case labels can only be used to compare a variable with integer values."
When complex decisions are required, there's no alternative to using if statements.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.

Part 0: Program Overview
  1. What is a program?
Chapter 3: Displaying on the Screen
  1. String Display
  2. newline character
  3. Practice Problem 3
Chapter 4: Displaying and Calculating Numbers
  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4
Chapter 6: Input from the Keyboard
  1. input function
  2. The fear of input
  3. Practice Problem 6
Chapter 9: Repeating a Fixed Number of Times
  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9
Chapter 10: Repeating Without Knowing the Number of Times
  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10
Chapter 13: Handling Multiple Variables at Once
  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13
Chapter 19: Dynamic Arrays
  1. Create arrays freely.
  2. Practice Problem 19