08-22-2006, 06:15 AM | #1 (permalink) |
Groovy Hipster Nerd
Location: Michigan
|
Solve this simple programming assignment
Alright, this might be a simple programming solution for most, but I would like to know what you would do the following question:
Design the logic for a module that would print number 1 through 10 along with its square and cube. Example: Printonethroughten() Number = 1 While number <= 10 Print number Number = number + 1 End while Return This was the example given and I assumed, one would have to do this to get the square Printonethroughten() number = 1 while number <= 10 print number number = number + 1 * number End while Return Cube Printonethroughten() number = 1 while number <= 10 print number number = number + 1 * number * number End while Return --- Was the above solution the correct answers or incorrect answers? |
08-22-2006, 06:46 AM | #2 (permalink) | |
Lover - Protector - Teacher
Location: Seattle, WA
|
A few things -- depending on your language you should have a "for()" construct. It's designed for iterative loops like the one you have -- you don't have to manually increment the value.
It'd be something like for (number =0; number < 10; number++). Everytime through the loop, the number would increment. Using the for construct you can avoid the strange +1 math you're trying to do - because right now your cube has a serious problem. Quote:
Number starts at 1, number is less than 10. 1 is printed. Number becomes 2. (Check your order of operations -- mult before add). Number is still less than 10. 2 is printed. Number becomes 2 + 1 * 2 * 2 = 6. Number is less than 10, and 6 is printed. In three iterations you've printed 1, 2, 6. That's hardly the cubes. And assuming you also can't use the math libraries of your language, I'd still combine those into one function: printNums() { // for the numbers 1 through 10, increment by 1 // Print the number // Print number*number // Print number*number*number } The biggest reason to go this way is that you're not printing it three seperate times. Unless the assignment explicitly requires it, you don't have to store the intermediate values. I've left it in psuedo-code because of my sneaking suspicion that this is a homework problem.
__________________
"I'm typing on a computer of science, which is being sent by science wires to a little science server where you can access it. I'm not typing on a computer of philosophy or religion or whatever other thing you think can be used to understand the universe because they're a poor substitute in the role of understanding the universe which exists independent from ourselves." - Willravel Last edited by Jinn; 08-22-2006 at 06:51 AM.. |
|
Tags |
assignment, programming, simple, solve |
|
|