• 회원가입
  • 로그인
  • 구글아이디로 로그인

[basic] C++ - If ... Else - (이프 조건문) ★

3,246  
목차
  1. C++ 조건문
  2. if 구문
  3. if...else... 구문
  4. if...else if...else 구문
  5. 3항 조건문

 

C++ 조건문

1. 

C++은 수학의 비교 및 논리 연산자 이용해 조건 판별 가능.

(예) < , <= , > , >= , == , !=

 


2.

if 구문 : if 조건이 참이면 실행.

else if 구문 : 앞서 지정한 조건이 거짓일 때 새로 시험할 조건문.

else 구문 :  앞서 지정한 모든 조건이 거짓일 때 실행.

cf.

switch 구문 : 각각의 경우에 실행할 조건문 지정.

 

 

if 구문

※ if는 소문자로 기재. 

※ 대문자 사용해 If (또는, IF)로 적으면 에러 발생.

 

if (조건식) {

   조건이 참일 때 실행할 코드



[예제1] 

 

#include <iostream>

using namespace std;

int main() {

  if (4 > 3) {

    cout << "참"; // 참

  }  

  return 0;

}

 


[예제2]

 

#include <iostream>

using namespace std;

int main() {

  int x = 4;

  int y = 3;

  if (x > y) {

    cout << "참";

  }  

  return 0;

}

 

 

if...else... 구문

 

if (조건식) {

    조건이 참일 때 실행할 코드

} else {

    조건이 거짓일 때 실행할 코드

}

 


[예제] 

 

#include <iostream>

using namespace std;

int main() {

  int time = 15;

  if (time < 12) {

    cout << "오전";

  } else {

    cout << "오후";

  }

  return 0;

}

 

결과값: 오후

 

if...else if...else 구문


if(조건1) {

    조건1이 참일 때 실행할 내용.

} else if(조건2) {

    조건1이 거짓이면서, 조건2가 참일 때 실행할 내용.

} else {

    조건1과 조건2 모두 거짓일 때 실행할 내용.

}

 

※ else if 구문은 여러 개 올 수 있음.


[예제] 

 

#include <iostream>

using namespace std;

int main() {

  int time = 20;

  if (time < 12) {

    cout << "오전";

  } else if (time < 18) {

    cout << "오후";

  } else {

    cout << "저녁";

  }

  return 0;

}

 

결과값: 저녁

 

3항 조건문

※ if...else... 조건문의 축약 표현.

※ 실무에서 아주 빈번하게 사용.

 

variable = (condition) ? true_execute :  false_execute;

즉,

변수 = (조건식) ? 조건 참이면 실행코드 : 조건 거짓이면 실행코드;

 


[예제] 

 

#include <iostream>

#include <string>

using namespace std;

int main() {

  int time = 15;

  string result = (time < 12) ? "오전" : "오후";

  cout << result;

  return 0;

}

 

결과값: 오후



분류 제목
basic C++ - references (참조변수) + 변수의 메모리 주소
basic C++ - Pointers (포인터)
function C++ - Functions (함수) - 정의/호출
function C++ - Function Parameters (함수 매개변수)
function C++ - Function Overloading (함수 오버로딩)
class C++ - OOP (객체 지향 프로그래밍)
class C++ - Class (클래스) / Object (객체)
class C++ - Class Methods (클래스 메서드)
class C++ - Constructors (생성자)
class C++ - Access Specifiers (접근지정자)
class C++ - Encapsulation (캡슐화)
class C++ - Inheritance (상속)
class C++ - Polymorphism (다형성)
class C++ - Files (파일) - 파일생성/파일읽기/파일쓰기
class C++ - Exceptions (= Try...Catch..) - 에러 제어
howto C++ - 사용자 입력값 더하기 ★ (Add Two Numbers)
2/2
목록
찾아주셔서 감사합니다. Since 2012