### generate new array

Hello! I have an array named a. I also have to generate an array named b which stores the first digit of each number in array a. I can get the values but I don't know how to put them into array b.

 12345678910111213 int main(){ int n, i, a[100], b[100]; cin>>n; for(i=0;i>a[i]; for(i=0;i9) a[i]/=10; //Some code... }

This is my attempt in solving the problem. I know it's not done yet.
Last edited on
Here is a program that will extract the first digit of a number > 0
 123456789101112131415 #include "iostream" using namespace std; int main() { unsigned number; cout << "Please enter a number: " << flush; cin >> number; while (number > 10) { number = number / 10; } cout << "the first digit is " << number << '\n'; return 0; }

I suggest that you:
1. Get your program working for input numbers > 0.
2. Modify the program so it will work for zero.
3. If you want to be a real hero, modify the program to work for numbers < 0 too.
Thanks for the answer, but my main problem was the idea of creating another array and inserting those elements inside it.
For example if we have a[4] ={ 345 , 11 , 2789 , 99 } array b should also have 4 elements (3, 1 , 2, 9), which are the first digits of the elements in a.
for (int i = 0; i < sz; ++i) b[i] = first_digit_of(a[i]);
Thanks , I figured it out by myself though :)
 123456789101112131415161718 #include #include using namespace std; int firstDigit( int n ) { return n < 10 ? n : firstDigit( n / 10 ); } int main() { int a[] = { 345, -11, 2789, -99 }; int n = sizeof( a ) / sizeof( a[0] ); int *b = new int[n]; for ( int i = 0; i < n; i++ ) { b[i] = firstDigit( abs( a[i] ) ); cout << b[i] << " "; } delete [] b; }
Last edited on