軟體實作與計算實驗 1 While-loop flow chart Decimal to binary representations...
date post
19-Jan-2016Category
Documents
view
258download
0
Embed Size (px)
Transcript of 軟體實作與計算實驗 1 While-loop flow chart Decimal to binary representations...
While-loop flow chart Decimal to binary representations
Lecture 6 While-Loop programming
While loopstatementsfalsewhile entry_condition statements;endECend
Flow chartstatementsfalse Execute body statements repeatedly until the entry condition fails The entry condition should eventually become false by iteratively executing body statementsECend
Decimal to binary representationsInput : positive decimal numbersOutput : binary representations of the input
Modulus: find remainder >> rm=mod(10,3)
ans =
1>> rm=mod(100,7)
ans =
2
Quotient>> quo=floor(100/7)
ans =
14>> quo=floor(10/3)
ans =
3
Decimal to binary representationLet M be a positive decimal numberLet b be an array of length n
b denotes the binary representation of M if
ExampleM > 0M=1, b1=1M=5, 101C=101
Example
M=25, C: 11001
The problem is to find b for given M11001
ExampleM > 0M=1, b1=1M=5, b=[1 0 1]M=25, b=[1 1 0 0 1]The problem is to find b for given M
Decimal to binary representationGiven M>0, find array bStrategy : Iteratively find b1 ,b2 ,,bnAppend from left to b
Find b1 r = mod(q,2);q_new = (q-r)/2;
remainder
Find b2 r = mod(q,2);q_new = (q-r)/2;Append remainder from left-hand-side
Find bi r = mod(q,2);q_new = (q-r)/2;Append remainder from left-hand-side
An iterative approachq=M; b=[];Calculate r, qnew and bi iterativelyAppend bi to b from left-hand-side q qnewuntil q equal zeroreturn b
StrategystatementstrueECendq=M; b=[];Calculate r, qnew and bi iterativelyAppend bi to b from left-hand-sideq qnewuntil q equal zeroreturn b
An iterative approachq=M; b=[];Calculate r, qnew and bi iterativelyAppend bi to b from left-hand-sideq qnewuntil q equal zeroreturn b Calculate r, qnew and bi Append bi to b from left-hand-sideq qnewtrueq>0endq=M; b=[]
An iterative approachCalculate rAppend r to b from left-hand-sideUpdate qq=M; b=[];Calculate r, qnew and bi iterativelyAppend bi to b from left-hand-sideq qnewuntil q equal zeroreturn b trueq>0endq=M; b=[]
Entry conditionEntry condition
q > 0Halt if q==0
Determine b
Change base
Decimal to Octal representation
>> dec2oct(7)
ans =
7
>> dec2oct(8)
ans =
1 0
>> dec2oct(18)
ans =
2 2
>> dec2oct(64)
ans =
1 0 0