How to loop in a switch statement in the C language?
In C language, you can use either while or do-while loop structures to repeatedly execute a switch statement. The specific loop structure to use depends on the desired loop condition and execution order.
Here are examples of two common types of switch statements used for looping:
- during the time that
int choice;
while (condition) {
// 获取用户输入的选项
scanf("%d", &choice);
// 根据用户输入的选项执行相应的操作
switch (choice) {
case 1:
// 执行操作1
break;
case 2:
// 执行操作2
break;
case 3:
// 执行操作3
break;
default:
// 执行默认操作
break;
}
}
- – repeat until
int choice;
do {
// 获取用户输入的选项
scanf("%d", &choice);
// 根据用户输入的选项执行相应的操作
switch (choice) {
case 1:
// 执行操作1
break;
case 2:
// 执行操作2
break;
case 3:
// 执行操作3
break;
default:
// 执行默认操作
break;
}
} while (condition);
You can set appropriate loop conditions in the loop as needed (such as using boolean variables, counters, etc.) to control the number of iterations.