[정보처리기사] 유튜브 두목넷 정보처리기사 실기를 위한 C 특강(6강 배열)

728x90

CH06 배열

 

1. C언어는

  • 사용자정의 자료형을 제공한다(배열, 구조체)
  • 한번의 선언으로 여러 개의 메모리 공간 확보

 

2. 배열변수의 선언문;

 

배열(array)

  • 같은 자료형의 값을 메모리 공간에 순서적으로 하나의 이름(배열명)으로 모아놓은 것
  • 형식: 자료형 변수명;
              자료형 배열명[갯수];
{
	int a[10];			# 4byte * 10 => 40byte
    	double b[2];			# 8byte * 2 => 16byte
   	char ch[5];			# 1byte * 5 => 5byte

 

2. 배열변수의 대입문;

 

배열의 초기화

  • 배열 요소의 범위: 배열명[0] ~ 배열명[첨자-1]
  • 배열의 첨자(index): 0부터 시작
  • 배열 선언과 동시에 초기화시, 요소의 개수 생략가능
{
	int a[3] = {1, 2, 3;				# 정수상수들
    	double b[2] = {1.1, 2.2};		# 실수상수들			
   	char ch[4] = {'P', 'A', 'S', 'S';	# '문자'상수들

 

3. 1차원 배열

 

# 예제 1

#include <stdio.h>
void main()
{
	int pill[5];
    float avg;
    int i;
    for(i=0;, i<5;, i++)
    {
    	scanf("%d", &pill[i]):
    }
    avg = (pill[0] + pill[1] + pill[2] + pill[3] + pill[4]) / 5.0
    printf("정보처리 필기 평균점수: %.2f점", avg);

 

# 예제 2

#include <stdio.h>
void main()
{
	int pill[5];
    float avg;
    int i;
    total = 0;	# 누적 총계
    for(i=0;, i<5;, i++)
    {
    	scanf("%d", &pill[i]);
        tottal += pill[i];
    }
    avg = total / 5.0
    printf("정보처리 필기 평균점수: %.2f점", avg);

 

문자배열 vs 문자열배열

 

# 문자배열 예시

#include <stdio.h>
void main()
{
	int i;
    char
    ch[4] = {'P', 'A', 'S', 'S'};
    for(i=0;, i<4; i++)
    {
    	printf("%c", ch[i]);
    }
    printf("\n");
}
ch[0] ch[1] ch[2] ch[3]
P A S S

 

# 문자열 배열 예시

#include <stdio.h>
void main()
{
	int i;
    char	ch[4] = ('P', 'A', 'S', 'S'};
    char	str[5] = {"PASS"};
    
    printf("문자배열의 크기: %d바이트, sizeof(ch));	# 4byte
    pirntf("문자열배열의 크기: %d바이트, sizeof(str));	# 5byte
}
ch[0] ch[1] ch[2] ch[3]
P A S S
str[0] str[1] str[2] str[3] str[4]
P A S S \0
  • 문자열상수의 마지막 널문자(\0) 포함

 

 

728x90