If and If else
Make a condition and run it.
เมื่อเราเขียนโปรแกรมโดยที่เราต้องการให้โปรแกรมทำตามคำสั่งโดยเงื่อนไขบางอย่าง เราสามารถกำหนดเงื่อนไขนั้นๆ ได้โดยการใช้คำสั่ง if โดยหลักการของคำสั่งจะเป็นไปตามด้านตัวอย่างแบบต่างๆด้านล่างดังนี้
การเขียนโปรแกรมสร้างเงื่อนไขด้วย if
Syntax การเขียน if statement นั้นจะเป็นดังนี้
if (condition) {
things you want to do;
}
#include<iostream>
using namespace std;
int main (){
int A = 0;
cout<<"Please enter a number to A: "<< endl;
cin >> A;
if(A<5){
cout<<"Condition met"<<endl;
}
return 0;
}
นอกจากนั้นเราสามารถใส่เงื่อนไขได้มากกว่า 1 เงื่อนไขได้ในหนึ่ง condition
#include<iostream>
using namespace std;
int main () {
int A = 0;
cout<<"Please enter a number to A: "<< endl;
cin >> A;
if(A<5 && A >1){ // two condition need to met
cout<<"Condition met"<<endl;
}
return 0;
}
หรือเราสามารถใส่เงื่อนไขหลายๆข้อได้โดยการนำ if มาต่อกัน
#include<iostream>
using namespace std;
int main () {
int A = 0;
cout<<"Please enter a number to A: "<< endl;
cin >> A;
if(A<8) {
cout<<"A less than 8"<<endl;
}
if(A<6) {
cout<<"A less than 6"<<endl;
}
if(A<4) {
cout<<"A less than 4"<<endl;
}
if(A<7) {
cout<<"A less than 7"<<endl;
}
if(A<5) {
cout<<"A less than 5"<<endl;
}
return 0;
}
เมื่อรันแล้วจะเห็นได้ว่าทั้งสามรูปแบบต่างมีเอกลักษณ์ของตัวมันเองซึ่งอยู่กับสถานะการณืของการออกแบบของผู้ใช้ว่าแบบไหนจะเหมาะสมที่สุดสำหรับการนำไปใช้เขียนโปรแกรมที่ต้องการ
การเขียนโปรแกรมสร้างเงื่อนไขด้วย if else
Syntax การเขียน if else statement นั้นจะเป็นดังนี้ โดยการทำงานของมันจะทำสองอย่างคือ เมื่อเป็นไปตามเงื่อนไขจะทำคำสั่งที่อยู่ภายใต้วงเล็บของ if และถ้าไม่เป็นไปตามเงื่อนไขจะไปทำงานอยู่ภายใต้วงเล็บของ else
#include<iostream>
using namespace std;
int main () {
int A = 0;
cout<<"Please enter a number to A: "<< endl;
cin >> A;
if(A == 8) {
cout<<"A equal 8"<<endl;
}
else {
cout<<"A is other number than 8"<<endl;
}
return 0;
}
เรายังสามารถกำหนดเงื่อนไขอื่นๆได้มากกว่า 1 เงื่อนไขเช่นเดียวกับการเขียนเงื่อนไขแบบ if ธรรมดา
#include<iostream>
using namespace std;
int main () {
int A = 0;
cout<<"Please enter a number to A: "<< endl;
cin >> A;
if(A < 4) {
cout<<"A less than 4"<<endl;
}
else if(A < 3) {
cout<<"A less than 3"<<endl;
}
else if(A < 7) {
cout<<"A less than 7"<<endl;
}
else if(A < 8) {
cout<<"A less than 8"<<endl;
}
else if(A < 9) {
cout<<"A less than 9"<<endl;
}
else {
cout<<"A is 9 or larger"<<endl;
}
return 0;
}
จากการรัน code ตัวอย่างด้านจะเห็นว่าเมื่อไหร่ก็ตามที่ A เข้าเงื่อนไขใดเงื่อนไขหนึ่งแล้วเป็นจริง จะไม่ทำการตรวจสอบเงื่อนไขอื่นๆต่อ นี่คือเอกลักษณ์ของการใช้ if else แต่อย่างไรก็ตามผู้เขียนจำเป็นต้องระมัดระวังในการเขียนเงื่อนไขที่ไม่จำเป็น
แหล่งอ้างอิง :
Last updated
Was this helpful?