How To Use Switch Statement in C Program
How To Use Switch Statement in C Program
PREPROCESSOR DIRECTIVES:
// Preprocessor Directives OR Header Files
#include<stdio.h>
// stdio (Standard Input Output) → To mention predefined keywords such as “printf” & “scanf”
#include<conio.h>
// (Console Input Output) → To mention predefined keywords such as “clrscr” & “getch”
MAIN FUNCTION:
void main ()
PROGRAM BODY:
{
int n;
// int for integer, float for decimal value, char for character
clrscr();
scanf(“%d”, &n);
// scanf → to get value from user → %d format specifier for integer, %f for float, %c for character
switch(n)
// switch (expression)
ADMISSION TEAM WHATSAPP
0347-2782177 دمہایگروہںیاورابروہںیےکےئلڈاٹیرفامہرکےنواالوادحادارہ،اچروںالکزسمہن
0342-1016201 سیگرپیپزاورریپگنمیکسےکےیلیتایکمیویٹبلنیچوزٹرکںی
YOUTH اکیالھکوٹسڈسٹنوکآنالنئایتریرکواےنواالوادحادارہ
ACADEMY 12TH COMPUTER
یتایکمےکاستاجریONLINE ااحتمانتکایتری
رھگٹیب
{
case1:
printf(“Monday”);
break;
case2:
printf(“Tuesday”);
break;
case3:
printf(“Wednesday”);
break;
case4:
printf(“Thursday”);
break;
case5:
printf(“Friday”);
break;
case6:
printf(“Saturday”);
break;
case7:
printf(“Sunday”);
break;
Default:
// default is used to print the default value. It is used when all the switch statements go wrong.
Printf(“invalid number”);
getch();
//holding screen
}
ADMISSION TEAM WHATSAPP
0347-2782177 دمہایگروہںیاورابروہںیےکےئلڈاٹیرفامہرکےنواالوادحادارہ،اچروںالکزسمہن
0342-1016201 سیگرپیپزاورریپگنمیکسےکےیلیتایکمیویٹبلنیچوزٹرکںی
YOUTH اکیالھکوٹسڈسٹنوکآنالنئایتریرکواےنواالوادحادارہ
ACADEMY 12TH COMPUTER
یتایکمےکاستاجریONLINE ااحتمانتکایتری
رھگٹیب
OUTPUT:
Enter number of a weekday: 6
Saturday
COMMON ERRORS:
✓ Don’t using terminator at the end of the statements (;)
✓ Using terminator at the end of if, else if, else statement
✓ Wrong condition
✓ Using wrong sign instead of colon (:)
✓ Mistakes in outer and inner if
✓ Go to inner if without outer one
✓ Mentioning wrong variable name in if statement
✓ Using getch & clrcsr with out including conio.h
✓ Mention & in printf while calling a variable
✓ Calling wrong variables in printf and scanf
✓ Using wrong data type
✓ Using wrong format specifier
✓ Don’t write statements in “ “
✓ Wrong use of “ “