C Arrays

 

1. 氣泡排序

         Sorting data

        Important computing application

        Virtually every organization must sort some data

         Bubble sort (sinking sort)

        Several passes through the array

        Successive pairs of elements are compared

         If increasing order (or identical ), no change

         If decreasing order, elements exchanged

        Repeat

         Example:

        original:   3  4  2  6  7

        pass 1:      3  2  4  6  7

        pass 2:      2  3  4  6  7  

        Small elements "bubble" to the top

 

Write a program to sort an array's values into ascending order using bubble sort.

2_1.c

2_1.exe

 

(Exercise)

2. 決定中位數

Write a program to sort an array and determine median element's value.

 

   int response[ SIZE ] = { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9,

                            7, 8, 9, 5, 9, 8, 7, 8, 7, 1,

                            6, 7, 8, 9, 3, 9, 8, 7, 1, 7,

                            7, 8, 9, 8, 9, 8, 9, 7, 1, 9,

                            6, 7, 8, 7, 8, 7, 9, 8, 9, 2,

                            7, 8, 9, 8, 9, 8, 9, 7, 5, 3,

                            5, 6, 7, 2, 5, 3, 9, 4, 6, 4,

                            7, 8, 9, 6, 8, 7, 8, 9, 7, 1,

                            7, 4, 4, 2, 5, 3, 8, 7, 5, 6,

                            4, 5, 6, 1, 6, 5, 7, 8, 7, 9};

2_2.c,

2_2.exe

 

3. 模擬擲1個骰子

Write a program to simulate rolling a six-sided die 6000 times.

2_3.c,

2_3.exe

 

(Exercise)

4. 模擬擲2個骰子

Write a program to simulate rolling two six-sided dice 36000 times.

 

One\two

1

2

3

4

5

6

1

2

3

4

5

6

7

2

3

4

5

6

7

8

3

4

5

6

7

8

9

4

5

6

7

8

9

10

5

6

7

8

9

10

11

6

7

8

9

10

11

12

 

2_4.c

2_4.exe

 

5. 模擬Craps 遊戲

         Craps simulator

         Rules

        Roll two dice

         7 or 11 on first throw, player wins

         2, 3, or 12 on first throw, player loses

         4, 5, 6, 8, 9, 10 - value becomes player's "point"

        Player must roll his point before rolling 7 to win

 2_5.c

2_5.exe

 

(Exercise)

6. 模擬Craps 遊戲1000

Write a program that runs 1000 games of craps and answers each of the following questions:

a)      How many games are won on the first roll, second roll, …, twentieth roll and after the twentieth roll?

b)      How many games are lost on the first roll, second roll, …, twentieth roll and after the twentieth roll?

c)      What are the chances of winning at craps?

d)      What is the average length of a game of craps?

e)      Do the chances of winning improve with the length of the game?

 

2_6.c

2_6.exe