for 문

	for (int i = 0; i < 5; i++) {
		cout << "for i : " << i << endl;
		for (int j = 0; j < 5; j++)
			cout << "for j : " << j << endl;
	}
	string word = "Hellow ! my name is C++";
	
	for (int i = word.size() - 1; i >= 0; i--) {
		cout << word[i] ;
	}
	int a1[4] = { 1,2,3,4 }; 
	int* pt = a1;
	for (int i = 0; i < 4; i++) {
		cout << a1[i] << endl;
	}
	*++pt; // 포인터를 증가 
	++*pt; // 지시되는 값을 증가 
	(*pt)++; // 지시되는 값 증가 
	*pt++; // 원래 주소를 참고하고 나서 포인터 증가
// 컴마 연산자를 이용하여 하나의 포문에 여러개의 증감, 변수선언을 할 수 있다 
	int i, j; // for문 내부에서 선언하지 않는것을 추천 
	for (i = 0, j = 5; j > i; i++, j--) {
	//for (i = 0, j = 5; j > i; ++i, --j) {
		cout << "i : " << i << " j : " << j << endl; 
	}
// range 기반 for 루프 - built-in array 
	int prices[5] = { 1,2,3,4,5 };
	int i = 0; 
	for (int x : prices) {
		cout << "x는 prices의 " << i << "번째 요소 : " << x << endl;
		i++;
	}
 // range 기반 for 루프- array 
    int i = 0;
	array<int, 5> arr = { 1,2,3,4,5 };
	for (int x : arr) {
		cout << "x는 arr의 " << i << "번째 요소 : " << x << endl;
		i++;
	}

for (;;) 는 무한루프이다

While 문 

// while문 사용 
	int i = 0; 
	const char name[20] = "Hong gil dong";
	while (name[i] != '\0') { // 하나의 문자를 나타낼 때는 작은 따움표, 문자열은 큰따움표
		cout << name[i] << "는 ASCII로 : " << int(name[i]) << endl;
		i++;
	}

if 문

	char t1[5] = "mate";
	if (t1 == "mate") {
		cout << "같다" << endl;
	}
	else {
		cout << "다르다" << endl;
	}
	if (strcmp(t1, "mate") == 0) { // 같으면 0을 반환
		cout << "같다" << endl;
	}
	else {
		cout << "다르다 : " << strcmp(t1, "mate") << endl;
	}
	string t2 = "mate"; // string 클래스는 간단하게 비교가능하다 
	if (t2 == "mate") {
		cout << "같다" << endl; 
	}
	else {
		cout << "다르다" << endl; 
	}

do while 

// do while 사용 
	int i = 0; 
	do {
		cout <<  i << endl;;
		i++;
		
	} while (i < 5);
	return 0;

 

if else문의 경우 ?: 연산자를 사용할 수 있다 

#include <iostream>

int main() {
	using namespace std; 
	int a = 6; 
	int b = 7; 
	int c = a > b ? a : b;
	cout << c; // b가 크기때문에 7 출력 
}

 

Switch

  • 조건결과가 정수일 경우 if else 문과 switch 둘다 사용할 수 있다  
  • 책에서는switch의경우선택사항의 개수가 3개 이상일 경우에 사용하는 것이 좋다고 작성되어 있다 
#include <iostream>

int main() {
	using namespace std; 

	// int user_input;
	char user_input;
	cout << "정수를 입력하세요 : ";
	cin >> user_input;

	switch (user_input) {
	case 1: 
		cout << "1을 입력하셨습니다." << endl;
		break; 
	case 2 : 
		cout << "2를 입력하셨습니다" << endl;
		break;
	case 3 : 
		cout << "3를 입력하셨습니다" << endl;
	case 4 : 
		cout << "4를 입력하셨을수도 있고 3을 입력하셨을 수도 있어요" << endl;
		break;
	case 'a':
		cout << "문자를 입력하셨습니다" << endl;
		break;
	default : 
		cout << "입력한 값이 없습니다." << endl;
			break;
	}

	return 0;
}

 

+ Recent posts