본문 바로가기

리눅스 C언어

코딩 연습 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
int main()
{
    char car[5][10= {"포르쉐""페라리""쉐보레""벤틀리""맥라렌"};
    char tmp[10];
    int i, j, n = sizeof(car)/sizeof(char[10]);
    
    //원본출력
    puts(" * 원본 출력 *");
    for (i=0; i<n; i++)
        printf(" car[%d] ==> %s \n", i, car[i]); 
    
    //정렬
    for (i=0; i<n-1; i++)
    {
        for (j=0; j<n-i-1; j++)
        {
            if (strcmp(car[j], car[j+1]) > 0)
            {
                strcpy(tmp, car[j]);
                strcpy(car[j], car[j+1]);
                strcpy(car[j+1], tmp);
            }
         }
    }
    
    //정렬 후 출력
    puts(" * 정렬 후 *");
    for (i=0; i<n; i++)
        printf(" car[%d] ==> %s \n", i, car[i]); 
    
    getchar();
    return 0;
 } 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <string.h>
typedef struct Car
{
    char mBrand[20];
    int mPrice;
}Car;
 
int main()
{
    Car c[5= { {"포르쉐"9000}, {"재규어"8000}, {"쉐보레"2500}
    , {"소나타"3000}, {"머스탱"5000} };
    
    Car tmp;
    int i, j, n = sizeof(c)/sizeof(Car);
    
    puts(" ** 원 본 출 력 ** ");
    puts("-----------------------");
    
    for (i=0; i<n; i++)
        printf(" [%d] %6s %6d만원 \n", i+1, c[i].mBrand, c[i].mPrice);
        
    puts("-----------------------");
    
    // 차 이름 순 정렬  
    for (i=0; i<n-1; i++)
    {
        for (j=0; j<n-i-1; j++)
        {
            if ( strcmp(c[j].mBrand, c[j+1].mBrand) > 0 )
            {
                tmp = c[j];
                c[j] = c[j+1];
                c[j+1= tmp;
            }
        }
    }
    
    puts(" ** 차 이름순  ** ");
    puts("-----------------------");
    
    for (i=0; i<n; i++)
        printf(" [%d] %6s %6d만원 \n", i+1, c[i].mBrand, c[i].mPrice);
        
    puts("-----------------------");
    
    // 차 가격순 정렬  
    for (i=0; i<n-1; i++)
    {
        for (j=0; j<n-i-1; j++)
        {
            if ( c[j].mPrice > c[j+1].mPrice)
            {
                tmp = c[j];
                c[j] = c[j+1];
                c[j+1= tmp;
            }
        }
    }
    
    puts(" ** 차 가격 순 ** ");
    puts("-----------------------");
    
    for (i=0; i<n; i++)
        printf(" [%d] %6s %6d만원 \n", i+1, c[i].mBrand, c[i].mPrice);
        
    puts("-----------------------");
     
    return 0;
 } 
cs





'리눅스 C언어' 카테고리의 다른 글

코딩 연습 2  (0) 2019.01.06
C 언어 - 4  (0) 2019.01.06
C 언어 - 3  (0) 2019.01.06
C 언어 - 2  (0) 2019.01.06