forked from DlangRen/Programming-in-D
-
Notifications
You must be signed in to change notification settings - Fork 1
/
do_while.d
91 lines (62 loc) · 2.14 KB
/
do_while.d
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
Ddoc
$(DERS_BOLUMU $(IX do-while) $(IX loop, do-while) $(CH4 do-while) Loop)
$(P
In the $(LINK2 /ders/d.en/for.html, $(C for) Loop chapter) we saw the steps in which the $(LINK2 /ders/d.en/while.html, $(C while) loop) is executed:
)
$(MONO
preparation
condition check
actual work
iteration
condition check
actual work
iteration
...
)
$(P
The $(C do-while) loop is very similar to the $(C while) loop. The difference is that the $(I condition check) is performed at the end of each iteration of the $(C do-while) loop, so that the $(I actual work) is performed at least once:
)
$(MONO
preparation
actual work
iteration
condition check $(SHELL_NOTE at the end of the iteration)
actual work
iteration
condition check $(SHELL_NOTE at the end of the iteration)
...
)
$(P
For example, $(C do-while) may be more natural in the following program where the user guesses a number, as the user must guess at least once so that the number can be compared:
)
---
import std.stdio;
import std.random;
void main() {
int number = uniform(1, 101);
writeln("I am thinking of a number between 1 and 100.");
int guess;
do {
write("What is your guess? ");
readf(" %s", &guess);
if (number < guess) {
write("My number is less than that. ");
} else if (number > guess) {
write("My number is greater than that. ");
}
} while (guess != number);
writeln("Correct!");
}
---
$(P
The function $(C uniform()) that is used in the program is a part of the $(C std.random) module. It returns a random number in the specified range. The way it is used above, the second number is considered to be outside of the range. In other words, $(C uniform()) would not return 101 for that call.
)
$(PROBLEM_TEK
$(P
Write a program that plays the same game but have the program do the guessing. If the program is written correctly, it should be able to guess the user's number in at most 7 tries.
)
)
Macros:
SUBTITLE=do-while Loop
DESCRIPTION=The do-while loop of the D programming languageh and comparing it to the while loop
KEYWORDS=d programming language tutorial book do while loop