180 likes | 300 Views
Iteration & Branching. CSC 171 FALL 2001 LECTURE 5. 1854 - George Boole describes his system for symbolic and logical reasoning: An Investigation into the Laws of thought Boolean logic later becomes the basis for computer design. History Boolean Logic. Quote.
E N D
Iteration & Branching CSC 171 FALL 2001 LECTURE 5
1854 - George Boole describes his system for symbolic and logical reasoning: An Investigation into the Laws of thought Boolean logic later becomes the basis for computer design HistoryBoolean Logic
Quote “No matter how correct a mathematical theorem may appear to be, one ought never to be satisfied that there was not something imperfect about it until it also gives the impression of being beautiful.” George Boole - Quoted in D MacHale, Comic Sections (Dublin 1993)
Boolean Logic • Boolean expressions • boolean expressions can take on one of two values (true or false) • 3 <= 5 • true • 3 > 5 • false
Boolean Variables int x = 5, y = 3; boolean test1, test2, test3, test4; test1 = x < y ; test2 = x >= y; test3 = test1 && test2; test4 = test1 || test 2;
The mathematical basis for computer design • An open switch can represent • Zero • False • A closed switch can represent • One • True • A switch can control another switch • A logic gate
Boolean Operations & Circuits • And • Or • Not X
Branching Logic if (earnings < 50000.00) { tax = income * 0.35; } else { tax = income * 0.45; } netpay = earnings – tax;
While repetition int count = 0; while (count < 10) { sum += count; count++; }
Design Technique • State the problem • Write a pseudocode algorithm • Code around the comments
Example Decimal to binary • Start with an integer value “x” and an empty string • While the value of x is greater than zero • If x is odd, prepend a “1” to the string • If x is even, prepend a “0” to the string • Divide the value of x by 2
Example: Decimal to Binary int x = 10; // Start with an integer value “x” String binstring = “”; // and an empty string while (x > 0) { // While x is greater than zero if ((x % 2) == 0) { // If x is odd, binstring = “ 1” + binstring; // prepend a “1” } else { // If x is even binstring = “ 0” + binstring; // prepend a “0” } x /= 2; // Divide the value of x by 2 }
Trace at the top of the loop • x==10, binstring ==“”, (x%2) == 0 • x==5, binstring ==“0”, (x%2)==1 • x==2, binstring ==“10”, (x%2)==0 • x==1, binstring ==“010”, (x%2)==1 • x==0, binstring ==“1010”, (x%2)==0
In class example • The user wants to know how much money he will have saved year by year for retirement. • Questions to ask • How old are you, now? • How much can you save, each year? • How old will you be when you retire? • How much do you need, during retirement? • How old will you be when you die? • What interest rate should we invest at?
In class excercise • You design the program (pair up) • Use dialog boxes for input, console for output • Identify the key variables needed • Write a pseudocode program • You have 10 minuites to do this