ฟังก์ชั่นตัดสินใจ
ฟังก์ชั่นตัดสินใจ หรือ ฟังก์ชั่นเงื่อนไข หรือฟังก์ชั่นทางเลือก ในภาษา C มี 4 แบบ คือ
1 ฟังก์ชั่นทางเลือกทางเดียว คือ ฟังก์ชั่น if
2 ฟังก์ชั่นทางเลือก 2 ทางเดียว คือ ฟังก์ชั่น if-else
3 ฟังก์ชั่นทางเลือกหลายทาง คือ ฟังก์ชั่น switch-case
***************************************
***************************************
ฟังก์ชั่น if (ฟังก์ชั่น 1 ทางเลือก)
รูปแบบ
if ( เงื่อนไข )
{ คำสั่งที่ทำเมื่อเงื่อนไขเป็นจริง; }
ตัวอย่าง
if (age <= 18)
{ printf(“You are young girl \n“);
ตัวอย่างโปรแกรม
#include<stdio.h>
void main()
{ int age=0;
clrscr();
printf(“enter your age : “);
scanf(“%d”,&age);
if (age <=17)
{ printf(“you are young man !!! \n“); }
{ printf(“you are young man !!! \n“); }
printf(“ end of program ! “);
getch();
}
******************************************
ฟังก์ชั่น if - else (ฟังก์ชั่น 2 ทางเลือก)
รูปแบบ
if ( เงื่อนไข )
{ คำสั่งที่ทำเมื่อเงื่อนไขเป็นจริง; }
else
{ คำสั่งที่ทำเมื่อเงื่อนไขเป็นเท็จ;}
ตัวอย่าง
if (age <= 18)
printf (“You are young man \n“);
else
printf (“You are man \n”);
ตัวอย่างโปรแกรม
#include<stdio.h>
void main( )
{ char sex;
clrscr( );
printf(“enter your sex : “);
scanf(“%c”,&sex);
if (sex = “m”)
printf(“you are male !!! \n“);
printf(“you are male !!! \n“);
else
printf (“you are female !!!\n”);
printf(“ end of program ! “);
getch( );
}
**************************************
ฟังก์ชั่น switch…case (ฟังก์ชั่นหลายทางเลือก)
รูปแบบ
switch (ตัวแปร)
{
case ค่าคงที่1 : คำสั่ง ;
break;
case ค่าคงที่2 : คำสั่ง;
break;
…………..
…………..
case ค่าคงที่ n : คำสั่ง;
break;
default : คำสั่ง;
}
ตัวอย่าง
switch (num)
{ case 1 : printf(“one\n”);
break;
case 2 : printf(“two\n”);
break;
case 3 : printf(“three\n”);
break;
case 4 : printf(“four\n”);
break;
case 5 : printf(“five\n”);
break;
default : printf(“number > 5 \n”);
}
ตัวอย่างโปรแกรม
#include<stdio.h>
void main( )
{ char ans;
clrscr( );
printf(“ Enter character : “);
#include<stdio.h>
void main( )
{ char ans;
clrscr( );
printf(“ Enter character : “);
scanf(“%c”,&ans);
switch (ans)
{ case “a” : printf(“A\n”);
break;
case “b” : printf(“B\n”);
break;
case “c” : printf(“C\n”);
break;
case “d” : printf(“D\n”);
break;
default : printf(“character < > “A” “B” “C” “D” \n”);
}
************************************************
แบบฝึกหัด
จงเขียนโปรแกรมรับตัวอักษร 1 ตัว จาก keyboard ถ้าตัวอักษรที่รับมาเป็น
r ให้พิมพ์ red
y ให้พิมพ์ yellow
g ให้พิมพ์ green
b ให้พิมพ์ black
w ให้พิมพ์ while
แต่ถ้าตัวอักษรที่รับมาเป็นตัวอักษรอื่น ให้แสดงข้อความ
“error character !!!”
***********************************
ไม่มีความคิดเห็น:
แสดงความคิดเห็น