Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
7.

How to use switch, break and continue statements in a program? Give example code.

Explanation

switch Statement ‘:

  • The ‘switch statement ‘ is used to select one of many code blocks to be executed based on the value of an expression.

#include <stdio.h>

int main() {

int choice;

printf("Enter a choice (1, 2, or 3): ");

scanf("%d", &choice);

 switch (choice) {

case 1:

printf("You chose option 1.\n");

break; // Break out of the switch statement.

case 2:

printf("You chose option 2.\n");

break;

case 3:

printf("You chose option 3.\n");

break;

default:

printf("Invalid choice.\n");

}

 return 0;

}

 

Break Statement:

  • The ‘ break statement ‘ is used to exit a loop or ’ switch ‘ statement prematurely when a certain condition is met.

#include <stdio.h>

int main() {

int i;

for (i = 0; i < 5; i++) {

if (i == 3) {

break; // Exit the loop when i equals 3.

}

printf("i is %d\n", i);

}

 return 0;

}

 

Continue Statement:

  • The ‘ continue statement ‘ is used to skip the current iteration of a loop and continue with the next iteration.

 

#include <stdio.h>

int main() {

int i;

for (i = 0; i < 5; i++) {

if (i == 3) {

continue; // Skip the iteration when i equals 3.

}

printf("i is %d\n", i);

}

 return 0;

}

‘ the switch ‘ statement allows you to select different code blocks based on the value of choice. The ‘ ‘ break statement ’ is used to exit the loop or ‘switch statement ’. The continue statement is used to skip the current iteration of a loop and move to the next iteration. These statements are essential for controlling the flow of your program.