1 / 49

6 장 배열과 문자열

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

rory
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장 배열과 문자열 6.1 배열의 표현과 선언 6.2 1차원 배열 6.3 다차원 배열 6.4 문자배열(문자열) 6.5 배열 크기 정의 6.6 배열과 함수

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

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

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

  5. 예제 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]); }

  6. 6.2 1차원 배열의 선언 • 1차원 배열은 배열의 index가 1개인 배열을 말한다.

  7. 6.2.1 1차원 배열의 선언 • 문법 • 데이터형 배열명[요소의 개수]; • 예제 6.3 • int a[10]; /* index는 0~9까지 사용*/

  8. 예제 6.4 ⑴ 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];

  9. 예제 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]); }

  10. 예제 6.61차원 배열을 이용한 합계계산 프로그램 #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); }

  11. 예제 6.9N개의 정수를 읽어들여 오름차순으로 정렬하는 프로그램.미리 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]);

  12. 예제 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");        } }

  13. 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;

  14. ③ 선언된 배열에 사용자가 직접 외부로부터 입력하는 방법 int a[10];        for(i=0;i<10;i++){               printf("\n input a[%d] = ", i);               scanf("%d",&a[i]);        }

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

  16. 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];

  17. 다차원 배열의 초기값 저장 ① 다차원 배열에 초기값을 저장하는 방법 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;

  18. ③ 배열을 먼저 선언하고, 이 배열에 외부로부터 입력을 통해서 받아들이는 방법 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]);

  19. 예제 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};

  20. 예제 6.172차원 배열의 초기화 및 행의 크기가 지정되지 않은 배열에서 행의 크기를 계산하는 프로그램 #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');        } }

  21. 예제 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 ); }

  22. 6.4 문자배열

  23. 6.4.1 문자배열 • 문자열을 처리하는 방법에는 문자배열(character arrays)을 사용하는 방법과 포인터를 사용하는 방법이 있다. • 여기서는 배열을 이용한 방법만을 배우기로 한다.

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

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

  26. 문자열을 복사할 때는 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'; */

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

  28. 예제 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); }

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

  30. 예제 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"); }

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

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

  33. 예제 6.22toupper()를 사용하여 문자열을 한번에 한 문자씩 대문자로 변환하는 예제. #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); }

  34. 예제 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 ); }

  35. 보이는 문자(visible graphic character)

  36. 추가 그래픽 문자(Additional graphic characters)

  37. 제어문자(escape sequence)

  38. 숫자를 이용한 제어 문자(numerical escape sequence)

  39. 예제 6.24문자처리함수를 이용한 프로그램이다. 그 결과를 분석해보자 #include <stdio.h> #include <ctype.h> #include <conio.h> void main(void) {        int c;        printf("\n isalpha : \n");        for(c=0;c<127;c++)               if(isalpha(c))putchar(c);        printf("\n isdigit :\n");        for(c=0;c<127;c++)               if(isdigit(c))putchar(c);        printf("\n islower :\n");

  40. 예제 6.24(계속)        for(c=0;c<127;c++)               if(islower(c))putchar(c);        printf("\n ispunct :\n");        for(c=0;c<127;c++)               if(ispunct(c))putchar(c);        printf("\n isupper :\n");        for(c=0;c<127;c++)               if(isupper(c))putchar(c);        getch(); }

  41. 6.4.3 데이터 변환

  42. 예제 6.25문자열을 숫자 데이터형으로 변환하는 프로그램. 문자열은 계산이 안되지만 숫자로 변환한 후에는 계산이 가능하게 된다. #include <stdio.h> #include <stdlib.h> void main(void) {    char string1[] = "12.434";    char string2[] = "43.534";   char string3[] = "453", string4[] = "985";   /* printf("%s", string1 + string2); 이 부분은 컴파일 시 에러가 난다. 문자열은 덧셈을 할 수 없으며, 어떤 컴파일러에서는 되는 곳도 있다.*/

  43. 예제 6.25(계속)    printf("%f\n", atof(string1) + atof(string2)); /* 실수로 변환이 되었으므로 연산이 가능하다. */    /* printf("%s", string3 + string4); 마찬가지로 에러가 발생한다.*/    printf("%d\n", atoi(string3) + atoi(string4));    /* 정수로 변환이 되었으므로 연산이 가능하다. */ }

  44. 6.4.4 스트림 입출력

  45. 6.4.4 스트림 입출력(계속)

  46. 6.4.5 문자열 처리

  47. 6.4.5 문자열 처리(계속)

  48. 예제 6.28문자열 처리 함수를 이용한 프로그램이다. #include <stdio.h> #include <conio.h> #include <string.h> void main(void) {    char a[30],b[30],pass[10],s1[15],s2[15]; printf("/*strcat()=string1+string 2 */\n\n");    printf("input string 1:"); gets(a);    printf("input string 2:"); gets(b);    printf("\n\n string1 + string2 = %s \n", strcat(a,b));    printf("\n\n/* strcmp() = compare string1 with string2 */ \n");    printf("\n\nif your password is....h6614 \n");

  49. 예제 6.28(계속)    do{       printf("Your Password : "); gets(pass);       if(strcmp(pass,"h6614"))            printf("invalid password\n");       else            break;    } while(1);    printf("\n O.K");    getch();   printf("\n/*strcpy(s1,s2)=Copy s2 to s1*/ \n");    printf("input string s2 :"); gets(s2);    strcpy(s1,s2);    printf("s1 = %s\n",s1);    getch(); }

More Related