Application of Nested Loops in C Language: break and continue Statements

Application of Nested Loops in C Language: break and continue Statements

【Problem 1】The multiplication table for elementary school students, known as the “Nine-Nine Multiplication Table,” is a 9×9 grid where both rows and columns range from 1 to 9, as shown in the table.

Application of Nested Loops in C Language: break and continue Statements

#include <stdio.h>
int main() {
    int i, j;
    for (i = 1; i <= 9; i++) {
        for (j = 1; j <= i; j++) {
            printf("%d*%d=%d\t", j, i, i * j);
        }
        printf("\n");
    }
    return 0;
}

Application of Nested Loops in C Language: break and continue Statements

【Problem 2】

In daily life, we have played a game of finding friends. One student finds a friend among a group of classmates, and after finding a friend, they switch to another classmate to find a friend again. Now, design a game to find letter friends. Input a character ‘ch’ from the keyboard; if ‘ch’ is a letter, output the found letter friend ‘ch’. If the input is not a letter, the game ends.

#include <stdio.h>
    void main() {
        char ch;
        while(1) // Loop
        {
            printf("Please enter the friend to find: ");
            ch=getchar(); // Input character
            getchar();
            if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z') // Check if it is a letter friend
                printf("Found letter friend %c\n",ch);
            else {
                printf("Not a letter friend, exiting the game!\n"); // Not a letter, exit
                break;
            }
        }
    }

Application of Nested Loops in C Language: break and continue Statements

【Problem 3】

Now let’s play a guessing number game. Please have the player input a guessed number, ranging from 0 to 9, and then guess all integers within 100 that can be divided by this input number and have the same unit digit as this number. The game ends when all guessed numbers are output.

#include <stdio.h>
    void main() {
        int n,i,j;
        printf("********** Guessing Number Game **********\n");
        printf("Please enter a guessed number 1~9:");
        scanf("%d",&n); // Input the guessed number n
        printf("Please guess all integers within 100 that can be divided by %d and have %d as the unit digit:\n",n,n);
        for(i=0;i<=9;i++) // Loop variable i as the tens digit
        {
            j=i*10+n; // Calculate the two-digit number with unit digit n
            if(j%n!=0) continue; // Check if the two-digit number can be divided by n
            printf("%d\n",j);
        }
        printf("Guessing complete!");
    }

Application of Nested Loops in C Language: break and continue StatementsApplication of Nested Loops in C Language: break and continue Statements

Leave a Comment