![]() |
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? |
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. :) |
You are correct, it is a homework problem. I was helping out a friend and came to the same conclusion as you did, but I thought it was incorrect, so I put down my first answer, which was incorrect. Thanks for the help.
|
in java...
for (int i = 1; i < 11; i++) { System.out.println("Number: " + i + ",Square: " + (i * i) + ",Cube: " + (i*i*i)); } |
All times are GMT -8. The time now is 09:38 AM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project