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.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
usingnamespace std;
#include <iostream>
usingnamespace std;
int main()
{
unsignedint n;
constchar 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;
}
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];