Theory
એક drink કે 2?
User એ આ canteen menu પર 2 દબાવ્યું:
int choice = 2;
switch (choice) {
case 1: printf("Tea ");
case 2: printf("Coffee ");
case 3: printf("Juice ");
}
Programmer ને એક drink ની અપેક્ષા હતી. Screen પર શું આવે છે?
Think first
પહેલાં તમારો અંદાજ
જે print થશે તે બરાબર એ જ રીતે type કરો.
Show the answer
Coffee Juice. switch case 2 પર કૂદ્યો, પછી ચાલતો જ રહ્યો: break વગર મેળ ખાતા case ની નીચેનું દરેક statement ચાલે છે. આને fall-through કહેવાય.
Theory
switch, break, default
switch (value) સીધો એ case label પર કૂદે છે જે value ની બરાબર હોય. break; switch માંથી બહાર લઈ જાય છે; એના વગર execution નીચેના case માં ચાલ્યું જાય છે. default: ત્યારે ચાલે છે જ્યારે કોઈ case મેળ ન ખાય, ladder ના છેલ્લા else ની જેમ.
Practical
સુધારેલું menu
#include <stdio.h>
int main() {
int choice = 2;
switch (choice) {
case 1:
printf("Tea\n");
break;
case 2:
printf("Coffee\n");
break;
case 3:
printf("Juice\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Think first
કોઈ મેળ નહીં
ઉપરના સુધારેલા menu માં choice 2 ને બદલે 7 છે. જે print થશે તે type કરો.
Show the answer
Invalid choice. 7 કોઈ case સાથે મેળ ખાતો નથી, એટલે default ચાલે છે. દરેક menu માં default રાખો.
Theory
case શું હોઈ શકે
Case label એક integer constant હોવું જોઈએ, જેમ કે case 2: કે case 'y': (char એક number તરીકે store થાય છે). case marks >= 35: illegal છે, કારણ કે marks એક variable છે. Float પર switch પણ ન થઈ શકે.
Think first
Illegal lines પકડો
આમાંથી 2 compile નહીં થાય. એમના letters type કરો.
- A:
case 'Y': - B:
case 3 + 1: - C:
case marks >= 35: - D:
switch (f), જ્યાં f એકfloatછે
Show the answer
C અને D. 'Y' (89 તરીકે store થાય) અને 3 + 1 (જેને compiler 4 ગણી લે) constants છે. C માં variable marks છે; D એક float પર switch કરે છે.
Think first
સાચું ઓજાર પસંદ કરો
switch કે if-else ladder? (a) Day 1 થી 7 માટે weekday નું નામ print કરવું. (b) Age પ્રમાણે Child, Adult કે Senior citizen print કરવું.
Show the answer
(a) switch: 7 exact values. (b) if-else ladder: દરેક age group એક range છે, જે case label ચકાસી ન શકે.
Practical
Exam-style: output કહો
#include <stdio.h>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent ");
case 'B':
printf("Good ");
case 'C':
printf("Pass ");
break;
default:
printf("Fail ");
}
return 0;
}This example runs in Gri-Learn on the web, where you can edit it and see the output.
Quiz
Exam-style: ઉપરના program નું output શું છે?
- Good Pass
- Good
- Excellent Good Pass
- Good Pass Fail
Show the answer
Good Pass
switch case 'B' પર કૂદે છે (Good), case 'C' માં ચાલ્યો જાય છે (Pass), અને ત્યાંનો break switch પૂરો કરી દે છે, એટલે default ક્યારેય ચાલતો નથી.
Summary
Key takeaways
- switch એ case પર કૂદે છે જે int કે char value સાથે મેળ ખાય.
- break વગર execution નીચેના cases માં ચાલ્યું જાય છે.
- કોઈ case મેળ ન ખાય તો default ચાલે છે.
- યાદ રાખવાની યુક્તિ: exact values માટે switch, ranges માટે ladder.