" async="async"> ', { cookie_domain: 'auto', cookie_flags: 'max-age=0;domain=.tistory.com', cookie_expires: 7 * 24 * 60 * 60 // 7 days, in seconds }); 책 알려주는 남자 :: '프로그래밍/쉽게 풀어쓴 C언어 Express' 카테고리의 글 목록

13장 Programming


1.

#include <stdio.h>


struct point{

int x, y;

};


int equal (struct point p1, struct point p2){

if(p1.x==p2.x && p1.y==p2.y)

return 1;

return 0;

}


int quadrant(struct point p){

if(p.x>0 && p.y>0)

return 1;

else if(p.x<0 && p.y>0)

return 2;

else if(p.x<0 && p.y<0)

return 3;

else if(p.x>0 && p.y<0)

return 4;

}



int main(){

struct point p1, p2;

printf("점의 좌표를 입력하시오: ");

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

printf("점의 좌표를 입력하시오: ");

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

if(equal(p1, p2)==1) 

printf("두 점은 일치합니다\n");

else 

printf("두 점은 일치하지 않습니다\n");

printf("첫번째 점은 %d사분면에 있습니다\n", quadrant(p1)); 

printf("두번째 점은 %d사분면에 있습니다\n", quadrant(p2));


return 0;

}


2.

#include <stdio.h>


struct point{

int x, y;

};


int equal (struct point *p1, struct point *p2){

if(p1->x==p2->x && p1->y==p2->y)

return 1;

return 0;

}


int quadrant(struct point *p){

if(p->x>0 && p->y>0)

return 1;

else if(p->x<0 && p->y>0)

return 2;

else if(p->x<0 && p->y<0)

return 3;

else if(p->x>0 && p->y<0)

return 4;

}



int main(){

struct point p1, p2;

printf("점의 좌표를 입력하시오: ");

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

printf("점의 좌표를 입력하시오: ");

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

if(equal(&p1, &p2)==1) 

printf("두 점은 일치합니다\n");

else 

printf("두 점은 일치하지 않습니다\n");

printf("첫번째 점은 %d사분면에 있습니다\n", quadrant(&p1)); 

printf("두번째 점은 %d사분면에 있습니다\n", quadrant(&p2));


return 0;

}


3.

#include <stdio.h>


typedef struct {

int x, y;

} Point;


typedef struct {

Point a, b

} Rectangle;


int area(Rectangle r);

int perimeter(Rectangle r);

int is_square(Rectangle r);


void main(){

Rectangle r;

printf("오른쪽 상단 점의 좌표: ");

scanf("%d,%d", &r.a.x, &r.a.y);

printf("왼쪽 하단 점의 좌표: ");

scanf("%d,%d", &r.b.x, &r.b.y);

printf("사각형의 넓이: %d\n", area(r));

printf("사각형의 둘레: %d\n", perimeter(r));

if(is_square(r)==1)

printf("정사각형입니다\n");

else

printf("정사각형이 아닙니다\n"); 

}


int area(Rectangle r){

return (r.a.x-r.b.x)*(r.a.y-r.b.y); 

}


int perimeter(Rectangle r){

return ((r.a.x-r.b.x)+(r.a.y-r.b.y))*2;

}


int is_square(Rectangle r){

if((r.a.x-r.b.x)==(r.a.y-r.b.y))

return 1;

return 0;

}


4.

#include <stdio.h>


typedef struct {

double real;

double imag;

} Complex;


void add_complex(Complex x, Complex y);


void main(){

Complex x, y;

printf("첫 번째 복소수의 실수부: "); scanf("%lf", &x.real);

printf("첫 번째 복소수의 허수부: "); scanf("%lf", &x.imag);

printf("두 번째 복소수의 실수부: "); scanf("%lf", &y.real);

printf("두 번째 복소수의 허수부: "); scanf("%lf", &y.imag);

add_complex(x, y); 

}


void add_complex(Complex x, Complex y){

printf("합의 실수부: %lf\n", x.real+y.real);

printf("합의 허수부: %lf\n", x.imag+y.imag);

}


5.

#include <stdio.h>


typedef struct{

double x, y;

} Vector;


void add_vector(Vector v1, Vector v2);


void main(){

Vector v1, v2;

printf("벡터 a의 좌표: ");

scanf("%lf,%lf", &v1.x, &v1.y);

printf("벡터 b의 좌표: ");

scanf("%lf,%lf", &v2.x, &v2.y);

add_vector(v1, v2);

}


void add_vector(Vector v1, Vector v2){

printf("벡터 a+b = (%0.2lf,%0.2lf)", v1.x+v2.x, v1.y+v2.y);

}


6.

#include <stdio.h>


typedef struct {

char title[30];

char toname[20];

char byname[20];

char text[100];

char date[20];

int primary;

} Email;


void main(){

Email x;

printf("제목: ");

gets(x.title);

printf("수신자: ");

gets(x.toname);

printf("발신자: ");

gets(x.byname);

printf("본문: ");

gets(x.text);

printf("보낸날짜(yymmdd): ");

gets(x.date);

printf("우선순위: ");

scanf("%d", &x.primary); 

}


7.

#include <stdio.h>


typedef struct{

char name[100];

int calories;

} Food;


void add_calories(Food info[], int count);


void main(){

Food info[10];

int i=0, count=0;

char an;

while(1){

printf("음식정보를 저장하시겠습니까?(y/n)");

scanf("%c", &an);

fflush(stdin);

if(an=='n')

break; 

printf("음식이름: ");

gets(info[i].name);

printf("칼로리: ");

scanf("%d", &info[i].calories);

fflush(stdin);

i++;

count++;

}

add_calories(info, count);

}


void add_calories(Food info[], int count){

int i, sum=0;

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

sum+=info[i].calories;

printf("총 칼로리는 %d입니다", sum);

}


8.

#include <stdio.h>


typedef struct{

int id_number;

char name[20];

int ph_number;

int age;

} Employee;


void main(){

Employee people[10];

int i, count=0;

for(i=0; i<10; i++){

printf("%d번째 직원정보\n", i+1);

printf("사원번호: "); scanf("%d", &people[i].id_number);

fflush(stdin);

printf("이름: "); gets(people[i].name);

printf("전화번호: "); scanf("%d", &people[i].ph_number);

printf("나이: "); scanf("%d", &people[i].age);

}

printf("\n");

printf("나이가 20이상 30이하인 직원\n");

for(i=0; i<10; i++){

if(people[i].age>=20 && people[i].age<=30){

puts(people[i].name);

count++;

}

printf("해당 총인원: %d명\n", count);

}


9.

#include <stdio.h>

#include <string.h>

 

typedef struct {

    char name[20];

    char homeNum[20];

    char phoneNum[20];

} Book;


void main() {

    Book number[5];

    char search[20];

    int i;

    char an;

 

    for(i=0; i<5; i++) {

        printf("%d번째 전화번호부\n", i+1);

        printf("이    름 : ");        gets(number[i].name);

        printf("자택번호 : ");        gets(number[i].homeNum);

        printf("휴대전화 : ");        gets(number[i].phoneNum);

    }

    printf("\n");

 

    do {

        printf("이름을 검색하시오 : ");

        gets(search);

        for(i=0; i<5; i++) {

            if(strcmp(search, number[i].name) == 0) {

                printf("자택번호 : %s \n", number[i].homeNum);

                printf("휴대전화 : %s \n", number[i].phoneNum);

                printf("\n");

            }

        }

        printf("계속 찾으시겠습니까?(y/n) : ");

        scanf("%c", &an);

        fflush(stdin);

    } while(an != 'n');

}



10.

#include <stdio.h>

#include <stdlib.h>

#include <time.h> 

#define SIZE 52


typedef struct {

int value;

char suit;

} Card;


void init_card(Card pack[], char shape[]);

void print_card(Card pack[], int size);

void shuf_card(Card pack[], int size);


void main(){

Card pack[SIZE];

char shape[]={'c', 'd', 'h', 's'};

init_card(pack, shape);

printf("카드가 초기화 되었습니다.\n");

print_card(pack, SIZE); 

printf("\n");

shuf_card(pack, SIZE);

printf("카드를 섞었습니다.\n");

print_card(pack, SIZE);

printf("\n");

}


void init_card(Card pack[], char shape[]){

int i, j, count=0;

for(i=0; i<4; i++){

for(j=0; j<13; j++){

pack[count].value=j+1;

pack[count].suit=shape[i];

count++;

}

}

}


void print_card(Card pack[], int size){

int i, j;

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

printf("%3d%c", pack[i].value, pack[i].suit);

if((i+1)%13==0)

printf("\n");

}

}


void shuf_card(Card pack[], int size){

int i, j;

srand((unsigned)time(NULL));

Card temp;

for(i=0; i<size-1; i++){

j=rand()%(size-i)+i;

temp = pack[i];

pack[i] = pack[j];

pack[j] = temp;

}

}


11.

#include <stdio.h>

#define PI 3.14

#define SIZE 10


typedef struct {

int type;

union {

struct { double base, height; } tri;

struct { double width, height; } rect;

struct { double radius; } circ;

} shape;

} Figure;


void main(){

Figure data[SIZE];

int i=0;

char an;

do{

printf("저장하려는 도형의 종류를 입력하시오(0=삼각형, 1=사각형, 2=원): ");

scanf("%d", &data[i].type);

fflush(stdin);

switch(data[i].type){

case 0 : 

printf("삼각형의 밑변: "); scanf("%lf", &data[i].shape.tri.base);

printf("삼각형의 높이: "); scanf("%lf", &data[i].shape.tri.height);

i++;

break;

case 1 : 

printf("사각형의 밑변: "); scanf("%lf", &data[i].shape.rect.width);

printf("사각형의 높이: "); scanf("%lf", &data[i].shape.rect.height);

i++;

break;

case 2 : 

printf("원의 반지름: "); scanf("%lf", &data[i].shape.circ.radius);

i++;

break;

default:

printf("숫자를 0~2사이 값을 입력하시오\n");

fflush(stdin);

printf("더 저장하시겠습니까?(y/n)\n");

scanf("%c", &an);

} while(an!='n');

}



12.

#include <stdio.h>

#include <string.h>

#define SIZE 20


typedef struct {

char title[20];

char singer[20];

int class;

} Music;


int i;

int num[SIZE]={0};


void add_music (Music* list);

void print_music (Music* list);

void search_music (Music* list, int size);

void delete_music (Music* list);


void main(){

Music list[SIZE];

int n, result=1;

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

printf(" 1. 추가(ADD)\n");

printf(" 2. 출력(PRINT)\n");

printf(" 3. 검색(SEARCH)\n");

printf(" 4. 삭제(DELETE)\n");

printf(" 5. 종료(EXIT)\n");

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

while(result==1){

printf("메뉴를 선택하시오: ");

scanf("%d", &n);

fflush(stdin);

switch(n) { 

case 1: 

add_music(list);

break;

case 2:

print_music(list);

break;

case 3: 

search_music(list, SIZE);

break;

case 4:

delete_music(list);

break;

case 5:

result=0;

}

}


void add_music(Music* list){

do{

printf("1번부터 %d번까지 트랙이 있습니다. 몇 번 트랙에 저장하시겠습니까?", SIZE);

scanf("%d", &i);

fflush(stdin);

if(num[i-1]==1)

printf("이미 저장되어있는 트랙입니다. 다른 트랙번호를 입력하시오\n");

} while(num[i-1]==1);

printf("제목: "); gets(list[i-1].title);

printf("가수: "); gets(list[i-1].singer);

printf("종류(팝=0, 재즈=1, 클래식=2, 락=3): "); scanf("%d",&list[i-1].class);

fflush(stdin);

num[i-1]=1;

printf("\n");

}


void print_music(Music* list){

do{

printf("몇 번 트랙의 음악정보를 출력하시겠습니까? ");

scanf("%d", &i);

if(num[i-1]==0)

printf("해당 트랙엔 저장된 음악정보가 없습니다. 다른 트랙번호를 입력하시오\n");

} while(num[i-1]==0);

printf("제목: %s\n", list[i-1].title);

printf("가수: %s\n", list[i-1].singer);

switch(list[i-1].class){

case 0: printf("종류: 팝\n"); break;

case 1: printf("종류: 재즈\n"); break;

case 2: printf("종류: 클래식\n"); break;

case 3: printf("종류: 락\n"); break;

}

printf("\n"); 

}


void search_music(Music* list, int size){

char searchName[20];

printf("검색하고자 하는 노래 제목을 입력하시오: ");

gets(searchName); 

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

if(strcmp(searchName, list[i].title)==0){

printf("제목: %s\n", list[i].title);

printf("가수: %s\n", list[i].singer);

switch(list[i].class){

case 0: printf("종류: 팝\n"); break;

case 1: printf("종류: 재즈\n"); break;

case 2: printf("종류: 클래식\n"); break;

case 3: printf("종류: 락\n"); break;

}

}

else {

printf("찾으시는 노래가 없습니다\n");

break; 

}

}

printf("\n");

}


void delete_music(Music* list){

do{

printf("몇 번 트랙의 음악정보를 삭제하시겠습니까? ");

scanf("%d", &i);

if(num[i-1]==0)

printf("해당 트랙엔 저장된 음악정보가 없습니다. 다른 트랙번호를 입력하시오\n");

} while(num[i-1]==0);

num[i-1]=0;

printf("%d번 트랙의 음악정보가 삭제되었습니다\n", i-1);

printf("\n");

}

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

13장 Summary


구조체와 배열의 차이점은 묶는 료형들의 일치여부이다.

구조체는 키워드 struct으로 선언하고 공용체는 union, 열거형은 enum으로 선언한다.

구조체의 선언만으로 변수가 만들어지는가? 아니다. 따로 변수의 선언이 필요하다

구조체를 가리키는 포인터 p를 통하여 구조체 안의 변수 x를 참조하는 수식은
(*p).x 또는 p->x
이다.

원본 구조체를 포인터로 함수에 전달하는 경우, 원본 구조체를 훼손하지 않게 하려면 어떻게 하면 되는가? const 키워드가 포인터 앞에 있으면 이 포인터가 가리키는 구조체의 값을 변경하려고 하면 오류메시지가 뜬다. 즉 원본수정이 불가능하게 되어 원본이 훼손되지 않는다


 union data{

   double d;
   int i;

  };

union 은 다른 타입의 변수들이 동일한 기억 공간을 공유할 수 있도록 만든 것이다. 때문에 동시에 모든 멤버 변수들의 값을 저장할 수 없으며 어떤 순간에는 하나의 멤버만 존재할 수 있다


  enum color { red, green, blue};

  enum color favorite = red; 

enum 은 정수형 상수값들을 나열해 놓은 자료형이다.

#define 대신에 열거형을 사용하는 장점은 무엇인가? 특정한 숫자 대신 기호를 사용함으로써 프로그램의 이해도를 향상 시킬 수 있고, 변수가 열거된 값 이외의 값을 취하는 것을 막아서 오류를 줄여준다


   typedef long int BIGINT;

   BIGINT i; 

새로운 자료형을 정의하기 위하여 사용되는 키워드는 typedef이다.

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

13장 Exercise


1. 구조체를 정의하고 c1이라는 이름의 구조체 변수를 정의하시오.

struct customer {

char name;

int post_num;

long mileage;

};

struct customer c1;


2. T/F

(a) 구조체를 선언하면 자동으로 변수가 생성된다. F
(b) typedef은 변수를 선언하는 키워드이다. F, 변수가 아니라 자료형이다
(c) 구조체는 ==연산자를 사용하여 비교할 수 있다. T
(d) 구조체를 함수로 전달하면 원본이 전달된다.   F, 복사본이 전달된다
(e) 구조체 변수는 =연산자를 이용하여 대입될 수 있다. T

비고) 대입의 경우 p1=p2나 p1.x=p2.x, p1.y=p2.y 모두 가능하다. 하지만 비교의 경우 p1==p2는 불가능하고 p1.x==p2.x && p1.y==p2.y 가 가능하다


3. Employee 구조체로 정의된 변수 e에는 salary라는 필드가 있다. 이 필드를 올바르게 참조한 것은?

②e.salary


4. 포인터 p는 Employee 구조체로 정의된 변수 e를 가리킨다. 올바르게 참조한것은?

① p->salary ③ (*p).salary


5. 다음 열거형의 정의를 보고 각 식별자의 정수값을 예측하여 보라.

enum colors {white, red=3, blue, green, black=9 };

 식별자 

 white 

 red 

 blue 

 green 

 black 

 값

 0

 3 

 4 

 5 

 9 

비고) 0부터 혹은 지정된 값으로부터 자동적으로 1씩 증가한다.


6. 다음과 같은 구조체 정의가 있는 경우에 올바른 문장을 모두 골라라

   struct STU{

        char name[30];
        int id;

    } s; 

 ①②③⑤⑦⑧⑥


7. 잠시 컴파일러가 되어보자. 다음 코드에서 오류가 있는 것은?

   union id{

        char name[4];

        long number;

   } var={"Tom", 1}; 

초기화 할 시 한 번에 하나의 멤버만 사용이 되기 때문에  첫 번째 멤버만 초기화된다. 따라서 var={"Tom"}; 으로 바꾸어야 한다.


8. 다음의 설명에 부합하는 구조체를 정의하여 보라.

(a) char title[30]과 int pub_date, pages, price를 포함하는 구조체 book

struct book{

      char title[30];
      int pub_date;
      int pages;
      int price;

};

(b) char name[30], int age, double height를 포함하는 구조체 friend

struct friend{

      char name[30];
      int age;
      double height;

};

(c) 이름, 수량, 가격으로 부품 재고를 표현하는 구조체 part 정의

struct part{

      char name[20];
      int ea;
      int price;

};


9. 다음의 설명에 부합하는 열거형을 정의하여 보라

(a) 빛의 3원색을 표현하는 열거형 primary_color

enum primary_color { RED, GREEN, BLUE };

(b) 12달을 표현하는 열거형 months 정의

enum months { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

  


10. 다음 코드가 오류를 가지고 있는지를 먼저 분석하고 오류가 있다면 어떤 오류인지 설명하라.

 (a) 

 struct book{

    char title[50];
    int pages;

 };

 book.pages = 512;


 struct book{ 

    char title[50];
    int pages;

 }; book;

 book.pages = 512;


 (b) 

 struct book{

     char title[50]="Data Structures";
     int pages = 577;

 } abook;

 struct book{

      char title[50];
      int pages;

 }; abook = {"Data Structures", 577};

 (c)

 typedef enum { red, green, blue } color;

 color.red = 1;

 typedef enum color { red=1, green, blue };

 (d)

 struct fraction {

     int num;
     int den;

  } *p;

  *p->num = 3;
  *p->den = 5;

 struct fration {

      int num;
      int den;

 } s = {3, 5};

 struct fration p;

 p=&s;



블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

12장 Programming


1.

#include <stdio.h>


void main(){

char c;

printf("문자를 입력하시오: ");

scanf("%c", &c);

printf("아스키 코드값=%d", c);

}


2.

#include <stdio.h>


void space_delete(char *str);


void main(){

char str[100];

printf("공백 문자가 있는 문자열을 입력하시오: ");

gets(str);

space_delete(str);

}


void space_delete(char *str){

int i=0;

while(str[i]!=NULL){

if(str[i]!=' ')

printf("%c", str[i]);

i++;

}

}


3.

#include <stdio.h>


int str_chr(char *s, int c);


void main(){

char s[100];

char c;

printf("문자열을 입력하시오: ");

gets(s);

printf("개수를 셀 문자를 입력하시오: ");

scanf("%c", &c); 

printf("%c의 개수 : %d", c, str_chr(s, c));

}


int str_chr(char *s, int c){

int i, count=0;

for(i=0; s[i]!=NULL; i++){

if(s[i]==c)

count++;

}

return count;

}


4.

#include <stdio.h>


int str_chr(char *s, int c);

void count_chr(char *s);


void main(){

char s[100];

char c;

printf("문자열을 입력하시오: ");

gets(s);

count_chr(s);

}


int str_chr(char *s, int c){

int i, count=0;

for(i=0; s[i]!=NULL; i++){

if(s[i]==c)

count++;

}

return count;

}


void count_chr(char *s){

int i;

for(i='a'; i<='z'; i++)

printf("%c: %d\n", i, str_chr(s,i));

}


5.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>


void upper_lower(int c);


void main(){

int c;

printf("문자를 입력하시오: ");

while((c=getchar())!='.'){

fflush(stdin);

if(islower(c)){

c=toupper(c);

putchar(c);

}

else if (isupper(c)){

c=tolower(c);

putchar(c);

}

printf("\n");

printf("문자를 입력하시오: ");

}

}


6.

#include <stdio.h>


void str_upper(char *s);


void main(){

char s[100];

printf("문자열을 입력하시오: ");

gets(s);

str_upper(s); 

printf("변화된 문자열: ");

puts(s);

}


void str_upper(char *s){

int i;

for(i=0; s[i]!=NULL; i++)

if(s[i]>='a' && s[i]<='z')

s[i] += 'A' - 'a';

}


7.

#include <stdio.h>

#include <string.h>


int get_response(char *prompt);


void main(){

char prompt[10];

printf("게임을 하시겠습니까? ");

gets(prompt);

if(get_response(prompt)==1)

printf("긍정적인 답변");

else

printf("부정적인 답변");

}


int get_response(char *prompt){

strlwr(prompt);

if(strcmp(prompt, "no")==0)

return 0;

else if (strcmp(prompt, "yes")==0 || strcmp(prompt, "ok")==0)

return 1;


8.

#include <stdio.h>

#include <string.h>


int count(char *str);

char *token;

void main(){

char str[100];

printf("문자열을 입력하시오: ");

gets(str);

printf("단어의 수는 %d입니다.", count(str));

}


int count(char *str){

int count=1;

token = strtok(str, " ");

while(token!=NULL){

count++;

token=strtok(NULL, " ");

}

return count;

}



9.

#include <stdio.h>

#include <string.h>


char check_upper(char *str);

char check_punct(char *str);


void main(){

char str[100];

printf("텍스트를 입력하시오: ");

gets(str);

check_upper(str);

check_punct(str);

printf("결과 텍스트 출력: %s", str); 

}


char check_upper(char *str){

if(islower(str[0]))

str[0]=toupper(str[0]);

return str;

}


char check_punct(char *str){

if(ispunct(str[strlen(str)-1])==0)

str[strlen(str)]='.';

return str;

}


10.

#include <stdio.h>

#include <string.h>


int check_palindrome(char *str);


void main(){

char str[100];

printf("문자열을 입력하시오: ");

gets(str);

strupr(str);

if(check_palindrome(str)==0)

printf("회문입니다.");

else 

printf("회문이 아닙니다."); 

}


int check_palindrome(char *str){

int i, count=0;

for(i=0; i<strlen(str)/2; i++){

if(str[i]==str[strlen(str)-1-i])

count+=0;

else

count+=1;

}

return count;

}


11.  ★★★★

#include <stdio.h>

#include <string.h>

#include <stdlib.h>


void main(){

char str[100];

char *word[100];            // 배열이 아니라 포인터배열이여야만 여러글자를 한 칸에 넣을 수 있다. 주소지(여기서는 token)를 가르키는 방법으로 && 저장될 곳을 미리 할당해주어야 한다.

char *token;

int i, count=0;

printf("문자열을 입력하시오: ");

fgets(str, sizeof(str), stdin);

str[strlen(str)-1] = NULL;    // 남은 빈칸에 쓰레기값이 들어가는 것을 방지함

token = strtok(str, " ");

for(i=0; token!=NULL; i++){

word[i] = token;        // 문자열에서 찾은 마지막 토큰의 주소값을 리턴하며 토큰이 더이상 없다면 NULL 포인터를 리턴한다. 

token = strtok(NULL, " ");

count++;

}

printf("출력문자열: ");

for(i=0; i<count; i++){

printf("%s ", word[count-i-1]);

}


비고) scanf함수는 공백, \t, \n이 오기 전까지의 의미있는 값들을 받는 함수이다. 즉 중간에 띄어쓰기가 있다면 scanf는 띄어쓰기가 포함된 모든 문자열을 입력값으로 받는 것이 아니라 첫번째 띄어쓰기 전까지의 입력값만을 받고 나머지는 버퍼stdin에 저장된다. 문제에서 요구하는 '엔터키가 눌려질 때까지 사용자로부터 문자열을 입력받아서' 라는 문장의 의미는 \n이 오기 전까지 공백과 \t이 포함된 문자열을 받는 fgets함수를 사용하라는 의미이다.  scanf함수의 복잡성을 알지 못한다면 다소 이해하기 어려운 문제이다.

기본형식: char *fgets(char *str, int num, FILE*stream);

 scanf 함수의 앞부분을 생략하는 것처럼 처음의 char * 은 보통 생략한다. 첫 번째 인자는 저장할 배열을 의미한다. 두 번째 인자는 마지막 NULL문자를 포함하여 읽어들일 문자의 수를 의미한다. 세 번째 인자는 문자열을 받아들일 스트림의 FILE 객체를 가르키는 포인터이다. 보통 표준입력에서 입력을 받기때문에 대개 stdin을 쓴다.

성공적으로 읽어드렸다면 함수는 str을 반환하고 오류가 발생하거나 아무것도 읽어드리지 못했다면 NULL 포인터를 반환한다.


12. 

#include <stdio.h>

#include <string.h>


char get_punct(str);


void main(){

char str[100];

char *name[100];

char *token;

char seps[]=" ";

int i, count=0;

printf("영어 이름을 입력하시오: ");

fgets(str, sizeof(str), stdin);

strlwr(str);

str[strlen(str)-1]=NULL;

token = strtok(str, seps);

for(i=0; token!=NULL; i++){

name[i]=token;

token=strtok(NULL, seps);

count++;

printf("변환된 이름: %s %s, %s", name[1], name[2], name[0]);

}


13.

#include <stdio.h>

#include <string.h>


void main(){

char str[100];

int i, count=0;

printf("텍스트를 입력하시오: ");

fgets(str, sizeof(str), stdin);

str[strlen(str)-1]=NULL;

for(i=0; str[i]!=NULL; i++)

if(str[i]=='.' || str[i]==',')

count++;

printf("구두점의 갯수는 %d개입니다.", count);  

}


14. ★★

#include <stdio.h>

#include <string.h>


void main(){

char str[80];

char word1[10];

char word2[10];

char *token;

char *str2[80];

int i, count=0;

printf("문자열을 입력하시오(최대 80자): ");

fgets(str, sizeof(str), stdin);

str[strlen(str)-1]=NULL;

printf("찾을 문자열: ");

fgets(word1, sizeof(word1), stdin);

word1[strlen(word1)-1]=NULL;

printf("바꿀 문자열: ");

fgets(word2, sizeof(word2), stdin);

word2[strlen(word2)-1]=NULL;

token = strtok(str, " ");

for(i=0; token!=NULL; i++){

str2[i]=token;

token=strtok(NULL, " ");

count++;

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

if(strcmp(word1, str2[i])==0)

str2[i] = word2;

printf("결과: ");

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

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

}


15.

#include <stdio.h>

#include <string.h>


void main(){

char str[3];

int x, y, result;

printf("연산을 입력하시오: ");

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

if(strcmp(str, "add")==0) result=x+y;

else if(strcmp(str, "sub")==0) result=x-y;

else if(strcmp(str, "mul")==0) result=x*y;

else if(strcmp(str, "div")==0) result=x/y;

printf("연산의 결과: %d", result);

}


16. ★★★

(a) 매 반복마다 실제로 문자 배열의 내용을 수정


(b) 포인터를 이용하여 현재 위치에서 일정길이만큼 화면 표시

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

12장 Exercise


1. 

(a) strcat() 함수는 하나의 문자열의 끝에 다른 문자열을 연결한다. 
(b) strcpy() 함수는 문자열을 복사한다.
(c) strtok() 함수는 문자열에서 토큰을 찾는다.
(d) gets() 함수는 표준입력에서 하나의 문자열을 읽는다.
(e) strlen() 함수는 문자열을 이루는 문자의 개수를 반환한다.


2. 오류있을 시 정정하라

(a) strcat(s, '?');

 (a) strcats(s, "?");

 (b) if( s!="value")

 (b) if(strcmp(s1, "value") !=0

 (c) char a[20];
     a="Hello World!";

 (c) char a[20];
     strcpy(a, "Hello World!");

     또는

     char *a;
     a="Hello World!";



3. 다음 문장이 제대로 동작하지 않은 이유 및 수정방안

  char *s1 = "Hi ";
  char *s2 = "Programmers!";
  char *s3 = strcat(s2, s2); 

 *s1의 공간은 NULL을 포함해 3byte뿐이다. 이어 붙일 공간이 부족하기 때문에 동작하지 않는다.

 char s1[100] = "Hi ";


4. 다음 두 문장의 차이점을 설명하라

  char a[] = "Hello World!";
  strcpy(a, "Goodbye"); 

  char *p = "Hello World!";
  p = "Goodbye";

비고) 문자열 변경에 있어서 방법이 다르다.


5. 두개의 문자열이 일치하는지를 검사하는 문장을 올바르게 작성한 것은?

④if( strcmp(s1, "Hello") == 0)


6. 오류있을 시 정정하라

 int main(){

     char *p;

     scanf("%s", p);

  } 

 int main(){

    char *p=malloc(sizeof(char)*10);

    scanf("%s", p);

  } 

비교 ) 문자열 포인터에 입력값을 받을 때, 문자열을 받을 수 있을 만큼 메모리를 할당해 주어야 한다. 


7. 다음의 변수들에게 몇 바이트의 메모리가 할당되는가?

 (a) char str[] = "abc"; 

  4 bytes

 (b) char *pc = "abc";

  4 bytes

 (c) char str[10] = "abc";

  10 bytes

 (d) char str[2][10] = {"abc", "def"};

  20 bytes


8. 다음의 수식값을 말하여라

char s[][10] = {"HIGH", "MIDDLE", "LOW"};

(a) s[0] = HIGH

(b) s[1][3] =D

(c) *S = HIGH


9. 다음 코드의 실행결과를 써라

void main()

{

char *p;

char s[]="Hello";

p=s+strlen(s) -1;

while(p>=s){

printf("%s \n", p);

p--;

}

}


실행결과) 

o
lo
llo
ello
Hello

비고) 처음 p=s+4이고 반복될 때마다 1씩 줄어든다. 

처음엔 s+4인 지점부터의 문자열을 프린트해서 o가 나오고

그 다음엔 s+3인 지점부터 문자열을 프린트해서  lo가 나온다.

이런식으로 반복하여 마지막엔 s의 문자열 전체가 나온다.



10. 다음의 함수가 하는 작업은 무엇인가? 구체적으로 mystery("abc", "abd")와 같이 호출하면 어떤 값이 반환되는가?

#include <stdio.h>


int mystery(const char *s1, const char *s2){

while(*s1==*s2){

if(*s1==0)

return (0);

s1++; 

s2++;

}

return (1);

}


void main(){

int result;

result = mystery("abc", "abd");

printf("%d", result);

}


실행결과) 1

비고) 두 개의 문자열 상수가 일치하는지를 검사하는 함수이다. 일치한다면 0으로 반환될 것이고 한 문자라도 틀리면 1로 반환될 것이다.

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

12장 Summary


컴퓨터에서 문자는 아스키 코드로 나타낸다.

문자를 표현하는 자료형은 char이다.

문자열은 연속된 문자들의 모임으로 문자열의 끝은 NULL 문자로 표시한다.
                               정상적인 데이터와 쓰레기값을 분리하기 위해서 필요하다.

문자열을 저장할 때는 char형의 배열에 저장한다.

대상 

설명 

 A

 컴파일러는 변수의 이름으로 간주한다

 'A'

 문자 A를 나타낸다. 문자 A에 대한 아스키코드와 같다

 "A"

 문자 A로 이루어진 문자열을 나타낸다


문자 배열 s를 "xyz"로 초기화하려면 char s[] = {'x', 'y', 'z', '\0'}; 또는 char s[] = "xyz"; 와 같이 한다.

저장하려는 문자열의 크기보다 문자 배열의 크기를 하나 더 크게 하는 이유은 NULL 문자를 저장하기 위해서이다.


데이터 세그먼트 : 값을 변경할 수 있는 메모리 영역 (모든 변수)

텍스트 세그먼트  : 값을 읽기만 하고 변경할 수 없는 메모리 영역(문자열 상수)

이로 인해 아래와 같은 차이가 발생한다.

 가능 

 불가능 

 char p[] = "HelloWorld";
 strcpy(p, "Goodbye");

 char *p = "HelloWorld";
 strcpy(p, "Goodbye");

 char *p = "HelloWorld";
 p = "Goodbye";

 char p[] = "HelloWorld";
 p = "Goodbye";



문자열 처리 함수에는 다음과 같은 함수들이 있다.

함수 

설명 

 strlen(s)

 문자열 s의 길이를 구한다

 strcpy(s1, s2)

 s2를 s1에 복사한다 

 strcat(si1 s2)

 s2를 s1의 끝에 붙여넣는다 

 strcmp(s1, s2)

 최대 n개의 문자까지 s1과 s2를 비교한다


strcmp() 함수에서 2개의 문자열이 일치하면 어떤 값이 반환되는가? 0

문자열 처리 라이브러리 함수를 사용하려면 포함시켜야하는 헤더 파일은 <string.h> 이다.

getchar()와 getch()의 차이점은 버퍼의 사용유무, 에코여부, 문자수정여부이다.(getchar()가 모두 사용 혹은 가능)

strcpy()와 strncpy()의 차이점은 복사할 문자의 개수 제한여부이다.

strcmp("dog", "dog")의 반환값은 0이다.

음수 

 s1이 s2보다 앞에 있다 

 0

 s1 == s2 

 양수

 s1이 s2보다 뒤에 있다


printf()와 sprintf()의 차이점은 첫번째 매개변수이다.

문자열 입출력 함수에는 다음과 같은 함수들이 있다. 

함수 

설명 

 gets()

 한 줄의 문자열을 읽어서 배열에 저장한다

 puts()

 배열에 저장되어 있는 한 줄의 문자열을 출력한다

 sprintf(s, ...)

 변수의 값을형식 지정자에 따라 문자열 형태로 문자 배열 s에 저장한다

 sscanf(s, ...)

 문자열 s로부터 지정된 형식으로 수치를 읽어서 변수에 저장한다



블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

11장 Programming


1.

#include <stdio.h>


int main(){

int x=0x12345678;

unsigned char *xp=(char *)&x;
        // x의 주소값을 char형으로 변환

printf("바이트 순서: %x %x %x %x\n", xp[0], xp[1], xp[2], xp[3]);     
        //xp의 배열을 출력 

if(xp[0]=='Ctrl-R DC2') printf("해당 CPU는 빅엔디언입니다.\n");

else if (xp[0]=='x')                 printf("해당 CPU는 리틀 엔디언입니다.\n");

return 0; 

}


2.

#include <stdio.h>


void get_sum_diff(int x, int y, int *p_sum, int *p_diff)

{

*p_sum=x+y;

*p_diff=x-y;

 

 int main()

 {

int x, y;

int p_sum;

int p_diff;

printf("두개의 정수를 큰 순서대로 입력하시오: ");

scanf("%d %d", &p_sum, &p_diff);

get_sum_diff(x, y, &x, &y);

printf("두 수의 합: %d\n", p_sum);

printf("두 수의 차: %d\n", p_diff); 

  return 0;

 }


3.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define SIZE 10 


void array_fill(int *A, int size){

int i;

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

{

A[i]=rand();

printf("A[%d]=%d\n", i, A[i]);

}

}


void main(){

srand((unsigned)time(NULL));

int A[SIZE];

array_fill(A, SIZE);

}



4.

#include <stdio.h>


void array_print(int *A, int size){

int i;

printf("A[] = { ");

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

A[i]= i+1;

if(i==size-1) printf("%d");

else printf("%d, ", A[i]);

}

printf(" }\n");

}


void main(){

int A[5];

array_print(A, 5);

}


5.

#include <stdio.h>


void convert(double *grades, double *scores, int size){

int i;

printf("scores[] = { ");

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

scores[i]=100*grades[i]/4.3;

if(i==size-1) printf("%3.2lf }", scores[i]);

else printf("%3.2lf, ", scores[i]);

}

}


void main(){

double grades[] = { 1.5, 2.3, 2.6, 3.1, 3.3, 3.5, 3.85, 4.1, 4.21, 4.3};

double scores[10];

convert(grades, scores, 10);

}


6.

#include <stdio.h>


void array_copy (int *A, int *B, int size){

int i;

printf("B[] = {");

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

B[i]=A[i];

if(i==size-1) printf("%d }", B[i]);

else printf("%d, ", B[i]);

}

}


void main(){

int A[]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int B[10];

array_copy(A, B, 10);

}


7.

#include <stdio.h>


void array_add (int *A, int *B, int *C, int size){

int i;

printf("각 사원들의 총 월급액 = {");

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

C[i]=A[i]+B[i];

if(i==size-1) printf("%d만원 }", C[i]);

else printf("%d만원, ", C[i]);

}

}


void main(){

int A[]={170, 132, 123, 124, 155, 186, 171, 189, 193, 210};

int B[]={30, 12, 15, 22, 38, 25, 55, 45, 36, 19};

int C[10]={0};

array_add(A, B, C, 10);

}


8.

#include <stdio.h>


int array_sum (int *A, int size){

int i, sum=0;

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

sum+=A[i];

return sum;

}


void main(){

int A[]={170, 132, 123, 124, 155, 186, 171, 189, 193, 210};

printf("지급할 월급 총액:  %d만원", array_sum(A, 10));


9.

#include <stdio.h>


int search (int *A, int size, int search_value){

int i;

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

if(A[i]==search_value)

printf("%d번째 사원의 월급이 200만원입니다.\n", i+1);

}

return 0;

}


void main(){

int A[]={170, 200, 123, 124, 155, 186, 200, 189, 193, 210};

search(A, 10, 200);


10.

#include <stdio.h>


int get_gcd(int x, int y){

while(y!=0){

int a=x%y;

x=y;

y=a;

}

return x;

}


void get_lcm_gcd(int x, int y, int *p_lcm, int *p_gcd){

*p_gcd = get_gcd(x, y);

*p_lcm = (x*y) / *p_gcd;

}


void main(){

int x, y;

int lcm, gcd;

printf("두 개의 정수를 입력하시오 : ");

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

get_gcd(x, y);

get_lcm_gcd(x, y, &lcm, &gcd);

printf("두 수의 최소공배수는 %d이고 최대공약수는 %d 이다", lcm, gcd);

}


11.

#include <stdio.h>

#define SIZE 4


void merge(int *A, int *B, int *C, int size){


int i, a=0, b=0;


for(i=0; i<size*2; i++){

if(a<size && b<size){

if(A[a]<=B[b]){

C[i]=A[a];

a++;

}

else if(A[a]>B[b]){

C[i]=B[b];

b++;

}

}

else if(a==size){

C[i]=B[b];

b++;

}

else if(b==size){

C[i]=A[a]; 

a++;

}

}

}


void main(){


int A[SIZE] = {2, 5, 7, 8};

int B[SIZE] = {1, 3, 4, 6};

int C[SIZE*2]={0};

merge(A, B, C, SIZE);

print_merge(A, SIZE);

print_merge(B, SIZE);

print_merge(C, SIZE*2);

}


void print_merge(int *A, int size){

int i;

static ch = 'A';

printf("%c[] = {" , ch);

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

if (i==size-1) printf("%d }\n", A[i]);

else printf("%d, ", A[i]);

}

ch++;

}

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

11장 Exercise


1. (a) 처럼 바꾸시오

(a) list[6] -> *(list+6)
(b) name[3] ->*(name+3)
(c) *(cost+8) -> cost[8]
(d) message[0] -> *message

비고) a+i는 &a[i]와 같고, *(a+i)는 a[i]와 동일하다


2. 알맞은 문장 넣기

char code;
char *p;        // char형 포인터 p선언
p=&code;     // 포인터에 변수 code의 주소 대입
*p='a';          // 포인터를 통하여 변수 code에 'a' 대입하기


3. int a[]={10, 20, 30, 40, 50}으로 정의되었다고 가정할 때, *(a+2)의 값은?     ③30


4. 아래의 문장이 실행되었을 때 다른 문장들과 실행 결과가 다른것은?         ③*p++

int i;
int *p=&i;

비고) ③*p++은 p가 가르키는 i값을 가져오고 p를 1증가시키는 것이다.
        ①②④ i를 1 증가한다.
        int *p=&i;  =  int *p;  +  p=&i;


5. 다음 프로그램의 출력은?                                5, 6

 int x=6;
int *p=&x;
printf("%d\n", --(*p));
printf("%d\n", (*p)++);


6. 다음 프로그램의 출력은?                             1008, 2008

int *p = (int *)1000;
double *q = (double *)2000;
printf("%d\n", p+2);
printf("%d\n", q+1);

비고) 결과값 : x+sizeof(x)*integer


7. 다음 프로그램의 출력은?                         0, 1, 2   

int list[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *p;
p=list;
printf("%d\n", *list);
printf("%d\n", *p+1);
printf("%d\n", *p+2);

비고) %d대신 %x로 바꾸고 *을 제거하면 주소들이 출력된다.


8. double형 배열을 매개 변수 a로 전달받는 함수 print_array()의 헤더를 다음과 같은 방법으로 작성하라. 반환값은 없다.

 (a) b를 배열로 선언 

 print_array(double a[]);

 (b) b를 포인터로 선언

 print_array(double *a); 


9. 다음 프로그램에서 ip의 값이 변경되지 않는 이유는 무엇인가?

void f(int *p)
{
static int data 5;
p=&data;
}

int main()
{
int*ip=NULL;
f(ip;)
}


모든 변수는 메모리에 값을 저장한다. 주소로 각각의 위치를 구별하여 저장하며 포인터 변수는 메모리의 주소를 지정하는 값을 가진다. 정적변수 역시 메모리에 배치되고 주소값을 가진다. 그러나 기계어 코드에 주소값을 고정하여 액세스된다. 즉 정적변수를 가르키는 포인터는 가르키는 주소값이 정적변수에 의해 고정되어 변경되지 않게 된다.


블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

11장 Summary


메모리는 이터를 기준으로 주소가 매겨진다

포인터는 메모리의 주소를 저장할 수 있는 변수이다

변수 x의 주소를 추출하려면 printf("x의 주소: %p", &x);라고 하면 된다.

int *p의 의미는 정수를 가르키는 포인터이다

int 형 포인터 p가 가리키는 위치에 100을 저장하는 문장은 *p=100;이다

포인터가 아무것도 가리키고 있지 않는 경우에는 NULL값을 넣어두는 편이 좋다

배열 a에서 a는 첫번째 원소(=a[0])의 주소이다.         
                    ★열의 이름은 첫번째 원소를 가르키는 포인터(포인터상수)와 같다

P가 포인터라면 p[2]는 수식 *(p+2)와 같다
                    ★a+i는 &a[i]와 같고, *(a+i)는 a[i]와 동일하다

*p++의 의미는 p가 가르키는 값을 가져온 후에 p를 증가한다.

   ★(*p)++ : p가 가르키는 값을 가져온 후에 가르키는 값을 증가한다.
       *++p : p를 증가시킨 수에 p가 가르키는 값을 가져온다
       ++*p : p가 가르키는 값을 증가시킨 후에 가져온다

사칙 연산 중에서 포인터에 대하여 적용할 수 있는 연산에는 덧셈과 뺄셈 이 있다.

int형 포인터 p가 80번지를 가리키고 있었다면 (p+1)은 84번지를 가리킨다

함수 호출시 인수 전달 방법 중에서 기본적인 방법은 "에 의한 호출"이다.

값에 의한 호출(call-by-value)은 복사본이 전달되고
   이 방법만 C에서 지원한다.
 
★참조에 의한 호출(call-by-reference)은 원본이 전달되고
   포인터를 이용해 간접구현이 가능하다.

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,

10장 Programming


1.

#include <stdio.h>


void main()

{

int i;

int days[]={31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

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

printf("%02d은 %d일까지 있습니다.\n", i+1, days[i]);

}



2.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>


void main()

{

srand((unsigned)time(NULL));

int i,j, least, temp, array[10];

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

array[i] = rand()%100;

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

{

least = i;

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

if(array[j] < array[least])

least = j;

temp = array[i];

array[i] = array[least];

array[least] = temp;

}

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

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

printf("\n");

printf("최소값은 %d이고 최대값은 %d입니다.", array[0], array[9]);

}



3.

#include <stdio.h>

#define SIZE 2


int array_equal(int a[], int b[], int size)

{

int i, result=0;

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

{

if(a[i]==b[i]) result += 1;

else  result += 0;

}

return result;

}


void main()

{

int a[]={1, 2};

int b[]={1, 2};

if(array_equal(a, b, SIZE)==SIZE)

printf("원소가 같다.\n");

else

printf("원소가 다르다.\n");

}



4.

#include <stdio.h>
#define SIZE 2

void array_copy(int a[], int b[], int size)
{
int i;
for(i=0; i<SIZE; i++)
{
b[i]=a[i];
printf("%d ", b[i]);
}
}

void main()
{
int a[]={1, 2};
int b[SIZE];
array_copy(a, b, SIZE);
}

5.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define SIZE 10


void main()

{

srand((unsigned)time(NULL));

int i, max=0, a[SIZE]={0};        // 0으로 초기화 하지 않으면 쓰레기값이 들어간다

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

a[rand()%SIZE]++;

printf(" 난수 빈도수\n");

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

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

{

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

if(a[i]>a[max])

max=i;

}

printf("가장 많이 생성된 수는 %d이다", max);

}


6.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define ROW 3

#define COL 5


void main()

{

srand((unsigned)time(NULL));

int i, j, sum=0, a[ROW][COL]={0};

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

{

for(j=0; j<COL; j++)

printf("%4d ", a[i][j]=rand()%100);

printf("\n");

}

printf("\n");

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

{

for(j=0; j<COL; j++)

sum+=a[i][j];

printf("%d행의 합은 %d입니다.\n", i+1, sum);

}

sum=0;

printf("\n");

for(j=0; j<COL; j++)

{

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

sum+=a[i][j];

printf("%d열의 합은 %d입니다.\n", j+1, sum);

}

}


7.

#include <stdio.h>

#define ROW 10

#define COL 3


void main()

{

int i, n, result=0, a[ROW][COL]={0};

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

{

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

a[i][2]=(i+1)*(i+1);

a[i][3]=(i+1)*(i+1)*(i+1);

}

printf("정수를 입력하시오: ");

scanf("%d", &n);

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

{

if(n==a[i][3])

{

printf("%d의 세제곱근은 %d", n, a[i][1]);

result=1;

break;

}

}

if (result==0)

printf("해당 정수의 세제곱근은 배열에 없습니다.");

}


8.

#include <stdio.h>      // 함수 통합

#include <stdlib.h>

#include <time.h>

#include <math.h>

#define SIZE 10


void main()

{

srand((unsigned)time(NULL));

int i, sum=0, a[SIZE]={0};

float mean, sd;

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

{

printf("데이터를 입력하시오: %d\n", a[i]=rand()%100);

sum+=a[i]; 

}

printf("\n");

mean = sum/SIZE;

printf("평균값은 %f\n", mean);

sum=0;

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

sum+=(a[i]-mean)*(a[i]-mean);

sd = sqrt(sum/SIZE);

printf("표준편차값은 %f\n", sd);

}


============================================

#include <time.h>        // 함수 분할

#include <math.h>

#define SIZE 10


float mean(int a[], int n);

void sd(int a[], int n, float mean);


void main()

{

srand((unsigned)time(NULL));

int i, a[SIZE]={0};

float m;

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

printf("데이터를 입력하시오: %d\n", a[i]=rand()%100);

m=mean(a, SIZE);

sd(a, SIZE, m);

}


float mean(int a[], int n)

{

int i, sum=0;

float mean;

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

sum+=a[i];

mean=sum/SIZE;

printf("평균값은 %f\n", mean);

return mean;

}


void sd(int a[], int n, float mean)

{

int i, sum=0;

float sd;

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

sum+=(a[i]-mean)*(a[i]-mean);

sd = sqrt(sum/SIZE);

printf("표준편차값은 %f\n", sd);

}



9.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define ROW 5

#define COL 3


void exam(int grade[][COL]);


void main()

{

srand((unsigned)time(NULL));

int i, j, grade[ROW][COL]={0};

printf("학번  #1  #2  #3\n");

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

{

for(j=0; j<COL; j++)

grade[i][j]=rand()%101;

printf("%3d  %3d %3d %3d\n", i+1, grade[i][0], grade[i][1], grade[i][2]);

}

printf("\n");

exam(grade);

}


void exam(int grade[][COL])

{

int i, j, min, max;

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

{

min=0, max=0;

for(j=0; j<COL; j++)

{

if(grade[i][j]<grade[i][min])

min=j;

else if (grade[i][j]>grade[i][max])

max=j;

}

printf("%d번 학생의 최대 점수는 %d, 최소 점수는 %02d 이다.\n", i+1, grade[i][max], grade[i][min]);

}

}


10.

#include <stdio.h>


void vector_add(double x[], double y[], double z[])

{

int i;

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

{

z[i] = x[i] + y[i];

printf("%4lf ", z[i]);

}

printf("\n");

}


void vector_dot(double x[], double y[])

{

int i;

double sum=0;

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

sum += x[i]*y[i];

printf("%lf", sum);

}

void main()

{

double x[3]={1, 2, 3};

double y[3]={4, 5, 6};

double z[3]={0};

vector_add(x, y, z);

vector_dot(x, y);

}



11.

#include <stdio.h>


void main()

{

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

while(1)

{

printf("찾고자 하는 상품 번호를 입력하시오(종료: -1) : ");

scanf("%d", &n);

if(n==-1) return 0; 

printf("%d번 상품은 %d번 장소에 있습니다.\n", n, a[n-1]);

}

}


12.

#include <stdio.h>


void scalar_mult (int a[][3], int scalar)

{

int  i, j;

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

{

for(j=0; j<3; j++)

printf("%2d ", a[i][j]*scalar);

printf("\n");

}

}


void transpose(int a[][3], int b[][3])

{

int i, j;

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

{

for(j=0; j<3; j++)

{

b[i][j] = a[j][i];

printf("%2d", b[i][j]);

}

printf("\n");

}

}


int main(void) 

{

int a[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

int b[][3]={0};

scalar_mult(a, 2);

printf("\n");

transpose(a, b);

return 0;

}


13.★★★

#include <stdio.h>


void main()

{

int i, n, binary[32]={0}, count=0;

printf("10진수를 입력하시오 : ");

scanf("%d", &n);

for(i=0; i<32 && n>0; i++)

{

binary[i]=n%2;

n=n/2;

count++;

}

printf("변환된 2진수 값: ");

for(i=count-1; i>=0; i--)

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

}



14.★★★

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define ROW 20

#define COL 20


int main()

{

srand((unsigned)time(NULL));

int i, j, n, m;

int visit, count=0;

int tile[ROW][COL]={0}; 

n=ROW/2, m=COL/2;

tile[n][m]=1;

while(1){

visit=0;

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

{

for(j=0; j<COL; j++)

{

if(tile[i][j]==1)

visit++;

}

}

if(visit==ROW*COL) break;

switch(rand()%8){

case 0 : 

if(n==0) break;

tile[n--][m]=1; 

count++; 

break;

case 1 : 

if(n==0 || m==COL-1) break;

tile[n--][m++]=1; 

count++; 

break;

case 2 : 

if(n==0 || m==COL-1) break;

tile[n][m++]=1; 

count++; 

break;

case 3 : 

if(n==ROW-1 || m==COL-1) break;

tile[n++][m++]=1; 

count++; 

break;

case 4 : 

if(n==ROW-1) break;

tile[n++][m]=1; 

count++; 

break;

case 5 : 

if(n==ROW-1 || m==0) break;

tile[n++][m--]=1; 

count++; 

break;

case 6 : 

if(m==0) break;

tile[n][m--]=1; 

count++; 

break;

case 7 : 

if(n==0 || m==0) break;

tile[n--][m--]=1; 

count++; 

break;

}

}

printf("딱정벌레의 총 이동수는 %d입니다.", count);

return 0;


15.

#include <stdio.h>

#define SIZE 100


void main()

{

int seive[SIZE]={0};  

int i, j;

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

{

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

{

if(j%i==0)

seive[j]=1;

}

}

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

{

if(seive[i]==0)

printf("%d ", i);

}

}

블로그 이미지

얼음꿀차

책을 한 번 읽긴 읽어야겠는데 막상 읽자니 뭘 읽을지 고민되는 당신을 위해 읽을만한 책들을 알려드립니다!

,