I'm supposed to write a function that takes an input, and then outputs a set number of digits based on an array. The code I have works for the numbers 1-10, but anything above that messes up because it goes on to a value that doesn't exist in the array. I'd like for the program to handle values up to 127.

The problem isn't limiting inputs, it's just I have no idea how to make it go above 10 without going wonky.

For example:
Input Output
0 0
9 0123456789
19 01234567890123456789
25 01234567890123456789012345

#include <iostream>
using namespace std;


int main(){
int input;
int num[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cin >> input;
cout << endl;
int i;
for(i=0;i<input;i++){
cout << num[i];
}}

Recommended Answers

All 4 Replies

Its much easier than you are making it.

cin >> limitNum;

for(int i = 0; i < limitNum; i++) 
    cout<<i<<" ";

Thanks for the reply, but that isn't what I was trying to do.

The output isn't just the number of the counter, it's the particular digit in an array. Once it gets above 10, it's supposed to loop back to 0 and start over.
Input/Output
0 | 0
9 | 0123456789
19 | 01234567890123456789
25 | 01234567890123456789012345

Picture attached with an input of 14, which should show up as 01234567890123

http://i27.tinypic.com/2le6hj6.jpg

Thanks for the reply, but that isn't what I was trying to do.

The output isn't just the number of the counter, it's the particular digit in an array. Once it gets above 10, it's supposed to loop back to 0 and start over.
Input/Output
0 | 0
9 | 0123456789
19 | 01234567890123456789
25 | 01234567890123456789012345

Picture attached with an input of 14, which should show up as 01234567890123

http://i27.tinypic.com/2le6hj6.jpg

Extract the ones digit by using the % operator.

for(i=0;i<input;i++){
cout << i % 10;

Edit:
I don't see the need for an array here. Am I missing something?

Extract the ones digit by using the % operator.

for(i=0;i<input;i++){
cout << i % 10;

Edit:
I don't see the need for an array here. Am I missing something?

It was the way it was described in the assignment, but since that works perfectly I'll just do that. Thanks!

Edit: Actually, I found a problem. When inputting 0 it shows up with nothing, when it's supposed to show 0. Suppose it can be fixed by messing with the cin.

Finished code.

#include <iostream>
using namespace std;


int main(){
int input, i;
do{
cout << "Please input a number between 0 and 127\n";
cin >> input;
cout << endl;
}while(input<0 || input>127);
input=input+1;
for(i=0;i<input;i++)
cout << i % 10;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.