💻 프로그래밍 언어/C++
C++ 3주차
SA성아
2023. 9. 20. 12:45
C언어 문법 정리 1
sizeof 연산자 예
#include <stdio.h>
int main(void)
{
int x;
int y[10];
printf("%d\n", sizeof("I love you!"));//12
printf("%d\n", sizeof("대한"));// 5(cp949) or 7(utf-8)
printf("%d\n", sizeof(int));// 4
printf("%d\n", sizeof(x));// 4, sizeof x라고 써도 됨
printf("%d\n", sizeof(y));// 40, sizeof y라고 써도 됨
return 0;
} //c언어
#include <iostream>
int main()
{
int x; // 정수형 변수 x 선언
int y[10]; // 정수형 배열 y 선언, 크기는 10
std::cout << sizeof("I love you!") << std::endl; // "I love you!" 문자열의 크기 출력. 문자열 끝의 null 문자를 포함해 총 12바이트.
std::cout << sizeof("대한") << std::endl; // "대한" 문자열의 크기 출력. 인코딩에 따라 다르지만 cp949일 경우 5바이트, utf-8일 경우 7바이트.
std::cout << sizeof(int) << std::endl; // int 타입 자체의 크기 출력. 일반적으로 4바이트.
std::cout << sizeof(x) << std::endl; // 변수 x의 크기 출력. int 타입이므로 위와 동일하게 4바이트.
std::cout << sizeof(y) << std::endl; // 배열 y의 전체 크기 출력. int 타입 원소가 10개 있으므로 총 40바이트.
return 0;
} //c++
혼합 대입 연산자
x = x + 1;
x += 1;
x++;
++x;
위 4개의 코드 모두 같은 뜻이다.
시프트 연산자 예
#include <stdio.h>
int main(void)
{
printf("%d\n", 90 << 1); //180
printf("%d\n", 90 * 2); //180
printf("%d\n", 90 << 2); //360
printf("%d\n", 90 << 3); //720
printf("%d\n", 90 << 4);//1440
printf("%d\n", 90 >> 1); //45
printf("%d\n", 90 / 2); //45
printf("%d\n", 90 >> 2); //22
printf("%d\n", 90 >> 3); //11
return 0;
} //C언어
#include <iostream>
int main()
{
std::cout << (90 << 1) << std::endl; //180
std::cout << (90 * 2) << std::endl; //180
std::cout << (90 << 2) << std::endl; //360
std::cout << (90 << 3) << std::endl; //720
std::cout << (90 << 4) << std::endl;//1440
std::cout << (90 >> 1) <<std::endl; //45
std::cout << (90 / 2) <<std::endl; //45
std::cout << (90 >> 2) <<std :: endl ;//22
std::cout << (90 >> 3) <<std :: endl ;//11
return 0;
} //C++
시프트 연산자는 cin, cout으로 만나면 다른 의미로 쓰인다.
c, c++, java, c#, javascript 연산자 공통점
연산자 | 설명 |
산술 연산자 | 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/), 나머지(%) 등 수학적인 계산을 수행합니다. |
할당 연산자 | 변수에 값을 할당하는데 사용됩니다. (=) |
비교 연산자 | 두 값의 비교를 수행하고 결과로 true 또는 false를 반환합니다. (==, !=, <, >, <=, >=) |
논리 연산자 | 조건문이나 반복문에서 조건식을 평가할 때 사용되며, 논리적인 AND(&&), OR(` |
비트 연산자 | 이진수로 표현된 값을 다룰 때 사용되며, AND(&), OR(|), XOR(^), NOT(~) 등의 비트 단위 연산을 수행합니다. |
증감 연산자 | 변수의 값을 1만큼 증가시키거나 감소시킵니다. (++, --) |
조건(삼항) 연산자 | 조건에 따라 다른 값을 반환하는데 사용됩니다. (condition ? value1 : value2) |
멤버 접근(도트) 연산자 | 객체나 구조체의 멤버에 접근하기 위해 사용됩니다. (.) |
배열 접근(인덱스) 연산자 | 배열 요소에 접근하기 위해 사용됩니다. ([]) |
연산자의 우선순위(precedence)와 결합성(associativity)
C언어 문법 정리 2-1
제어문(Control flow)
C언어와 javascript 제어문 비교
제어문 | C | JavaScript |
if 문 | if (condition) { ... }<br>else if (condition) { ... }<br>else { ... } | if (condition) { ... }<br>else if (condition) { ... }<br>else { ... } |
switch 문 | switch(expression) { case value1: ... break; case value2: ... break; default: ...} | switch(expression) { case value1: ... break; case value2: ... break; default: ...} |
for 반복문 | for (initialization; condition; update) {...} | for (initialization; condition; update) {...} |
while 반복문 | while(condition){...} | while(condition){...} |
do-while 반복문 | do{...} while(condition); | JavaScript도 동일함. 하지만 일반적으로 자주 사용되지 않음. |
C++, java, C# 제어문 비교
제어문 | C++ | Java | C# |
if 문 | if (condition) { ... }<br>else if (condition) { ... }<br>else { ... } | if (condition) { ... }<br>else if (condition) { ... }<br>else { ... } | if (condition) { ... }<br>else if (condition) { ... }<br>else { ... } |
switch 문 | switch(expression) { case value1: ... break; case value2:... break; default:...} | switch(expression) { case value1:... break; case value2:... break; default:...} | switch(expression){case value1:...break;case value2:...break;default:...} |
for 반복문 | for(initialization; condition; update){...} | for(initialization; condition; update){...} | for(initialization; condition; update){..} |
while 반복문 | while(condition){..} | while(condition){..} | while(condition){..} |
do-while 반복문 | do{..} while(condition);, |
C언어에서 제일 많이 사용하는 제어문 순서
if-else 문: 조건에 따라 코드를 실행하거나 건너뛸 때 사용합니다.
for 반복문: 특정 조건이 만족될 때까지 코드를 반복적으로 실행할 때 사용합니다.
while 반복문: for 문과 유사하게 특정 조건이 만족될 때까지 코드를 반복적으로 실행하지만, 초기화와 업데이트 부분이 별도로 분리되어 있습니다.
switch-case 문: 여러 조건 중 하나가 만족될 때 해당하는 코드 블록을 실행할 때 사용합니다.
if문 예제 1
#define _CRT_SECURE_NO_WARNINGS //Visual Studio에서만 사용
#include <stdio.h>
int main(void)
{
int score;
printf("당신의 점수를 입력하고 Enter를 누르세요=");
scanf("%d", &score);
if (score < 60) printf("60점 미만이므로 재수강해야 합니다.\n");
//if문 4가지 방법으로 만들어보기
return 0;
}
if문 다음에는 (조건)을 쓰고 조건이 맞으면 실행할 문장을 { }안에 쓴다.
if~else문 예제 2 : 60 미만 판단, 양자택일
#define _CRT_SECURE_NO_WARNINGS //Visual Studio에서만 사용
#include <stdio.h>
int main(void)
{
int score;
printf("당신의 점수를 입력하고 Enter를 누르세요=");
scanf("%d", &score);
if (score < 60) {
printf("60점 미만이므로 재수강해야 합니다.\n");
}
else {
printf("60점 이상이므로 Pass입니다.\n");
}
return 0;
}
다중 if~else문 1 : 주민등록번호로 성별 판단
#include <stdio.h>
int main(void)
{
int num;
printf("당신의 주민등록번호 뒷 자리의 첫 번째 숫자를 입력하세요=");
scanf("%d", &num);
if (num == 1 || num == 3)
printf("당신은 남성이군요!\n");
else if (num == 2 || num == 4)
printf("당신은 여성이군요!\n");
else
printf("당신은 대한민국 사람이 아니군요!\n");
return 0;
}
조건문 : switch∼case문
#define _CRT_SECURE_NO_WARNINGS //Visual Studio에서만 사용
#include <stdio.h>
int main(void)
{
int value;
printf("1~3까지의 수를 입력하세요:");
scanf("%d", &value);
switch (value) {
case 1:
printf("1을 입력하셨습니다.\n");
break;
case 2:
printf("2을 입력하셨습니다.\n");
break;
case 3:
printf("3을 입력하셨습니다.\n");
break;
default:
printf("잘못 입력하셨습니다.\n");
break;
}
return 0;
}
switch∼case문을 사용하는 프로그래밍 언어
C
C++
Java
JavaScript
C#
PHP
Swift
Go
Rust
다양한 for문의 형태 1
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i< 10; i++) {
printf("Hello ");
}
return 0;
} //C
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
std::cout << "Hello ";
}
return 0;
} //c++
for (let i = 0; i < 10; i++) {
console.log("Hello ");
} //javascript
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
Console.Write("Hello ");
}
}
} //C#
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.print("Hello ");
}
}
} //java
for문을 활용한 예제
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 10; i++) {
printf("%2d: 박성아\n", i+1);
}
return 0;
}
C++에서 for문을 사용하는 4가지 방법
#include <iostream>
#include <iomanip> //setw()
int main()
{
for (int i = 1; i <= 10; i++) {
std::cout << std::setw(2) << i << " : Hello\n";
}
}
i를 찍을때 몇 칸을 찍을지 setw()안에 넣어야한다.
setw()를 쓸 때는 iomanip를 선언해야한다.
#include <iostream>
#include <iomanip> //setw()
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++) {
cout << setw(2) << i << " : Hello\n";
}
}
setw(2) => i를 2칸으로 찍어라
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++) {
cout.width(2); //다음에 출력되는 하나(i)를 두칸에 출력
cout << i << " : Hello\n";
}
}
width(2) => i를 2칸으로 찍어라
#include <iostream>
int main()
{
for (int i = 1; i <= 10; i++) {
std::cout.width(2); //다음에 출력되는 하나(i)를 두칸에 출력
std::cout << i << " : Hello\n";
}
}
switch∼case문 계산기(반복)
#define _CRT_SECURE_NO_WARNINGS //Visual Studio에서만 사용
#include <stdio.h>
int main(void)
{
char op;
int num1, num2;
for (; ; ) //추가
{ //추가
printf("\n덧셈과 뺄셈만 가능합니다\n");
printf("끝내려면 0+0을 입력하세요\n"); //추가
printf("계산하려는 수식(예:10+20)을 입력하세요:");
scanf("%d%c%d", &num1, &op, &num2); //10+20
if (num1 == 0 && num2 == 0) break; //추가
switch (op) {
case '+':
printf("덧셈 결과는 %d입니다.\n", num1 + num2);
break;
case '-':
printf("뺄셈 결과는 %d입니다.\n", num1 - num2);
break;
default:
printf("다시 입력하세요\n");
break;
}// switch~case문 끝
} //추가, for문 끝
return 0;
} //C
#include <iostream>
using namespace std;
int main() {
char op;
int num1, num2;
while (true) {
cout << "덧셈과 뺄셈, 곱셈, 나눗셈 가능합니다\n";
cout << "끝내려면 0+0을 입력하세요\n";
cout << "계산하려는 수식(예:10+20)을 입력하세요:";
cin >> num1 >> op >> num2;
if (num1 == 0 && num2 == 0) break;
switch (op) {
case '+':
cout << "덧셈 결과는 " << num1 + num2 << "입니다.\n";
break;
case '-':
cout << "뺄셈 결과는 " << num1 - num2 << "입니다.\n";
break;
case '*':
cout << "곱셈 결과는 " << num1 * num2 << "입니다.\n";
break;
case '/':
if (num2 != 0)
cout << "나눗셉 결과는 " << (double)num1 / num2 << "입니다.\n";
else
cout << "0으로 나머지를 구할 수 없습니다. 다시 입력해주세요\n";
break;
default:
cout << "다시 입력하세요\n";
break;
}
}
return 0;
} //C++
메뉴를 가지고 있는 프로그램의 기본 틀
#include <iostream>
using namespace std;
int main() {
int menu;
do {
cout << "\n메뉴\n";
cout << "1:추가\n";
cout << "2:삭제\n";
cout << "3:저장\n";
cout << "4:되돌리기\n";
cout << "원하는 작업을 선택하세요 -> ";
cin >> menu;
} while (!(menu >= 1 && menu <= 4));
cout << menu << "를 선택했습니다.\n";
return 0;
} //C++
무한루프
#include <stdio.h>
int main(void)
{
for (; ;) {
printf("Hi ");
}
return 0;
}
#include <stdio.h>
int main(void)
{
while (1) {
printf("Hi ");
}
return 0;
}
#include <stdio.h>
int main(void)
{
do {
printf("Hi ");
} while (1);
return 0;
}
출처: C++ 프로그래밍 강의 자료
202312005 박성아