1. 배열의  개념 : 자료형이 같은 여러개의 값을 연속된 기억장소에 같은 이름(배열명)으로 저장한것 주로 동일한 구조의 많은 자료등을 다룰때 사용한다.


변수는 하나의 자료를 저장하지만 배열은 여러개의 자료를 저장한다 즉 여러 변수의 모임이라고 볼수있다.


2. 배열 선언 및 주의사항 : 배열을 선언할때에 배열의 크기(배열 원소수)에는 정수형 상수만 가능하고 변수는 불가능하다.


3. 배열의 초기화 : 배열의 크기를 지정하고 초기값이 부족하다면 초깃값은 자동으로 0으로 지정된다. 배열 원소수를 명시 않으면 중괄호{} 안의 값 개수가 원소수로 결정된다.


4. 예제1 - 5명의 퀴즈점수를 배열에 저장한 후 평균 출력하기 프로그램


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

/*

//배열선언 예

//1. 1000명의 나이를 저장하는 배열

int age[1000];

//2. 5명의 퀴즈점수를 저장하는 배열

int quiz[5];

//3. 100명의 평균을 저장하는 배열

double avg[100];

//4. 학생의 이름(홍길동)을 저장하는 배열

char name[10];  

*/


//배열 예제1. 5명의 퀴즈점수를 입력

int quiz[SIZE], i, count;

int sum=0;

double avg;


for(i=0;i<SIZE;i++)

{

printf("퀴즈점수 입력 : ");

scanf("%d", &quiz[i]);

sum+=quiz[i]; //sum=sum+quiz[i];

avg = (double)sum / SIZE;

//입력한 점수의 합을 출력

printf("입력한 %d명의 합 : %d\n", SIZE, sum);

printf("입력한 %d명의 평균 : %.1lf\n", SIZE, avg);

//평균미만인 수

for(i=0;i<SIZE;i++)

{

if(quiz[i] < avg)

count++;

}

//결과출력

printf("===========================\n");

printf(" 번호 점수 평균과의 차이 \n"); 

printf("===========================\n");

for(i=0;i<SIZE;i++)

printf(" %2d     %2d      %5.1lf\n", i+1, quiz[i], quiz[i]-avg);

printf("===========================\n");

printf(" 평균 : %.1lf 점 \n", avg);

printf("===========================\n");

printf(" 평균미만 : %d명 \n", count);

return 0;

}




5. 예제 2 - 배열의 원소에서 최소값, 최대값 구하기


#include <stdio.h>

#include <stdlib.h>

#define N 5

/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int i;

int min, max; //1. min 변수 지정 

int f[N]={3,0,-30,-20,-1};

for(i=0;i<N;i++)

{

printf("%d ", f[i]);

}

printf("\n");

//최소값 찾기

//2.첫번째 원소를 min변수에 저장

min = f[0];

for (i=1;i<N;i++)

{

if(f[i]<min) //3. 각 원소를 min변수와 비교 및 교체작업 

min = f[i];

//최소값 출력

printf("\n\n 최소값은 %d \n", min); 

//최대값 찾기

max = f[0];

for(i=1;i<N;i++)

{

if(f[i]>max)

max = f[i]; 

//최대값 출력

printf("\n\n 최대값은 %d \n", max); 

 

return 0;

}



7. 예제4 - 배열의 원소를 오름차순 정렬 소스코드, 실행결과

             (주석: 오름차순의 개념정리, 버블정렬, 개선된 버블정렬의 원리 및 차이점)


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a[SIZE] = {5,4,3,2,1};

int repeat, i, temp;

FILE *fp;


printf("정렬 전 배열 : ");

for(i=0;i<SIZE;i++)

printf("%4d",a[i]);

printf("\n");

// 버블 정렬 시작 : 오름차순정렬 

for(repeat=1;repeat<SIZE;repeat++) // (배열 원소수-1)번 반복하기 

{

//배열의 이웃한 두 원소간의 정렬을 차례대로 반복하기 

for(i=0;i<SIZE-repeat;i++) //(i가 0부터 3까지 순서를 반복) 

{ //SIZE-repeat 개선된 이유 : 이미 정렬이 끝난 부분의 비교를 제거하여 실행속도가 빨라짐. 

if(a[i]>a[i+1])

{

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;//이웃하는 두원소 교환 

}

} //안쪽 for의 끝 

} // 바깥쪽 for의 끝 

  for(i=0;i<SIZE;i++)

printf("%4d", a[i]);

//배열원소 출력 

fp=fopen("asc.txt","w");

        for(i=0;i<SIZE;i++)

fprintf(fp, "오름차순 정렬 : %2d",a[i]);

fclose(fp);

return 0;

}





8. 예제5 - 배열의 원소를 내림차순 정렬 소스코드, 실행결과           

             (주석:  내림차순 개념정리)


#include <stdio.h>

#include <stdlib.h>

#define SIZE 5


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a[SIZE] = {1,2,3,4,5};

int repeat, i, temp;


printf("정렬 전 배열 : ");

for(i=0;i<SIZE;i++)

printf("%4d",a[i]);

printf("\n");

// 버블 정렬 시작 : 내림차순정렬 

for(repeat=1;repeat<SIZE;repeat++) // (배열 원소수-1)번 반복하기 

{

//배열의 이웃한 두 원소간의 정렬을 차례대로 반복하기 

for(i=0;i<SIZE-repeat;i++) //(i가 0부터 3까지 순서를 반복) 

{ //SIZE-repeat 개선된 이유 : 이미 정렬이 끝난 부분의 비교를 제거하여 실행속도가 빨라짐. 

if(a[i]<a[i+1])

{

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;//이웃하는 두원소 교환 

}

} //안쪽 for의 끝 

} // 바깥쪽 for의 끝 

  for(i=0;i<SIZE;i++)

printf("%4d", a[i]);

//배열원소 출력 

return 0;

}




'basic > C' 카테고리의 다른 글

7. 포인터  (0) 2016.11.10
6. 함수  (0) 2016.10.31
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22
2. C프로그래밍의 기초문법  (0) 2016.09.08

1. 조건문 - if문


1.1 형식1 예제(소스코드, 실행결과)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int score;

printf("점수입력 : ");

scanf("%d", &score);

//if문 형식1 예제

if(score>=80)

{

printf("점수는 %d, 결과는 ", score);

printf("합격"); 

}

return 0;

}



*텍스트 파일 생성


예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int age;

FILE *fp; //1. FILE포인터 선언

 

printf("나이입력 : ");

scanf("%d", &age);

fp=fopen("age.txt", "w"); //2. 생성할 FILE open

fprintf(fp, "나이 : %d",age);//3. file에 내용 쓰기 : fprintf() 

fclose(fp);//4. file 닫기 : fclose() 


return 0;

}



1.2 형식2 예제(소스코드, 실행결과)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

//if문 형식2

int score;

printf("점수 입력 : ");

scanf("%d", &score); 

if(score>=80)

{

printf("점수는 %d이고, ",score);

printf("합격입니다.\n");

}

else

{

printf("점수는 %d이고, ",score);

printf("불합격입니다.\n");

}

return 0;

}



1.3 형식3 예제(소스코드, 실행결과)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


//if문 형식3

int score;

printf("점수입력 : ");

scanf("%d", &score);

if(score >= 90)

printf("A등급\n");

else if(score>=80) //주의 : else와 if사이에 공백이 있어야함. 

printf("B등급\n"); 

else if(score>=70)

printf("C등급\n");

else

printf("F등급\n"); 

return 0;

}



2. 조건문 - switch문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int menu;


printf("1. 입금하기 \t 2. 출금하기 \t 3. 송금하기 \n");

printf("메뉴 번호선택 : ");

scanf("%d", &menu);

//주의 : case문 뒤에 반드시 break문을 붙인다. 

switch(menu) //정수형 값 또는 정수형 결과 

{

case 1: printf("입금하기 화면이동...\n"); break; 

case 2: printf("출금하기 화면이동...\n"); break;

case 3: printf("송금하기 화면이동...\n"); break;

default: printf("잘못된 입력입니다. \n");

}

return 0;

}




3. 반복문 - for문 예제

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


//for문

int i, sum=0;

printf("1. 1~10출력 \n\n");

for(i=1;i<=10;i++) 

printf("%d\n", i);

printf("\n");

printf("2. 10~1출력 \n\n");

for(i=10;i>=1;i--)

printf("%d\n", i); 

printf("\n");

printf("\n------------------\n");

printf("3. 1~10합출력");

for(i=1;i<=10;i++)

{

sum = sum+i; // sum+=i;

}

printf("합 = %d\n", sum);

printf("\n");

printf("4. 1~10중 3의 배수 출력\n\n");

for(i=0;i<=10;i+=3) // i+=3 은 i=i+3과 같음

printf("%d\n", i);

printf("\n------------------\n");

printf("\n");

printf("5. 무한반복 : 합이 1000이 넘는 i값 \n\n");

for(i=1;;i++) //조건식을 생략하면 무한반복됨

{

printf("%d\n",i);

sum+=i;

if(sum>1000) break;

}

printf("합은 %d \n",sum);


return 0;

}



#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int line, star;

for(line=1;line<=5;line++)

{

for(star=1;star<=line;star++)

printf("*");

printf("\n");

}

for(line=1;line<=5;line++)

{

for(star=5;star>=line;star--)

printf("*");

printf("\n");

}



int i,j;

printf("6. 2중 for문 : 구구단\n\n");

for (i=2;i<=9;i++)

{

for(j=1;j<=9;j++)

{

printf("%d * %d = %d\n",i,j,i*j);

}

printf("\n");

}

return 0;

}





4. 반복문 - while문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


printf("7. while문 : 1~10출력 \n\n");


//while문 형식

// 1. 초기식

// 2. while문(조건식)

// { 반복실행 문장 

// 3. 증감식 

// }

int i;

i=1; //초기식 

while(i<=10)//조건식 

{

printf("%d\n",i);

i++; //증감식 

}


return 0;

}




5. 반복문 - do~while문 예제


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


printf("8. do~while문 : 1~10출력 \n\n");

//형식

// 1.초기식

//do

// {

// //3.증감식 

// } while(조건식); //2. 조건식 : 세미콜론(;) 붙인다.

int i;

i=1; //1. 초기식

do{

printf("%d\n",i);

i++; //3. 증감식 

} while(i<=10); //2. 조건식 


return 0;

}



'basic > C' 카테고리의 다른 글

6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
3. 연산자  (0) 2016.09.22
2. C프로그래밍의 기초문법  (0) 2016.09.08
1. C프로그래밍의 기초  (0) 2016.09.05

1. 대입연산자


(1) 종류 : 왼 = 오 (오른쪽에서 왼쪽으로 대입)


(2) 예제 


#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int a = 3, b = 5, temp=0; // 변수 선언  


printf("교환전 : a= %d, b= %d\n", a, b); 

temp=b; //b를 temp에 대입 

b=a; // a를 b에 대입 

a=temp; // temp를 a에 대입 

printf("교환후 : a= %d, b= %d\n",a ,b);

return 0;

}




2. 산술연산자


(1) 종류 : + 더하기     - 빼기     * 곱하기     / 나누기     % 나머지 구하기(정수만 가능) 


(2) 예제1(소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


int main(int argc, char *argv[]) {


int a, b;


printf("두개의 숫자를 입력하시오\n");


scanf("%d%d", &a, &b);


printf("%d + %d =%d\n", a, b, a + b);// 더하기 연산

printf("%d - %d =%d\n", a, b, a - b);// 빼기 연산


printf("%d * %d =%d\n", a, b, a*b);// 곱하기 연산


printf("%d / %d =%d\n", a, b, a / b);// 나누기 연산


printf("%d %% %d = %d\n\n", a, b, a%b);// 나머지 구하기



return 0;

}



(3) 예제2 : 형변환 연산 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

char ch = 'A'; // A라는 문자의 아스키 코드값을 저장

 

int x = 10, y = 4, sum = 0; 

double pi = 3.14, avg;

sum = ch + 2; //자동형 넓힘 변환. char형(1byte) 에서 int형(4byte)으로 들어가면서 자동으로 모양이 넓혀짐. 

printf("sum = %d = %c \n", sum, sum);

sum = pi; // 자동형 좁힘 변환. double형(8byte) 에서 int형(4byte)으로 컴파일러가 자동으로 모양을 좁혀서 넣음. 

printf("sum = %d \n", sum);

printf("x/y = %d", x/y); // 정수/정수 = 정수 

// 강제형변환 : 실수/실수 = 실수 

printf("x/y = %lf", (double)x/(double)y); //강제적으로 자료형을 변환시킬수있음 

sum = (double)x/(double)y; // 강제형변환 후 자동 형좁힘 ( 실수형 -> 정수형 ) 

printf("잘못된 나눗셈 = %d\n", sum);

avg = (double)(x/y); // 2.5가 아닌 2.0으로 나온 이유 x,y가 이미 정수형으로 연산된 후의 값에 강제형변환을 해서 정확한 값이 안나옴. 

printf("avg = %lf\n", avg);


avg = (double)x/y;

printf("정확한 나눗셈 = %lf\n", avg); 

 

return 0;




3. 복합대입연산자


  (1) 종류 : +=, -+, *=, /=, %/, >>=, <<=, &=, |=, ^=


  (2) 예제 (소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

// 복합대입연산자 

int x,y;

x = y = 5;

printf("x = %d, y = %d\n", x, y);

printf("x += y의 결과는 %d\n", x+=y); // x = x + y

printf("x -= y의 결과는 %d\n", x-=y); // x = x - y

printf("x *= y의 결과는 %d\n", x*=y); // x = x * y

printf("x /= y의 결과는 %d\n", x/=y); // x = x / y

printf("x %%= y의 결과는 %d\n", x%=y); // x = x % y

return 0;

}




4. 관계연산자

  

  (1) 종류 : >, <, >=, <=, ==, !=


  (2) 예제 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

// 관계연산자 

int x,y;

printf("두정수 입력 : ");

scanf("%d%d", &x, &y);

printf("%d > %d 의 결과는 %d입니다.\n", x, y, x>y); // 결과가 참인 경우 리턴값이 1 

printf("%d == %d 의 결과는 %d입니다.\n", x, y, x==y); 

// 결과가 거짓인 경우 리턴값이0 


return 0;

}




5. 논리연산자

 

  (1) 종류 : &&, || !


  (2) 예제 (소스코드, 실행결과, 주석)

#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int x,y,z;

x = 5; y = 10; z;

z = (x+=2) || (y+=1);

printf("x=%d,y=%d\n", x, y); 

printf("z=%d\n", z); // z = (x+=2) || (y+=1) 에서 x = 7이 되고 y = 11이 됨 0이 아닌 수는 참이므로 or 연산에서 참이 하나라도 있으면 결과값이 1 


return 0;

}




6. 조건연산자

  (1) 종류 : ?:

  (2) 예제 (소스코드, 실행결과, 주석)


 /*조건연산자 (조건식? 참: 거짓) 


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {


int n1,n2,max,min; 

 

printf("두정수 입력 : "); 


scanf("%d%d", &n1, &n2); 

 

(n1>n2) ? (max=n1 , min=n2) : (max=n2 , min=n1); 

 

printf("\n>> 큰 수 / 작은 수 = %d\n", max / min); 


printf(">> 큰 수 %% 작은 수 = %d\n", max % min); 


return 0;

}





7. 증감연산자

 

(1) 종류 : ++, --


(2) 예제 (소스코드, 실행결과, 주석)


//증감연산자 ++, --

// ++x (진위형, prefix) : x값 1증가후 연산수행

// --x 

// x++ (후위형, postfix) : x값 연산후 1증가 

// x-- 

//int x=5;

/*

int y=x++; // x는 y에 대입연산후 1증가 

printf("x=%d\n", x);

printf("y=%d\n", y);  

*/

/*

int y=++x; // x가 1증가후 y에 대입연산됨 

printf("x=%d\n", x);

printf("y=%d\n", y); 

*/

int a = 10, b = 20;

printf("a=%d\n", a++); // a에 10의 값이 대입연산후 1증가 

printf("a=%d\n", ++a); // 1의 값이 증가한후 a에 대입연산 

printf("a=%d\n", b--); // b에 20의 값이 대입연산후 1감소 

printf("a=%d\n", --b); // 1의 값이 감소한후 b에 대입연산 


return 0;

}




8. 비트연산자


(1) 종류 : &, |, ^, ~, <<, >>


(2) 예제 (소스코드, 실행결과, 주석)


#include <stdio.h>

#include <stdlib.h>


/* run this program using the console pauser or add your own getch, system("pause") or input loop */


int main(int argc, char *argv[]) {

int x;

printf("정수입력 : ");

scanf("%d", &x);

printf("%d>>3=%d\n", x, x>>3); // 비트를 3번 이동한뒤 나누는 연산 (피연산자 나누기 2^3이 결과값으로 나옴) 

printf("%d<<3=%d\n", x, x<<3); // 비트를 3번 이동한뒤 곱하는 연산 (피연산자 곱하기 2^3이 결과값으로 나옴)

return 0;

}




9. 연산자의 우선순위


연산자 분류에 따른 우선순위 : 단항 > 산술 > 이동 > 관계 > 비트 > 논리 > 조건 > 대입 > 콤마 순이다.


연산자의 우선순위가 기억이 나지않는다면 괄호를 사용하여 강제로 우선순위를 지정할수있다.




'basic > C' 카테고리의 다른 글

6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
2. C프로그래밍의 기초문법  (0) 2016.09.08
1. C프로그래밍의 기초  (0) 2016.09.05

+ Recent posts