{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

The Multiplication Example

The Multiplication Example - The Multiplication Example...

This preview shows pages 1–7. Sign up to view the full content.

The Multiplication Example

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Problem Given two int variables x and y , set the int variable z to their product Note: we have to solve this problem without using the * (multiplication) operator in C.
Solution 1 (repeated addition) int z = 0; int k = 0; while (k < y) { z = z + x; k = k + 1; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
How did we arrive at this program? First, we needed to have an algorithm. In this case, our algorithm was: “Add x to itself y times” From this algorithm, we realized that we needed a loop This is the “do IT y times” kind of loop. The program is easy to write. Just recognize that IT is “z = z + x;” and plug into the template for that loop idiom.
Is this a good program? The program is fine Easy to understand, that’s by far the most important criterion for evaluating programs The algorithm is awful Awfully slow anyway The program may have to do many, many iterations of the loop to find the answer We should probably rewrite the program using a smarter algorithm

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
A better algorithm
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 11

The Multiplication Example - The Multiplication Example...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online