Computer Science/C++

[C++] C와 C++의 공통점 (if, while, for, switch) 씹어먹는 C++ 1-3강

토마토. 2021. 7. 17. 14:04

<< C ❤ C++ >>

공통점 1. 선언

변수

#include <iostream>

int main() {
	int i;
	char c;
	double d;
	float f;

	return 0;
}

포인터

#include <iostream>

int main() {
	int arr[10];
	int* ptr = arr;

	int i;
	int* p = &i;

	return 0;
}

 

공통점 2. 반복문

for

#include <iostream>

int main() {
	int i, sum=0;
	for (i = 0; i < 10; i++) {
		std::cout << i << std::endl;
		sum += i;
	}
	std::cout << sum << std::endl;
	return 0;
}

while

#include <iostream>

int main() {
	int i=0, sum=0;
	while (1) {
		if (i == 10) {
			break;
		}
		sum += i;
		i++;
	}
	std::cout << sum << std::endl;
	return 0;
}

 

** 참고 - std::cin >> user_input; **

input은 >> 이쪽

print는 << 어쩌구 <<

#include <iostream>

int main() {
	int user_input;
	std::cin >> user_input;
	std::cout << user_input << std::endl;
	return 0;
}

if - else

#include <iostream>

int main() {
	
	while (1) {
		int answer = 10, guess;
		std::cout << "guess it!" << std::endl;
		std::cin >> guess;
		if (guess != answer) {
			std::cout << "try it again" << std::endl;
		}
		else {
			std::cout << "good job!" << std::endl;
			break;
		}
	}
	
	return 0;
}

switch

#include <iostream>

int main() {
	int user_input;
	std::cout << "information about TOMATO" << std::endl;
	std::cout << "1. name" << std::endl;
	std::cout << "2. age" << std::endl;
	std::cout << "3. gender" << std::endl;

	std::cin >> user_input;

	switch (user_input) {
		case 1:
			std::cout << "tomato" << std::endl;
			break;
	
		case 2:
			std::cout << "30" << std::endl;
			break;
		case 3:
			std::cout << "woman" << std :: endl;
			break;
		default:
			break;
	}

	return 0;
}