Saturday, May 22, 2010

C++ Help - Triangle problem?

Hey. I'm trying to do a program for school, and I'm haveing for loop problems. I'm trying to make a triangle that looks like this...





AC


A C


A C


A C


ABBB


something like that. Anyway, I basically need to add another space between the A and C in each new row. I was thinking if I did something like





(for int j=0, j%26lt;N, j++)


{


cout %26lt;%26lt; var1 NUMSPACES var3 %26lt;%26lt; endl;


}


Is there a way I can make a variable represent spaces? Like, NUMSPACES = 0, and have the code know that 0 is the number of spaces? so when I change it to NUMSPACE = 2, it knows that I want two spaces?

C++ Help - Triangle problem?
Not sure if anybody should be answering this, but I'll give some useful pointers.





First, you could do something like the following to write out one space:


cout %26lt;%26lt; var1;


cout %26lt;%26lt; ' ';


cout %26lt;%26lt; var2;


cout %26lt;%26lt; endl;





Now just find a why to execute the line with the spaces the number of times you need it. (hint: this exercise is meant to teach you about nested loops)





For extra points, 'NUMSPACES' could be a variable, but maybe not of the number of spaces. Rather, think of what other types a variable has.





Oh and in python one could indeed do something like " "*3 and get 3 spaces. But that's just a shorthand.
Reply:Perhaps this is overcomplicating things? Just change the value for baseSize to make it bigger/smaller.





void outLine(char, char, char, int);


int baseSize=4;


int main(int argc, char* argv[]) {


for (int n=0; n%26lt;baseSize; n++) {


outLine('A',' ','B',n);


}


outLine('A','B','B',baseSize);


return 0;


}





void outLine(char bChar, char fChar, char eChar, int baseWide) {


cout %26lt;%26lt; bChar;


for (int j=0; j%26lt;=baseWide; j++) {


cout %26lt;%26lt; fChar;


}


cout %26lt;%26lt; eChar %26lt;%26lt; endl;


}


No comments:

Post a Comment