-
April 21st, 2011, 12:55 PM
#1
generating a sequence 1, 12, 123, 1234, ...
Hi
I've been trying to write a program to generate the sequence:
1
12
123
1234
12345
...
It is the user who decides how many terms of the sequence are displayed. For example, the terms given above are five. Could you please help me with it? I think I need to use the for loop here. Given below are some random steps I put down while trying! Please help me.
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i, prevterm = 1, nexterm;
for ( i=0; i<=n; i++)
{
nexterm
cout << prevterm << prevterm
nexterm = ++prevterm
nth term = 10^(n-1)(n-1) + n
2 + (2-1) = 21
3 + 2 = 23
1
12
123
1234
12345
-
April 21st, 2011, 12:59 PM
#2
Re: generating a sequence 1, 12, 123, 1234, ...
Seems like you need two loops to me. The outer loop controls how many lines you write and the inner loop controls how many characters you write on each line. The upper bound of the inner loop will be the current iteration of the outer loop.
I can't tell what you're up to with the math you're doing in there. I don't see any math required.
Since there's nothing Visual C++ specific, this should be in the general C++ forum, not Visual C++/
-
April 21st, 2011, 01:54 PM
#3
Re: generating a sequence 1, 12, 123, 1234, ...
Thank you, GCDEF. If you think it belongs to the other sections, then you can move it there.
Best regards
H
-
April 21st, 2011, 02:06 PM
#4
Re: generating a sequence 1, 12, 123, 1234, ...
Originally Posted by heights
Thank you, GCDEF. If you think it belongs to the other sections, then you can move it there.
Best regards
H
I'm not a moderator.
-
April 21st, 2011, 02:08 PM
#5
Re: generating a sequence 1, 12, 123, 1234, ...
Originally Posted by GCDEF
I'm not a moderator.
It's okay then.
Regards
H
-
April 21st, 2011, 02:22 PM
#6
Re: generating a sequence 1, 12, 123, 1234, ...
Treat it as a string and it is fairly easy to do.
If you have to do it mathematically take note of the addition required to get to each iteration.
From 1 to 12 you add 11
From 12 to 123 you add 111 etc.
Which translates to adding 1 + 10^1, 11 + 10^2 etc.
That all works well in a for loop.
Zapper
-
April 21st, 2011, 02:26 PM
#7
Re: generating a sequence 1, 12, 123, 1234, ...
Originally Posted by zapper222
Treat it as a string and it is fairly easy to do.
If you have to do it mathematically take note of the addition required to get to each iteration.
From 1 to 12 you add 11
From 12 to 123 you add 111 etc.
Which translates to adding 1 + 10^1, 11 + 10^2 etc.
That all works well in a for loop.
Zapper
That's still more work than you need to to. All you need is two loops and output the loop counters. No math or strings required.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|