정보처리기사 실기 c언어
c언어 --------------------------
예제 -----
-----
#include
void digit(int a[]) {
//void는 "비어 있음" 또는 "아무것도 없음(무형)"을 의미하는 키워드입니다. 주로 함수의 반환값이나 매개변수가 없음을 명시하거나, 데이터 타입이 정해지지 않은 범용 포인터를 선언할 때 사용됩니다.
int temp;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
//71 69 89 91 99
//69 71 89 91 99
}
}
}
}
void main() {
int a[] = {89, 71, 69, 99, 91};
digit(a);
for (int i = 0; i < 5; i++) printf("%d", a[i]);
//6971899199
//끝
}
-----
#include
int factorial (int n);
main() {
int (*pf) (int);
//정수형 인수 한 개를 받는 정수형 함수 포인터 pf를 선언하는 것.
pf = factorial;
//함수의 시작 주소를 함수 포인터 pf에 저장하는 것.
printf("%d", pf(3));
//6
}
int factorial (int n) {
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
//3 * 2 == 6
}
-----
#include
struct jsu {
char nae[12];
int os, db, hab, hhab;
};
int main() {
struct jsu st[3] = { {"데이터1", 95, 88}, {"데이터2", 84, 91}, {"데이터3", 86, 75}};
struct jsu* p;
p = &st[0];
(p + 1)->hab = (p + 1)->os + (p+2)->db;
//84 + 75 == 159
(p + 1)->hhab = (p + 1)->hab + p->os + p->db;
//159 + 95 + 88 == 342
printf("%d", (p + 1)->hab + (p + 1)->hhab);
//159 + 342 == 501
}
-----
#include
int main()
{
int a = 50;
int *b = &a;
*b = *b + 20;
printf("%d, %d\n", a, *b);
//*b의 값이 a 이므로 a == 50 + 20 == 70
//*b의 값도 70
char *s;
s = "gilbut";
for (int i = 0; i < 6; i += 2) {
printf("%c, ", s[i]);
printf("%c, ", *(s + i));
printf("%s\n", s + i);
//첫번째 for문시에 i == 0, 출력값, g, g, gilbut
//두번째 for문시에 i == 2, 출력값, l, l, lbut
//세번째 for문시에 i == 4, 출력값, u, u, ut
}
}
-----
#include
int Decimal(int base, int exp) {
int i;
int result = 1;
for (i = 0; i < exp; i++) {
//exp == 10
result *= base;
//2를 10번 곱하면 됨.
}
return result;
}
void main() {
printf("%d", Decimal(2, 10));
//2, 4, 8, 16, 32, 64, 128, 256, 512, 1024
}
------
#include
struct student {
int a, b;
};
int main() {
struct student s[2];
int i = 0;
for (i; i < 2; i++) {
s[i].a = i;
//0, 1
s[i].b = i + 5;
//5, 6
}
//i == 2
while (i) {
i--;
printf("%d\n", s[i].a + s[i].b);
//i--로 인해서, 1이 되고, 1 + 6 == 7
//i--로 인해서, 0이 되고, 0 + 5 == 5
}
return 0;
}
------
#include
struct Student {
char name[20];
int ca, ds, sum, avr;
};
void main() {
struct Student s[3] = {{"강아지", 90, 90},{"고양이", 100, 90}, {"병아리", 80, 80}};
struct Student* p;
int i = 0;
p = &s[0];
for (i = 0; i < 3; i++) {
(p + i)->sum = (p + i)->ca + (p + i)->ds;
//i == 1 ===> 190
(p + i)->avr = (p + i)->sum / 2;
//i == 2 ===> 80
}
printf("%d", (p + 1)->sum + (p + 2)->avr);
//270
}
------
#include
struct STUDENT {
char check;
//1바이트
double score;
//8바이트
int math;
//4바이트
};
int main(void)
{
int a = 7;
struct STUDENT form;
printf("%d", sizeof(struct STUDENT));
printf("%d", sizeof(form));
printf("%d", sizeof(a));
//결과값 24244
return 0;
}
/*
C언어에서 구조체 크기가 24바이트로 출력되는 이유는 구조체 정렬(Structure Alignment)과 패딩(Padding) 바이트 때문입니다.각 멤버의 크기를 단순히 더하면 13바이트(1 + 8 + 4)이지만, 컴퓨터가 메모리에 접근할 때 효율성을 높이기 위해 데이터 사이에 빈 공간(패딩)을 집어넣습니다.🔍 24바이트가 되는 이유 분석구조체 멤버 중 가장 큰 데이터 타입은 double(8바이트)입니다. 따라서 컴파일러는 모든 멤버를 8바이트 단위(블록)로 정렬합니다.char check (1바이트)1바이트를 차지하고 나머지 7바이트는 패딩(빈 공간)으로 채워져 총 8바이트 블록을 만듭니다.double score (8바이트)이미 8바이트 크기이므로 패딩 없이 딱 맞게 다음 8바이트 블록을 차지합니다.int math (4바이트)참고: 질문에 8바이트로 적어주셨지만, 일반적인 64비트 환경에서 int는 4바이트입니다.4바이트를 차지하고 나머지 4바이트는 패딩으로 채워져 마지막 8바이트 블록을 완성합니다.결과 구조: [1 + 패딩7] + [8] + [4 + 패딩4] = 총 24바이트sizeof(struct STUDENT)와 sizeof(form) 모두 구조체의 전체 크기를 구하므로 둘 다 24를 출력하여 2424가 됩니다.
*/
------
#include
void main() {
int array[3] = { 3 };
int s = 0;
int i = 0;
array[1] = *(array + 0) + 2;
//[1] == 5
array[2] = *array + 4;
//[2] == 7
for (i = 0; i < 3; i++) {
s = s + array[i];
//s == 3 + 5 + 7 == 15
}
printf("%d", s);
}
------
#include
void main() {
char* p = "GRNWOO";
printf("%s\n", p);
//GRNWOO
printf("%s\n", p + 3);
//WOO
printf("%c\n", *p);
//G
printf("%c\n", *(p + 3));
//W
printf("%c\n", *p + 2);
//I
printf("%d\n", sizeof(p));
//모든 포인터(주소)의 크기가 8바이트로 고정됩니다.
}
------
#include
int f1(); int f2(); int f3();
int main() {
printf("%d\n", f3());
return 0;
//160
}
int f1() {
return 10;
}
int f2() {
return (50 + f1());
//60
}
int f3() {
return (100 + f2());
//160
}
------
#include
int length(char *c);
int main(void)
{
char *c1 = "C language";
char *c2 = "program";
printf("%d", length(c1) + length(c2));
//최종 값은 17
}
int length(char *c) {
int result = 0;
while (*c != '\0') {
//null이 아니라면을 의미?
result++;
c++;
//null값이 나오기까지 c1은 result를 10으로 만들고,
//c2는 result를 7로 만듦
}
return result;
}
------
#include
int main(void)
{
int *p[3];
int h = 12, m = 60, s = 59;
p[0] = &h; //12
p[1] = &m; //60
p[2] = &s; //59
printf("%d\n", *p[1] + **p+1);
//60 + 12 + 1 = 73
}
------
#include
int main(void)
{
char data[5] = {'f', 'i', 'g', 'h', 't'};
char* p1 = data;
char* p2 = data;
char first, second;
first = *++p1;
//f에서 i로 됨
second = ++*p2;
//f값 자체에 1을 더해서 g가 됨.
printf("%c%c", first, second);
//출력값 : ig
}
------
#include
int main(void)
{
short digit;
short *ptr;
ptr = &digit;
*ptr = 255;
printf("%d(%04x)", digit, digit);
/*
(%04x)는 정수를 4자리 16진수로 출력하되, 빈자리를 0으로 채우는 서식 지정자입니다.x: 16진수(Hexadecimal)로 출력합니다. (예: 15는 f)4: 출력할 자릿수를 최소 4자리로 지정합니다. 값이 4자리보다 짧으면 앞의 남는 공간을 공백으로 채웁니다.0: 빈자리를 공백 대신 0으로 채우도록 지시합니다.동작 예시 (printf("%04x", 변수); 기준)변수 값이 10인 경우 (16진수 a): 000a변수 값이 255인 경우 (16진수 ff): 00ff변수 값이 4096인 경우 (16진수 1000): 1000
*/
//따라서 출력값은 255(00ff)
}
-----
#include
int main()
{
int array[][4] = {{1,}, {2, 3}, 4, 5, 6, 7, 8, 9, 10};
/*
1행: [1][0][0][0]2행: [2][3][0][0]3행: [4][5][6][7]4행: [8][9][10][0]의 모양으로 배열이 생성됨.
*/
for (int i = 0; i < 4; i++)
printf("%d\n", *(*(array + i) + 2));
//가로로 2칸 더 이동하니,
/*
0
0
6
10
로 출력됨.
*/
}
------
#include
int cnt = 0;
int f1(int);
int main()
{
int k;
f1(5);
printf("%d", cnt);
}
int f1(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
cnt++;
return 1;
}
return(f1(n - 1) + f1(n - 2));
/*
return값에 함수가 들어가면 재귀함수로
f(5) -> f(4) + f(3)
f(4) + f(3) -> f(3) + f(2) + f(2) + f(1)
f(3) + f(2) + f(2) + f(1) -> f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1)
f(2) + f(1) + f(1) + f(0) + f(1) + f(0) + f(1) -> f(1)이 5개
따라서 5가 return 됨.
*/
}
------
#include
int str_cmp(const char* s1, const char* s2, int c) {
//const는 변수의 값을 변경하지 못하도록 상수화(Constant) 시키는 키워드입니다.
if (!c)
//c가 0일 때만 유효함.
return 0;
while(--c && *s1 && *s1 == *s2) {
//*s1만 있는거는 null 문자인지 아닌지 판단하는 거
printf("*");
s1++;
s2++;
//abc까지만 같으므로, *** 출력됨.
}
return *s1 - *s2;
//0이 아니므로
}
int main() {
int result = str_cmp("abcd", "abcD", 10);
switch (result) {
case 0 :
printf("equal");
break;
default :
printf("difference");
break;
//이거 출력됨.
}
return 0;
}
-------
#include
int main()
{
int score[] = {86, 53, 95, 76, 61};
char grade;
char str[] = "Rank";
for (int i = 0; i < 5; i++) {
switch (score[i] / 10) {
case 10:
case 9:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
default:
grade = 'F';
}
if (grade != 'F')
printf("%d is %c %s\n", i + 1, grade, str);
//[0] -> 1 is B Rank
//[1] -> F
//[2] -> 3 is A Rank
//[3] -> 4 is C Rank
//[4] -> F
-----
#include
int main()
{
int a = 5, b = 1, c = 0;
if (!c) {
int b = 5;
//b == 5
//int b를 if문 내에서 선언을 따로 했으므로, 최종 출력값에 b 값에 영향을 미치지 않습니다.
while(b) {
c += b;
b--;
//b가 4 3 2 1 0 순으로 작아지다가, 0이 된 이후에는 while문이 안돌아감.
}
//c는 4 + 3 + 2 + 1이므로 15입니다.
a = c - b;
}
printf("%d %d %d", a, b, c);
return 0;
}
//출력값 15 1 15
-----
#include
int sub(int a, int b) {
return (a + b);
}
int main() {
int (*p) (int, int);
//int (*p) (int, int);는 "정수형(int) 매개변수 2개를 받고, 정수형(int) 값을 반환하는 함수의 주소"를 담기 위한 함수 포인터 선언입니다.
p = sub;
//함수 이름 자체가 주소라서, &sub라고 안써도 괜찮음.
int c = p(2, 3);
printf("%d\n", c);
//최종 출력값에 5
return 0;
}
-----
#include
int result = 10;
int mul(int a, int b) {
int result;
result = a + b;
return result;
}
void main()
{
mul(5, 6);
printf("%d", result);
}
//지역변수와 전역변수로 인해서, 11이
//값으로 안나오고, 10이 결과값
//아래와 같이 바꾸면 값이 11나옴.
#include
int result = 10;
int mul(int a, int b) {
int result;
result = a + b;
return result;
}
void main()
{
//
result = mul(5, 6);
printf("%d", result);
}
-----
#include
int main(int argc, char *argv[])
/*
int argc (Argument Count)프로그램에 전달된 인자의 총 개수를 나타내는 정수입니다.프로그램의 이름도 인자에 포함되므로, 인자를 아무것도 넘기지 않고 실행해도 argc는 기본적으로 1이 됩니다.char *argv[] (Argument Vector)전달된 실제 인자들의 문자열 배열입니다.argv[0]에는 항상 실행하는 프로그램의 이름이나 경로가 들어갑니다.argv[1]부터 argv[argc - 1]까지는 사용자가 프로그램 실행 시 공백으로 구분하여 입력한 문자열들이 차례대로 저장됩니다.
프로그램 실행 시 외부 인자(명령행 인수)를 전달받을 필요가 없다면 int argc, char *argv[]를 생략하고 int main(void) 형태로 작성해도 됩니다.C언어 표준은 매개변수가 없는 main() 형태를 허용하며, 인자가 불필요한 단순 프로그램에서는 생략하는 것이 코드를 더 간결하게 만듭니다.
*/
{
int a = 6;
int s = 0;
int sum = 0;
while (a < 10) {
a++;
/*
a++한 후에 값이
7
8
9
10이 된다.*/
if (a % 2 == 0) continue;
sum += a;
//sum은 16이 된다.
}
switch (a % 2) {
case 2: s++;
case 3: a += s;
default: a++;
}
printf("%d %d", s, a);
//최종 결과값은 0 11 입니다.
return;
}
-----
#####
#include
int sub(int a, int b) {
return (a + b);
}
int main() {
//아래 줄은 원래 빈칸입니다.
int (*p)(int, int);
p = sub;
int c = p(2, 3);
printf("%d\n", c);
return 0;
}
//출력값 5
------
#include
int main()
{
char* str[] = {"Babo", "Train", "Pasta"};
char** q;
q = str;
printf("%c\n", **q);
//B
printf("%c\n", *(*(q + 1)));
//T [1]번 인덱스인 Train의 첫번째 글자
printf("%c\n", *(*(q + 2) + 2));
//s [2]번 인덱스인 Pasta의 첫번째 글자에서 부터 2칸 뒤
}
-----
자바 예제 보고 만든거
#include
int main()
{
int a[8];
int i = 0, n = 10;
while(n > 0){
a[i++] = n % 2;
n /= 2;
}
for(i = 7; i >= 0; i--){
printf("%d", a[i]);
}
}
----------------
문제 풀었음.
#include
int main()
{
char *p = "KOREA";
printf("%s\n", p);
printf("%s\n", p+3);
printf("%c\n", *p);
printf("%c\n", *(p+3));
printf("%c\n", *p+2);
}
출력 결과
KOREA
EA
K
E
M
------
문제 풀었음/
#include
int r1(){
return 4;
}
int r10(){
return(30+r1());
}
int r100(){
return(200+r10());
}
int main(){
printf("%d", r100());
return 0;
}
답은 234
--------
문제 풀었음.
#include
int main()
{
int i, c = 0;
while(i < 10) {
i++;
c *= i;
}
printf("%d", c);
}
해설
#include
int main()
{
int i, c = 0;
while(i < 10) {
i++;
1
c *= i;
c = 0 * 1
i => 2
c => 0 * 2
이런식으로 c => 0 * 10 -> c == 0
}
printf("%d", c);
}
답은 0
------
문제 풀었음.
#include
#define SIZE 5
int main(void)
{
int arr[SIZE] = {75, 100, 95, 50, 85};
int i, j, temp;
for(i = 1; i < SIZE; i++){
for(j = 0; j < SIZE - i; j++){
if(arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (i = 1; i < SIZE; i++) {
printf("%d", arr[i]);
}
}
->
i = 1
j = 0; j < 4; j++
0 1 2 3 뒤에꺼랑 비교해서
75 95 50 85 100 만들기
i = 2
j = 0; j < 3; j++
0 1 2 뒤에꺼랑 비교해서
75 50 85 95 100 만들기
i = 3
j = 0; j < 2; j++
0 1 뒤에꺼랑 비교해서
50 75 85 95 100 만들기
i = 4
j = 0; j < 1; j++
0 뒤에꺼랑 비교해서
50 75 85 95 100 만들기
최종 출력 50 75 85 95 100
------
쉼표 연산자
C언어에서 쉼표(comma, ,) 연산자는
하나의 문장이 필요한 위치에 여러 개의 표현식(expression)을 순차적으로 실행하기 위해 사용합니다. 왼쪽 식부터 차례대로 계산하고 최종적으로 가장 오른쪽 식의
결과값을 전체의 값으로 반환하는 특성을 활용해, 주로 반복문(for)이나 함수 호출 등에서 코드를 간결하게 줄일 때 사용됩니다.
예제
#include
int main() {
int c = 10, b = 20, d = 30;
int r;
r = (c++, ++b, d++);
printf("r: %d\n", r); // r = 30 (d의 이전 값)
printf("c: %d, b: %d, d: %d\n", c, b, d); // c=11, b=21, d=31
return 0;
}
-----
C++ 생성자 -----
객체 생성시 초기화 작업을 위한 함수. 객체를 생성할 때 자동으로 호출되고 제일 먼저 실행됨. new 연산자를 통해서 갤체를 생성할 때 반드시 호출되고 제일 먼저
실행되는 일종의 메소드.
-----
#define
컴파일 전, 코드 내의 특정 문자열을 정의된 값이나 식(매크로)으로 단순 치환하는 전처리기 지시자입니다.
예시: #define SIZE 5
-----
-----------------------------------------------
#include
int main()
{
struct insa {
char name[10];
int age;
} a [] = {"Kim", 28, "Lee", 38, "Park", 41, "Choi", 30};
struct insa *p;
p = a;
p++;
printf("%s\n", p->name);
printf("%d\n", p->age);
return 0;
}
https://www.youtube.com/watch?v=xK3UlibfjaM&list=PLz95GL3y9Hv0fbwTxWqc3dni3hCA7OXgj&index=11
16번 17분 17초 000000000000000000
구조체 예제 --------------
#include
#include
struct PERSON {
char name[50];
int age;
};
int main() {
struct PERSON p1 = {"김구름", 9};
struct PERSON p2;
strcpy(p2.name, "김구름름");
p2.age = 8;
struct PERSON p3[2] = {
{"김구룸", 7},
{"김름구", 6}
};
printf("이름: %s 나이: %d\n", p1.name, p1.age);
printf("이름: %s 나이: %d\n", p2.name, p2.age);
printf("이름: %s 나이: %d\n", p3[0].name, p3[0].age);
printf("이름: %s 나이: %d\n", p3[1].name, p3[1].age);
}
출력값
이름: 김구름 나이: 9
이름: 김구름름 나이: 8
이름: 김구룸 나이: 7
이름: 김름구 나이: 6
#include
#include
typedef struct PERSO {
//typedef 시에는 구조체 이름 PERSO로 된거 생략 가능
char name[50];
int age;
char address[100];
} PERSON;
int main() {
PERSON p4 = {"김구름", 9, "광주광역시"};
typedef unsigned int KWS;
KWS temp = 1;
printf("%d\n", p4.age);
printf("%u", temp);
return 0;
}
#####
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
inline 1, a
int
long
register
restrict 1, a
return
short
signed
sizeof
static
struct
switch
typedef
typeof
typeof_unqual
union
unsigned
void
volatile
while
_Alignas 2, a
_Alignof 2, a
_Atomic 2, b
_Bool 1, a
_Complex 1, b
_Generic 2, a
_Imaginary 1, b
_Noreturn 2, a
_Static_assert 2, a
_Thread_local
__asm 5
__based 3, 5
__cdecl 5
__declspec 5
__except 5
__fastcall
__finally 5
__inline 5
__int16 5
__int32 5
__int64 5
__int8 5
__leave 5
__restrict
__stdcall 5
__try 5
__typeof__
__typeof_unqual__
dllexport 4
dllimport 4
naked 4
static_assert 6
thread 4
--------------
printf_s
안전성 (printf_s): 버퍼 오버플로우나 포맷 문자열 취약점을 방지하기 위해 더 안전하게 설계된 마이크로소프트(MSVC) 확장 함수입니다. 포맷 문자열이 올바른지 검사하며, 잘못되었을 경우 프로그램을 강제 종료하여 오류를 방지합니다.표준 호환성 (printf): C언어의 전통적인 표준 함수로 모든 C/C++ 컴파일러에서 기본적으로 지원합니다. 반면 printf_s는 주로 Visual Studio 환경에서만 호환됩니다.
-----
삼중자 시퀀스
삼중자 문장 부호 문자
??= #
??( [
??/ \
??) ]
??' ^
??< {
??! |
??> }
??- ~
----------
#include
int main()
{
float a = 1.575E1;
float b = 1.575e1;
printf("%f %f", a, b);
}
결과
15.750000 15.750000
1.575E1의 E (또는 e)는 지수 표기법(Exponential notation)을 의미하며, 밑이 10인 거듭제곱을 나타냅니다.즉, 10^1을 곱하라는 뜻이므로 수학적으로 \(1.575 \times 10^1 = 15.75\)가 됩니다. 이를 코드로 작성할 때의 특징은 다음과 같습니다.값의 저장: 변수 a에는 실수형(floating-point)으로 15.75라는 값이 정확히 저장됩니다.대소문자 구분 없음: E와 e는 완전히 동일하게 취급되므로 1.575e1로 작성해도 결과는 같습니다.소수점과의 관계: 지수 표기법을 사용할 때 소수점은 필수가 아닙니다. 예를 들어 1575E-2로 작성해도 동일한 15.75를 의미합니다.이 표기법은 주로 \(0.0000012\)나 \(123000000\)처럼 자릿수가 매우 크거나 작은 실수를 코드 상에서 간결하고 명확하게 표현할 때 사용됩니다.
-----
10.0F => float
10.0 => double
10.0L => long double
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/limits-on-floating-point-constants?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/c-integer-constants?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/integer-types?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/cpp-integer-limits?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/character-types?view=msvc-170
-----
이스케이프 시퀀스
이스케이프 시퀀스 표현
\a 벨(경고)
\b 백스페이스
\f 폼 피드
\n 줄 바꿈
\r 캐리지 리턴
\t 가로 탭
\v 세로 탭
:\ 작은따옴표
:\ 큰따옴표
\\ 백슬래시
:\ 리터럴 물음표
\ ooo 8진수 표기법의 ASCII 문자
\xhh 16진수 표기법의 ASCII 문자
\xhhhh 이 이스케이프 시퀀스가 와이드 문자 상수 또는 유니코드 문자열 리터럴에 사용되는 경우 16진수 표기법의 유니코드 문자입니다.
예를 들어 WCHAR f = L'\x4e00' 또는 WCHAR b[] = L"The Chinese character for one is \x4e00"로 이름을 지정할 수 있습니다.
------
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/octal-and-hexadecimal-character-specifications?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/directives-to-the-preprocessor?view=msvc-170
-----
#####
https://learn.microsoft.com/ko-kr/cpp/c-language/c-pragmas?view=msvc-170
-----
#####
#include
int main()
{
int var = 0;
double val[MAXVAL];
char find( fileptr ) {};
int count( double f ) {};
}
-----
https://learn.microsoft.com/ko-kr/cpp/c-language/main-function-and-program-execution?view=msvc-170
이거부터 보기 - main 함수 및 프로그램 실행