1. 구조체 사용과정 (3단계)

  1. main 함수 위에 구조체를 정의함.
  2. main 함수 내에 구조체 변수를 선언함.
  3. 구조체의 맴버를 참조.
2. 구조체 변수를 이용한 예(소스, 결과, 주석)

#include <stdio.h>
#include <stdlib.h>

//1. main 함수 위에 구조체 정의
struct person
{
char id[6];
char name[10];
char tel[14];
int grade;
};

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

//2. 사용자 정의 자료형 : 구조체 변수 선언
struct person members;
printf("학번 : ");
scanf("%s", members.id);
 
printf("이름 : ");
scanf("%s", members.name);
 
  printf("전화 : ");
scanf("%s", members.tel);
printf("등급 : ");
scanf("%d", &members.grade);
printf("이름 : %s, 번호 : %s, 등급 : %d", members.name, members.tel, members.grade);

system("pause");
return 0;
}




3. 구조체 배열을 이용한 예(소스, 결과, 주석)

#include <stdio.h>
#include <stdlib.h>

//1. main 함수 위에 구조체 정의
struct person
{
char id[6];
char name[10];
char tel[14];
int grade;
};

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

//2. 사용자 정의 자료형 : 구조체 배열 선언
struct person members[3];
int i;
for(i=0;i<3;i++)
{
printf("학번 : ");
scanf("%s", members[i].id);
 
printf("이름 : ");
scanf("%s", members[i].name);
 
  printf("전화 : ");
scanf("%s", members[i].tel);
printf("등급 : ");
scanf("%d", &members[i].grade);
}
for(i=0;i<3;i++)
{
printf("\n 이름 : %s, 번호 : %s, 등급 : %d \n", members[i].name, members[i].tel, members[i].grade);
}


system("pause");
return 0;
}





20161126main1.c

main_ver2.c

ForOreport.dev

ForOreport.exe

ForOreport.layout

Makefile.win

report.c

report.o

main_ver2.c


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

7. 포인터  (0) 2016.11.10
6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

1. 포인터의 개념

데이터가 저장된 주기억장치의 주소만 저장 (갂단히 포인터(pointer)라고도 함)


2. 포인터와 배열의 관계 예(소스코드,실행결과)


#include <stdio.h>

#include <stdlib.h>

#define N 4


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


//void print_arr(int arr[]); //3. 함수의 원형 선언 

void print_arr(int *arr);


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

int count[N] = {42, 37, 83, 33}; // 배열이름 = 시작주소 

//1. 출력할 함수의 이름 정의

print_arr(count); 

return 0;

}


//2. 함수 구현

//void print_arr(int arr[]) //int arr[N]배열을 다시 선언하면서 받는다. 

void print_arr(int *arr) //배열의 주소가 넘어오므로 포인터로 받는다. 

{

int i;

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

printf("%3d", *(arr+i));

//printf("%3d", arr[i]);



3. 포인터를 이용한 문자열 교환 예제


#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[]) {


char *first = "GilDong", *last = "Hong"; // 이름 , 성 

char *temp;   // 임시 저장 포인터 변수 

   

printf("Name : %s %s \n", first, last);

    

   

   // 포인터 변수에 저장된 두 주소를 교환해 두 포인터가 가리키는 문자열 교환하기

   

temp = first;

first = last;

last = temp;

   

printf("Name : %s %s \n ", first, last); 



   return 0;

}




4. char형 배열을 이용한 문자열 교환 예제


#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[]) {


 char first[10] = "GilDong", last[10] = "Hong"; // 이름과 성

   char temp[10]; // 문자열을 임시로 저장할 배열


   printf("Name : %s %s\n", first, last);


 // 배열의 내용을 직접 교환하여 두 문자열을 교환하기

   strcpy(temp, first); // first 배열의 문자열을 temp 배열에 복사하기

   strcpy(first, last); // last 배열의 문자열을 first 배열에 복사하기

   strcpy(last, temp); // temp 배열의 문자열을 last 배열에 복사하기

   

   printf("Name : %s %s \n", first, last);



   return 0;

}




5. char형 2차원 배열을 이용한 정렬 예제


#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[]) {


char silver[SIZE][10] = {"나태희","유빈","나원빈","문건영","소지법"};

char temp[10];

int i, pass; 

printf("**은메달 리스트 ");

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

printf("%s, ", silver[i]);

printf("\b\b **\n\n");

for(pass=1;pass<SIZE;pass++)

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

if(strcmp(silver[i], silver[i+1]) > 0 )

{

strcpy(temp, silver[i]);

strcpy(silver[i], silver[i+1]);

strcpy(silver[i+1], temp);

}

printf("**정렬한 리스트 ");

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

printf("%s, ", silver[i]);

printf("\b\b **\n\n");


   return 0;

}




6. char형 포인터배열을 이용한 예제


#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[]) {


   char *gold[5] = {"한빛","성춘향","이몽룡","사공민국","황해"};

   char *temp;

   int size, i, j;

   

   size = sizeof(gold) / sizeof (gold[0]);

   

   printf("** 금메달 리스트 : ");

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

      printf("%s, ", gold[i]);

      printf("\b\b ** \n\n");

   

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

      for(j=i+1;j<size;j++)

         if(strcmp(gold[i], gold[j]) > 0 )

         {

            temp = gold[i];

            gold[i] = gold[j];

            gold[j] = temp;

         }

   

   printf("** 정렬한 리스트 : ");

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

      printf("%s, ", gold[i]);

      printf("\b\b ** \n\n");


   return 0;

}




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

8. 구조체  (0) 2016.11.21
6. 함수  (0) 2016.10.31
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

1. 함수의 필요성 : : 하나의 큰 문제들을 작은 문제로 쪼개어 해결함에 용이하여 사용함.


2 c함수의 종류


(1) 라이브러리 함수


예제1 : 기본적인 rand()함수 소스코드, 실행결과


rand()함수 : 0~32767 범위 안의 임의의 정수를 결과 값으로 호출


문제점 : 컴파일 시켰을때 동일한 값이 출력됨


#include <stdio.h>

#include <stdlib.h>

#include <time.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 i,random;

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

{

random = rand();

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




예제2 : 범위를 지정한 rand()함수 소스코드, 실행결과


#include <stdio.h>

#include <stdlib.h>

#include <time.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 i,random;

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

{

random = rand()%6+1;

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




예제3 : 씨드값 설정한 rand()함수 소스코드, 실행결과


#include <stdio.h>

#include <stdlib.h>

#include <time.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 i,random;

srand(time(NULL));

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

{

random = rand();

printf("%d번째 난수 %5d \n",i ,random);

}

return 0;

}




(2) 사용자 정의함수


정의하는 순서 예제


{1} main() 함수이름 정의


(2) main() 밖 아래 함수기능 정의


(3) main() 밖 위 함수의 원형 정의

아직 정리중인 내용...


(3) 인수 : main에서 넘어가는 값


(4) 매개변수 : 넘어오는 값을 받는 변수


*main()에서 함수호출시 인수를 전달하고 정의된 함수에서 매개변수를 선언하면서 받는다.


3. 함수의 인수전달 방법


(1) 값에 의한 호출 (call by value) 예제(소스코드,실행결과)

main안의 변수 그 안의 인수를 함수(매개변수공간)에 그대로 호출하여 입력. 

원본과 복사본이 서로 독립된 공간을 가짐 여기서 원본은 main공간 안의 인수를말하고 복사본은 사용자 지정 함수안에서의 매개변수 공간을 말함.


#include <stdio.h>

#include <stdlib.h>


void sort_by_point(int first, int second); // 함수 원형정의 


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


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

int point1=5000, point2=4000;

printf("함수 호출전 포인트 점수 %d, %d\n", point1, point2);

sort_by_point(point1, point2); // 값에 의한 호출. 

printf("함수 호출후 포인트 점수 %d, %d\n", point1, point2);

return 0;

}


void sort_by_point(int first, int second) //함수정의 : 값에 의한 호출


{

int temp;

if(first>second)

{

temp=first;

first=second;

second=temp;

}

printf("\n sort함수 안에서 정렬한 결과 first : %d, second : %d\n\n", first, second);

}




(2) 주소에 의한 호출 (call by address) 예제(소스코드,실행결과)


#include <stdio.h>

#include <stdlib.h>


void sort_by_point(int *first, int *second); // 함수 원형정의 


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


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

int point1=5000, point2=4000;

printf("함수 호출전 포인트 점수 %d, %d\n", point1, point2);

sort_by_point(&point1, &point2);   // 주소에 의한 호출. 

printf("함수 호출후 포인트 점수 %d, %d\n", point1, point2);

return 0;

}


void sort_by_point(int *first, int *second) //주소에 의한 호출 

{

int temp;

if(*first>*second)

{

temp=*first;

*first=*second;

*second=temp;

}

printf("\n sort함수 안에서 정렬한 결과 first : %d, second : %d\n\n", *first, *second);

}




4. 값에 의한 호출의 문제점과 주소에 의한 호출의 필요성 : 호출된 함수에서 자신을 호출한 함수의 인수 내용을 수정 할 수가 없는 문제점이 있고 호출된 함수에서 자신을 호출한 함수의 인수를 변경하고 싶다면 주소에 의한 호출을 이용해야 함.


5. 배열 원소 함수로 전달하는 방법->설명

(예제, 소스코드, 주석)


#include <stdio.h>

#include <stdlib.h>


//3. 함수의 원형을 작성 

int find_large(int first, int second);


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


// 배열의 원소를 함수로 전달하는 방법

int max, score[5] = {10,8,9,7,8};

//1. 호출할 위치에서 함수이름 정의

max = find_large(score[1], score[2]);

printf("%d, %d중 큰 수는 = %d\n", score[1], score[2], max);

return 0;

}


//2. 함수 작성

int find_large(int first, int second)

{

if (first>second)

return first;

else

return second;




6. 배열 전체를 함수로 전달하는 방법-> 설명

(예제, 소스코드, 주석)


#include <stdio.h>

#include <stdlib.h>

#define N 4


//3. 함수의 원형을 작성한다. 

void print_arr(int arr[N]);

void percentage(int arr[N]);


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

//예제2. 배열전체를 함수로 전달하는 방법

//함수 전달할때는 ~~~ 넘기고, 함수정의할떄는 ~~~ 받는다. 

int count[N] = {42, 37, 83, 33}; 

//1. 함수 이름을 정의한다. 

printf("인원수 : ");

print_arr(count); //배열 이름은 시작 주소를 의미하기 때문에 주소를 넘기면 배열 전체를 넘길수 있다.  

printf("\n");

printf("백분율 : ");

percentage(count); //함수는 배열의 백분율을 계산해서 출력 

print_arr(count);

return 0;

}


//2. 함수를 작성한다. 

void print_arr(int arr[N]) // int arr[]도 가능하다  

{

int i;

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

printf("%3d", arr[i]);

}


// 배열에 저장된 수치를 백분율로 변경하는 함수 

void percentage(int arr[N])// int arr[]도 가능 

{

int i, total = 0;

//전체 인원을 total에 구하기 

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

total += arr[i]; // 배열 전체를 읽으면서 total값 계산 

// 전체 인원수 total을 이용해 백분율 구하기 

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

arr[i] = (int)((double)arr[i]/total*100);

}



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

8. 구조체  (0) 2016.11.21
7. 포인터  (0) 2016.11.10
5. 배열  (0) 2016.10.13
4. 제어문(조건문과 반복문)  (0) 2016.10.06
3. 연산자  (0) 2016.09.22

+ Recent posts