1 / 64

제 6 장 배열과 문자열

제 6 장 배열과 문자열. 문봉근. 제 6 장 배열과 문자열. 6.1 배열의 표현과 선언 6.2 1 차원 배열 6.3 다차원 배열 6.4 문자배열 ( 문자열 ) 6.5 배열 크기 정의 6.6 배열과 함수. 6.1 배열의 표현과 선언. 종류가 같은 데이터를 여러 개 선언 데이터 형이 같은 많은 양의 데이터를 처리하고자 할 때 사용 다른 변수들과 마찬가지로 반드시 먼저 선언이 되어야 한다. 6.1.1 배열의 표현.

habib
Download Presentation

제 6 장 배열과 문자열

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 제6장 배열과 문자열 문봉근

  2. 제6장 배열과 문자열 6.1 배열의 표현과 선언 6.2 1차원 배열 6.3 다차원 배열 6.4 문자배열(문자열) 6.5 배열 크기 정의 6.6 배열과 함수

  3. 6.1 배열의 표현과 선언 • 종류가 같은 데이터를 여러 개 선언 • 데이터 형이 같은 많은 양의 데이터를 처리하고자 할 때 사용 • 다른 변수들과 마찬가지로 반드시 먼저 선언이 되어야 한다.

  4. 6.1.1 배열의 표현 • 배열은 여러 개의 데이터를 일련의 장소에 저장하므로 첨자(index)로 구별한다. • 첨자를 나타내기 위해서 [](대괄호, square bracket)을 사용한다. • Ex : int names[4]; // 4개의 데이터를 가지는 배열선언. names[0] = 101; // 첫 번째 요소 names[1] = 232; // 두 번째 요소 names[2] = 231; // 세 번째 요소 names[3] = 0; // 네 번째 요소

  5. 예제 6.1 배열의 각 요소에 하나씩 문자 넣기 • #include <stdio.h> • void main(void) • { • char word[20]; • word[0] = 'H'; • word[1] = 'e'; • word[2] = 'l'; • word[3] = 'l'; • word[4] = 'o'; • word[5] = ‘\0’; /* 문자배열의 끝을 표시 */ • printf("word[]에 담겨진 내용은 -->%s\n", word ); • } • 실행결과 • word[]에 담겨진 내용은  Hello

  6. 6.1.2 배열의 선언 • 배열의 선언(문법) • 데이터형 배열명[요소의 개수]; • data_type array_name[index]; • data_type : 배열의 데이터 형 • 기본 데이터형(int, float, char 등) • 사용자 정의 데이터형(구조체, 공용체 등) • array_name : 배열명(변수 정의 규칙에 따름) • index : 배열의 요소의 개수

  7. 예제 6.2 기본 배열의 선언을 위한 예제 #include <stdio.h> void main(void) { int numbers[100]; /* 100개의 요소를 가진 정수 배열 선언 */ float averages[20]; /* 20개의 요소를 가진 실수 배열 선언 */ numbers[2] = 10; /* 세 번째 요소에 10을 저장 */ --numbers[2]; /* 저장된 값(10)을 1 감소 */ printf("배열 numbers의 세 번째 요소는 %d이다.", numbers[2]); } 실행결과 배열 numbers의 세 번째 요소는 9이다.

  8. 6.2.1 1차원 배열의 선언 • 1차원 배열은 배열의 index가 1개인 배열을 말한다. • 문법 • 데이터형 배열명[요소의 개수]; • int array[10];

  9. 예제 6.3 array라는 배열을 선언하고, 지정된 요소에 데이터 넣기 • int a[10]; • int a = 3, array[10]; • array[a] = 100; • array[9] = 200; • array[10] = 400; • 설명 • array[10] = 400인 경우 에러 가능성 있음

  10. 예제 6.4 1차원 배열의 초기화 및 선언 예 ⑴ int a[10] = { 10, 30, 50, 70, 100, 40, 30, 55, 223, 765 }; ⑵ int b[] = { 10, 30, 50, 70, 100, 40, 30, 55, 223, 765 }; ⑶ int c[10] = { 10, 30, 50, 70, 100, 40, 30, }; /*숫자 뒤에 콤마가 있다.*/ ⑷ int d[3] = { 1, 10, 5, 7, 8 }; ⑸ char ch[5] = "Test"; ⑹ int numbers[10]; ⑺ static int numbers[10] = { 34, 27, 16 }; ⑻ static int numbers[] = { 2, -3, 45, 79, -14, 5, 9, 28, -1, 0}; ⑼ static char text[] = "Welcome to Korea."; ⑽ static float radix[12] = { 134.362, 1913.248 }; ⑾ double radians[1000];

  11. 예제 6.5 배열 선언시 초기화한 후, 출력하는 프로그램. #include <stdio.h> void main(void) {    int x;    static int  values[] = { 1,2,3,4,5,6,7,8,9 }; static char  word[] ={ 'H','e','l','l','o' };    for( x = 0; x < 9; ++x )       printf("values[%d] = %d\n", x, values[x]);    for( x = 0; x < 5; ++x )       printf("word[%d] = %d\n", x, word[x]); }

  12. 예제 6.6 1차원 배열을 이용한 합계계산 프로그램 #include <stdio.h> void main(void) {    int i, data[] = {78,55,99,75,84,39,67,98,87,100};    /*배열 선언*/    long int sum = 0;   /* 초기 값을 0으로 둔다. */    float ave;    for (i = 0; i < 10; i++)         sum += data[i];    ave = (float)sum / 10.0;  printf("Total = %ld  Average = %.2f\n", sum, ave); }

  13. 예제 6.7 년, 월, 일을 입력하여 1월 1일부터 입력한 날짜까지의 전체일수를 계산하는 프로그램 • #include <stdio.h> • void main(void) • { • int year, month , day; • int days; /*전체 날수를 기억 */ • int ia[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; • printf("년도를 입력하시오 : ");scanf("%d",&year); • printf("월을 입력하시오 : ");scanf("%d",&month); • printf("일을 입력하시오 : ");scanf("%d",&day); • if(day > 31) { • printf("에러 : 일이 잘못 입력되었습니다.\n"); • return; • } • else if(month==4 && month==6 && month==9 && month==11 && day>30 ) { • printf("에러 : 일이 잘못 입력되었습니다.\n"); • return; • }

  14. 예제 6.7(계속) • else if(month == 2) { • if(year%400==0 || (year%4==0 && year%100 !=0)) { • if( day > 29 ) { • printf("에러 : 일이 잘못 입력되었습니다.\n"); • return; • } • } • else { • if( day > 28 ) { • printf("에러 : 일이 잘못 입력되었습니다.\n"); • return; • } • } • } • if (month >= 1 && month <= 12) { • days = ia[month-1] + day; /*날수를 계산 */ • if (month>2 && (year%400==0 || (year%4==0 && year%100 !=0))) • ++days; /*윤년이고 3월 이후면 하루를 증가 */ • printf("%d년 %d월 %d일은 %d번째 날입니다.\n", • year, month, day, days); • } • else • printf("에러 : 월이 잘못 입력되었습니다!\n"); • }

  15. 예제 6.8 입력된 수들의~ • #include <stdio.h> • void main(void) • { • int ia[10] = { 0, }; /*초기 값이 모두 0 */ • int i; • printf("0에서 99사이의 값들을 입력하시오. 그 이외의 값이면 종료.\n"); • scanf("%d",&i); • while (i >= 0 && i <= 99) { • ++ia[i / 10]; • scanf("%d",&i); • } • printf("\n발생 빈도수\n"); • for (i = 0; i < 10; i++) • printf("%2d ~ %2d : %3d\n",i*10,(i+1)*10-1,ia[i]); • }

  16. 예제 6.9 N개의 정수를 읽어 들여 오름차순으로 정렬하는 프로그램. 미리 100개의 배열을 잡아두고 입력할 데이터의 개수를 받아들인 후 계산한다. /* N은 100을 넘지 않는다*/ #include <stdio.h> void main(void) {        static int data[100];        int i, j, N;        printf("입력할 데이터의 개수를 입력하시오 : ");        scanf("%d",&N);        for (i = 0; i < N; i++) /*  배열의 입력  */               scanf("%d",&data[i]);

  17. 예제 6.9 (계속)        for (i = 0; i < N-1; i++)               for (j = i + 1; j < N; j++)                      if (data[i] > data[j]) { /*XOR를 이용한 데이터 교환*/                             data[i] ^= data[j];                             data[j] ^= data[i];                             data[i] ^= data[j];                      }        printf("정렬된 데이터 :\n");        for (i = 0; i <= N - 1; i++) {      /*  정렬된 배열을 출력 */               printf("%10d",data[i]);               if ((i + 1) % 7 == 0)                      printf("\n");        } }

  18. 예제 6.10 데이터를 읽어 그 중 가장 긴 라인의 길이와 그 라인 전체를 출력하는 프로그램 • #include <stdio.h> • char data[250]; • void main(void) • { • char mdata[250]; /* 지금까지 읽은 라인 중 가장 긴 라인을 기억시킬 배열*/ • int max = 0; • int l, i; • while (1) {/*한 줄을 읽음 */ • l=0; • while(1) { • data[l] = getchar(); • if(data[l] == '\n' || data[l] == EOF) break; • l++; • } • if (l > max) {/*이것이 현재 라인 보다 길면 */ • for (i = 0; i <= l - 1; i++) • mdata[i] = data[i]; /*그대로 복사 */ • max = l - 1; • } • if(data[l] == EOF) break; • } • if (max == 0) /*읽어들인 라인이 없으면 */ • printf("데이터가 없습니다.\n"); • else { • printf("가장 긴 줄은 : "); • for (i = 0; i <= max - 1; i++) • putchar(mdata[i]); • printf("\n 길이 : %d\n",max); • } • }

  19. 예제 6.11 10명의~ • #include <stdio.h> • #include <conio.h> • void main(void) • { • int jumsu[10], sum=0, avg=0, i; • for(i=0;i<10;i++) • { • printf("input(jumsu %d )=>",i+1); • scanf("%d",&jumsu[i]); • printf("\n"); • } • for(i=0;i<10;i++) • sum += jumsu[i]; • printf("total = %d , avg = %d\n",sum, sum/i); • }

  20. 예제 6.12 0에서 9까지 제곱의 값을 배열에 기억시켜 출력하는 프로그램을 작성하라. • #include <stdio.h> • #include <conio.h> • void main(void) • { • int i, mul[10]; • printf("제곱의 합 출력 프로그램\n"); • for(i=0;i<10;i++) • mul[i]=i*i; • for(i=0;i<10;i++) • printf("%d * %d = %2d\n“,i,i,mul[i]); • getch(); • }

  21. 6.2.2 1차원 배열의 초기화 ① 데이터 초기값을 선언시에 미리 대입하는 방법 int arr[4]={10,20,30,40};     char ab[3]={'A','B','C'}; ② loop를 이용하여 배열의 모든 값들을 0으로 초기화하는 방법 int array[10];        for(i=0;i<10;i++)               array[i] = 0; ③ 선언된 배열에 사용자가 직접 외부로부터 입력하는 방법 int a[10];        for(i=0;i<10;i++){               printf("\n input a[%d] = ", i);               scanf("%d",&a[i]);        }

  22. 예제 6.13 1차원 배열 x[20]을 선언하고, 초기값으로 2의 배수를 저장하는 프로그램 • #include <stdio.h> • void main(void) • { • int x[10], i; • for(i=0;i<10;i++) • x[i]=i*2; • for(i=0;i<10;i++) • printf("x[%d] = %2d\n",i, x[i]); • }

  23. 6.3 다차원 배열 • 다차원 배열(multi dimensional arrays) • 배열의 요소를 지정하는 두 개 이상의 index를 가진다. • int multi[2][3]; 과 같이 선언했을 경우 • 행우선 배열 • 열우선 배열

  24. 6.3.1 다차원 배열의 선언과 계산 • 다차원 배열의 선언 int    m1[10][10]; float  matrix[4][4][4]; static int m2[2][2] = { {0,1}, {2,3} }; sum = m1[i][j] + m2[k][l];

  25. 다차원 배열을 초기화하거나 배열의 첨자를 사용하는 방법 ① 다차원 배열에 초기값을 저장하는 방법 int a[2][3]={10,20,30,40,50,60};     int a[2][3]={{10,20,30},{40,50,60}}; ② 배열을 먼저 선언하고 반복문(for)을 이용하여 배열을 0으로 초기화하는 방법 int array[5][4];     for(i=0;i<5;i++)            for(j=0;j<4;j++)                   rray[i][j] = 0;

  26. ③ 배열을 먼저 선언하고, 이 배열에 외부로부터 입력을 통해서 받아들이는 방법 int a[5][4];     for(i=0;i<5;i++)            for(j=0;j<4;j++){               printf("\n input[%d][%d] :", i, j);               scanf("%d",&a[i][j]);            } ④ 다차원 배열의 내용을 보기 위하여 출력하는 방법 int a[3][4] = { {10,20,30,40}, {50,60,70,80}, {90,100,110,120} };     for(i=0;i<3;i++)        for(j=0;j<4;j++)          printf("a[%d][%d] = %d  ", i, j, a[i][j]);

  27. 예제 6.14다차원 배열의 초기화 ⑴ int ia[2][3] = {{1,2,3}, {4,5,6}}; ⑵ int ia[][3] = {1,2,3,4,5,6}; ⑶ int ia[][] = {1,2,3,4,5,6}; /* 에러 */ ⑷ int ja[2][3][2]  = {{{1,2},{3,4},{5,6}}, {{7,8},{9,10},{11,12}}}; ⑸ int ja[][3][2] = {1,2,3,4,5,6,7,8,9,10, 11,12};

  28. 예제 6.15 3*3 행렬 2개를 읽어 들여 이의 합을 출력하는 프로그램 • #include <stdio.h> • void print_matrix(int M[3][3]) • { • int i, j; • for (i = 0; i < 3; i++) { • for (j = 0; j < 3; j++) • printf("%d ",M[i][j]); • printf("\n"); • } • } • void read_matrix(int M[3][3]) /* 3*3 행렬을 읽어 들이는 함수 */ • { • int i, j; • for (i = 0; i < 3; i++) • for (j = 0; j < 3; j++) • scanf("%d",&M[i][j]); • }

  29. 예제 6.15 3*3 행렬 2개를 읽어 들여 이의 합을 출력하는 프로그램(계속) • void main(void) • { • int A[3][3], B[3][3], C[3][3]; • int i, j; • printf("*** Input the first matrix(3*3) ***\n"); • /* read matrix A */ • for (i = 0; i < 3; i++) • for (j = 0; j < 3; j++) • scanf("%d",&A[i][j]); • /* printf matrix A : 함수로 했을 경우 배열의 이름을 인자로 전달한다 */ • printf("\t## A ##\n"); • for (i = 0; i < 3; i++) { • for (j = 0; j < 3; j++) • printf("%d ",A[i][j]); • printf("\n"); • }

  30. 예제 6.15 3*3 행렬 2개를 읽어 들여 이의 합을 출력하는 프로그램(계속) • printf("*** Input the second matrix(3*3) ***\n"); • /* read matrix B */ • for (i = 0; i < 3; i++) • for (j = 0; j < 3; j++) • scanf("%d",&B[i][j]); • /* printf matrix B : 함수로 했을 경우 배열의 이름을 인자로 전달한다 */ • printf("\t## B ##\n"); • for (i = 0; i < 3; i++) { • for (j = 0; j < 3; j++) • printf("%d ",B[i][j]); • printf("\n"); • } • for (i = 0; i < 3; i++) • for (j = 0; j < 3; j++) • C[i][j] = A[i][j] + B[i][j]; • printf("\n*** C = A + B ***\n"); • /* printf matrix C : 함수로 했을 경우 배열의 이름을 인자로 전달한다 */ • printf("\t## C ##\n"); • for (i = 0; i < 3; i++) { • for (j = 0; j < 3; j++) • printf("%2d ",C[i][j]); • printf("\n"); • } • }

  31. 예제 6.16 2차원 배열의 초기화하는 예제 • #include <stdio.h> • void main(void) • { • int array[4][3] = {{100, },{0, } ,{111, 222}, }; • int i, j; • for(i = 0; i < 4; i++) • { • for(j = 0; j < 3; j++) • printf("array[%d][%d] = %d\n", i, j, array[i][j]); • putchar('\n'); • } • }

  32. 예제 6.17 2차원 배열의 초기화 및 행의 크기가 지정되지 않은 배열에서 행의 크기를 계산하는 프로그램 #include <stdio.h> void main(void) {        int A[ ][3] = {{100,200,0},{0,}, {111,0,0}, {0,}};        int i, j, size;        size = sizeof(A)/sizeof(int)/3;        for(i = 0; i < size; i++)        {           for(j=0; j<3; j++) printf("A[%d][%d] = %d\n", i, j, A[i][j]);               putchar('\n');        } }

  33. 예제 6.18 행과 열의~ • /* 2차원 배열 array[3][5]의 각 행의 합과 전체 합을 계산하는 프로그램 */ • #include <stdio.h> • #define ROW 3 • #define COLUMN 5 • void main(void) • { • int array[ROW][COLUMN]; • int i, j; • long temp, total = 0;

  34. 예제 6.18 행과 열의~(계속) • for(i = 0; i < ROW; i++) • { • temp = 0; • for(j = 0; j < COLUMN; j++) • { • printf("Input data in array[%d][%d] : ", i, j); • scanf("%d", &array[i][j]); • temp += array[i][j]; • } • switch( i ) /* 각 행의 합을 출력 */ • { • case 0: printf("\narray[%d] = %ld\n\n", i, temp); • break; • case 1: printf("\narray[%d] = %ld\n\n", i, temp); • break; • case 2: printf("\narray[%d] = %ld\n\n", i, temp); • } /* end of switch */ • total += temp; • } /* end of for statement */ • printf("The total of array is %ld \n", total); • }

  35. 예제 6.19 주어진 2차원 배열에서, 모든 요소들의 합을 계산하고, total을 출력하는 프로그램을 작성하라. #include <stdio.h> void main(void) {        static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} };        int row, column, sum;        sum = 0;        for( row = 0; row < 4; row++ )          for( column = 0; column < 3; column++ )                 sum = sum + m[row][column];         printf("The total is %d\n", sum ); } 실행결과 The total is 82

  36. 6.4.1 문자배열 • 문자열을 처리하는 방법 • 문자배열(character arrays)을 사용하는 방법 • 포인터를 사용하는 방법

  37. (1) 문자열 상수 • 문자열 상수는 “…”로 문자열을 묶어 주기만 하면 된다. 주 소0x01 0x02 0x03 0x04 0x05 0x06 0x07 ASCII코드0x53 0x74 0x72 0x69 0x6E 0x67 0x00 문 자S t r i n g (NULL) (주소는 임의로 정한 주소임) • 문자열의 마지막에는 NULL 문자열이 들어간다.

  38. (2) 문자열 변수 • C에서는 문자열 데이터형이 없으므로 문자 배열을 사용하여 문자열 처리를 한다. • 문자배열 • char 배열이름[문자열길이+1] = “초기문자열”; • 문법 • 배열이름[첨자] = 값 • 변수 = 배열이름[첨자]

  39. 문자열을 복사할 때는 strcpy함수를 이용하여야 하며, 직접 대입할 수 없다. • 직접 대입을 할 경우는 하나씩 배열의 요소에 넣어야 한다. char str[10] = "String"; strcpy(문자배열이름,문자열); strcpy(str,"Welcome!"); str="Hello!"; /*이렇게 사용할 수는 없다. */ str[0]='H';  /* 대입연산자를 사용할 경우는 일일이 이렇게 한 문자씩 대입한다. */ str[1]='e'; str[2]='l'; str[3]='l'; str[4]='o'; str[5]='!'; str[6]=NULL; /* 또는 str[6]='\0'; */

  40. (3) 문자열 상수의 초기화 • const char str[10]="String"; • const char str[]="String";

  41. 예제 6.20 문자열 복사함수를 사용하는 방법과 하나의 배열 요소에 대입하는 방법. /* 파일 이름 : 문자열 처리 프로그램. */ #include <stdio.h> #include <string.h> void main(void) {        char str[10];        strcpy(str,"welcome");        printf("%s\n",str);        str[0]='W';        printf("%s\n",str); } 실행결과 welcome Welcome

  42. (4) 특수 문자 문자 기능 \a Beep음을 컴퓨터 스피커로 출력 \b Back space \n 현재 위치한 줄의 다음 줄로 내려간다. \r 현재 위치한 줄의 맨 처음으로 간다. \t 수평 Tab \v 수직 Tab \\ \(역슬래쉬) \‘ 작은 따옴표 \“ 큰 따옴표 \0 NULL문자 \0?? 8진수 ??에 대한 문자 \x?? 16진수 ??에 대한 문자.

  43. 예제 6.21 특수문자 처리하는 방법. #include <stdio.h> void main(void) {        printf("C Programming\n");        printf("C \bProgramming\n");        printf("\'C\' Programming\n");        printf("\"C Programming\"\n");        printf("C \tProgramming\n");        printf("C \rProgramming\n");        printf("C\n\tProgramming\n");        printf("C Programming\a\n"); }

  44. 표 6.2문자검사 및 변환함수 6.4.2 문자분류 및 문자변환 표준함수

  45. 6.4.2 문자분류 및 문자변환 표준함수(계속)

  46. 예제 6.22 toupper()를 사용하여 문자열을 한번에 한 문자씩 대문자로 변환하는 예제. #include <stdio.h> #include <ctype.h> void main(void) {    char name[80];    int loop;  printf("Enter in a name in lowercase\n");    scanf( "%s", name );    for( loop = 0; name[loop] != 0; loop++ )         name[loop] = toupper( name[loop] );     printf("The name in uppercase is %s", name); }

  47. 예제 6.23 예제 6.22를 strupr함수를 사용하여 한꺼번에 대문자로 바꾸기 #include <stdio.h> #include <ctype.h> void main(void) {    char name[80]; /*declare an array of characters 0-79*/    printf("Enter in a name in lowercase\n");    scanf( "%s", name );    strupr( name );    printf("The name is uppercase is %s\n", name );    strlwr( name );    printf("The name is lowercase is %s\n", name ); }

  48. 표 6.4 보이는 문자(visible graphic character)

  49. 표 6.5 추가 그래픽 문자(Additional graphic characters)

  50. 표 6.6 제어문자(escape sequence)

More Related