How to repeat a piece of text?

Nov 9, 2008 at 2:34pm
How do i repeat a piece of text

like..

cout<<"APPLE PIE"<<endl;

and now i want it to be written 20 times.
Please help.
Nov 9, 2008 at 2:36pm
Nov 9, 2008 at 2:52pm
Ok tnx i get it...

1
2
3
4
5
for(int n(1);n<=10;n++)
                 {
                          cout<<"APPLE PIE"<<endl;

                          }


But why doesn't this work?
1
2
3
4
5
6
for(int n(1);n<=10;n+1)
                 {
                          cout<<"APPLE PIE"<<endl;
                          }
                
Nov 9, 2008 at 3:08pm
i dont recognize this: n(1), that probably should be n=1, and n+1 should be n+=1 or simply n++: when you write n+1 you dont update the value of n, that statement would just return 2 (since you intialized n as 1)
Nov 9, 2008 at 3:26pm
int n(1) - it's ok, but in my opinion is better use type var = something; for bullit-in types.
Last edited on Nov 9, 2008 at 3:26pm
Nov 9, 2008 at 6:19pm
Well, actually, int n(1) is probably *slightly* faster then int n = 1. This is because when you do int n(1) will call the constructor with the value of 1, whereas int n = 1 calls the constructor with no arguments, and then will assign 1 to n.
Nov 9, 2008 at 7:17pm
Nay. The compiler does not actually generate any code to default construct an int (other than perhaps a sub of the stack pointer to allocate space).

The reason mastuh8's second code doesn't work is the last expression in the for loop:

n+1

This creates a temporary variable which is assigned the value of n, then the temporary is incremented by one, and finally since the value of the expression isn't used, the temporary is thrown away. Upshot: n is never itself incremented.

Nov 10, 2008 at 1:43pm
n++ is the same as n=n+1

n+1 doesn't work because because n does increase in value. it says at 2.
Topic archived. No new replies allowed.