軟體實作與計算實驗 1 While-loop flow chart Decimal to binary representations Lecture 6 While-Loop programming
軟體實作與計算實驗 2 While loop statements false while entry_condition statements; end EC end
軟體實作與計算實驗 3 Flow chart statements false Execute body statements repeatedly until the entry condition fails The entry condition should eventually become false by iteratively executing body statements EC end
軟體實作與計算實驗 4 Decimal to binary representations Input : positive decimal numbers Output : binary representations of the input
軟體實作與計算實驗 5 Modulus: find remainder >> rm=mod(10,3) ans = 1 >> rm=mod(100,7) ans = 2
軟體實作與計算實驗 6 Quotient >> quo=floor(100/7) ans = 14 >> quo=floor(10/3) ans = 3
軟體實作與計算實驗 7 Decimal to binary representation Let M be a positive decimal number Let b be an array of length n b denotes the binary representation of M if
軟體實作與計算實驗 8 Example M > 0 M=1, b 1 =1 M=5, 1 01 C=‘101’
軟體實作與計算實驗 9 Example M=25, C: ‘11001’ The problem is to find b for given M
軟體實作與計算實驗 10 Example M > 0 M=1, b 1 =1 M=5, b=[1 0 1] M=25, b=[ ] The problem is to find b for given M
軟體實作與計算實驗 11 Decimal to binary representation Given M>0, find array b Strategy : Iteratively find b 1,b 2,…,b n Append from left to b
軟體實作與計算實驗 12 Find b 1 r = mod(q,2); q_new = (q-r)/2; remainder
軟體實作與計算實驗 13 Find b 2 r = mod(q,2); q_new = (q-r)/2; Append remainder from left-hand-side
軟體實作與計算實驗 14 Find b i r = mod(q,2); q_new = (q-r)/2; Append remainder from left-hand-side
軟體實作與計算實驗 15 An iterative approach q=M; b=[]; Calculate r, q new and b i iteratively Append b i to b from left-hand-side q q new until q equal zero return b
軟體實作與計算實驗 16 Strategy statements true EC end q=M; b=[]; Calculate r, q new and b i iteratively Append b i to b from left-hand-side q q new until q equal zero return b
軟體實作與計算實驗 17 An iterative approach q=M; b=[]; Calculate r, q new and b i iteratively Append b i to b from left-hand-side q q new until q equal zero return b Calculate r, q new and b i Append b i to b from left-hand-side q q new true q>0 end q=M; b=[]
軟體實作與計算實驗 18 Calculate r Append r to b from left-hand-side Update q An iterative approach q=M; b=[]; Calculate r, q new and b i iteratively Append b i to b from left-hand-side q q new until q equal zero return b true q>0 end q=M; b=[]
軟體實作與計算實驗 19 Entry condition q > 0 Halt if q==0
軟體實作與計算實驗 20 Determine b r = mod(q,2); b=[r b]; q = (q-r)/2; true q > 0 end q=M;b=[];
軟體實作與計算實驗 21 Change base r = mod(q,2); b=[r b]; q = (q-r)/2; true q > 0 end q=M;b=[]; r = mod(q,base); b=[r b]; q = (q-r)/base; true q > 0 end q=M;b=[];base=2
軟體實作與計算實驗 22 Decimal to Octal representation r = mod(q,base); b=[r b]; q = (q-r)/base; true q > 0 end q=M;b=[];base=8
軟體實作與計算實驗 23 >> dec2oct(7) ans = 7 >> dec2oct(8) ans = 1 0
軟體實作與計算實驗 24 >> dec2oct(18) ans = 2 2 >> dec2oct(64) ans = 1 0 0