a better way to write this?

Hi,
I'm supposed to write a code which accepts an integer n(between 0-10) and then each character in my array is duplicated by that number. I've written a code that works, however its really long and i know this is a better way to write it.
I've been trying to only use two for loops and then increment the array, but for some reason i cant figure it out. Spaces are not supposed to be duplicated.
thanks to anyone who helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  #include "stdafx.h"

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

#include <iostream>
using namespace std;
int main()
{
	unsigned int n;
	const char mystring[] = "This is a string of length 30";

	cout << "Please enter a number between 0 and 10:" << endl;
	cin >> n;
	if (n < 0 || n>10)
	{
		cout << "error" << endl;	
	}
	else{
		
		for (int i = 0; i < n; i++)
			cout << mystring[0];
		for (int i = 0; i < n; i++)
			cout << mystring[1];
		for (int i = 0; i < n; i++)
			cout << mystring[2];
		for (int i = 0; i < n; i++)
			cout << mystring[3];
		for (int i = 0; i < n; i++)
			cout << mystring[5];
		for (int i = 0; i < n; i++)
			cout << mystring[6];
		for (int i = 0; i < n; i++)
			cout << mystring[8];
		for (int i = 0; i < n; i++)
			cout << mystring[10];
		for (int i = 0; i < n; i++)
			cout << mystring[11];
		for (int i = 0; i < n; i++)
			cout << mystring[12];
		for (int i = 0; i < n; i++)
			cout << mystring[13];
		for (int i = 0; i < n; i++)
			cout << mystring[14];
		for (int i = 0; i < n; i++)
			cout << mystring[15];
		for (int i = 0; i < n; i++)
			cout << mystring[17];
		for (int i = 0; i < n; i++)
			cout << mystring[18];
		for (int i = 0; i < n; i++)
			cout << mystring[20];
		for (int i = 0; i < n; i++)
			cout << mystring[21];
		for (int i = 0; i < n; i++)
			cout << mystring[22];
		for (int i = 0; i < n; i++)
			cout << mystring[23];
		for (int i = 0; i < n; i++)
			cout << mystring[24];
		for (int i = 0; i < n; i++)
			cout << mystring[25];
		for (int i = 0; i < n; i++)
			cout << mystring[27];
		for (int i = 0; i < n; i++)
			cout << mystring[28];





	}


	system("pause");
	return 0;
}
Last edited on
There certainly is! Loops were made for arrays after all. :P
1
2
3
for (int i = 0; i < strlen(mystring); ++i) //for every letter in mystring
    for (int j = 0; j < n; j++) //output it to the console j number of times
        cout << mystring[i];
Last edited on
wow thank you so much!! thats exactly what i was trying to do! :)
Topic archived. No new replies allowed.