https://www.youtube.com/watch?v=FI_knIp3QDA&list=PLgqG2uj21HgkcfVtlr5rPekQl5VWJEnIB&index=19
분기 구문에는 if와 switch가 있는데 이번에 알아볼 구문은 if 구문이다. 실행할 문장이 한개이면 {} 없이 사용할 수 있고, 실행 할 문장이 여러개라면 {}를 통해서 묶어주어야한다. 또한 조건문을 통해서 분기를 한다.
#include <iostream>
int main(){
using namespace std;
if (true){
cout <<"hello"<< endl;
cout <<"world"<< endl;
}
if (false)
cout << "false"<< endl;
return 0;
}
else를 이용하면 if 구문이 참이 아닐때 실행이 된다.
#include <iostream>
int main(){
using namespace std;
if (true){
cout <<"hello"<< endl;
cout <<"world"<< endl;
}
else{
cout << "false"<< endl;
}
return 0;
}
중첩으로 if문을 사용할 수 있다.
#include <iostream>
int main(){
using namespace std;
if (false){
cout <<"1"<< endl;
}
else{
if(true){
cout << "2"<< endl;
}
else{
cout <<"1"<< endl;
}
}
return 0;
}
조건을 여러개를 거쳐서 분기를 하고싶다면 else if를 사용하면 된다.
#include <iostream>
int main(){
using namespace std;
if (false){
cout <<"1"<< endl;
}
else if (true){
cout <<"2"<< endl;
}
else{
cout <<"3"<< endl;
}
return 0;
}