May 31, 2013 Why do i have to add to the counter when using for loop to perfectly get result? | ||||
|---|---|---|---|---|
| ||||
/* licenced under the wtfpl license :D... as if i even understand how to license*/
import std.stdio;
void main(){
//yeah... im making a diamond pattern out off asterisks
writeln("Pick a number that is odd");
int chosen;
bool oddnoteven = false;
while(oddnoteven == false){
write("Enter number here: ");
readf(" %s", &chosen);
int numbercheck = chosen % 2;
if(numbercheck == 0){
writeln("I really don't like even numbers mofo >:/... Just odd ones.. Try again? :D");
}
else{
oddnoteven = true;
}
}
int peak = (chosen + 1)/2;
for(int counter = 0; counter < chosen + 1; ++counter){ // my fro block
//Ok its not broken DO NOT KILL THE BLOCK!!!!!
if(counter < peak){
int spacesneeded = (peak - counter) - 1;
for(int spacesmade = 0 ; spacesmade < spacesneeded; ++spacesmade ){
write(" ");
}
int shotsneeded = (2*counter) + 1;//(countxXXXerx + 1) +x (counterx + 1)/xxxxx2; uhh nope
for(int shotsmade = 0; shotsmade < shotsneeded; ++shotsmade){
write("*");
}
writeln();
}
//hmmm bastard block... >:/
if(counter > peak){
int spacesneeded = (counter - peak);
for(int spacesmade = 0; spacesmade < spacesneeded; ++spacesmade){
write(" ");
}
int shotsneeded = (2*(chosen - counter))+ 1;
for(int shotsfired = 0; shotsfired < shotsneeded; ++shotsfired){
write("*");
}
writeln();
}
}
}
ok i know its bad math, hope its not too much of a waste of serv space. so can someone shoot me an explain about why in my "fro block" i hav to add "+1" to chosen to perfectly make the diamond shape.. but it i take out the " + 1" it cuts of the last print... help please :(
| ||||
May 31, 2013 Re: Why do i have to add to the counter when using for loop to perfectly get result? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Tori | Well, after a quick glance at the code you're iterating N times but only printing N-1 times. When counter == peak the loop does nothing so you'd get something like:
chosen=5
for(int counter = 0; counter < chosen ; ++counter){ // note +1 removed }
counter = 0, 1, 2, [3]NO_PRINT, 4
*0
***1
*****2
***4
(note: my ascii art, I assume this is what the code would produce...)
Now add the +1
for(int counter = 0; counter < chosen +1 ; ++counter){
0, 1, 2, [3]skip, 4, 5
*0
***1
*****2
***4
*5
With your implementation as it stands you need to skip iteration N/2+1 to get the correct output. But you still need to write N lines.
Hope that makes sense...!! :D
Stewart
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply