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.

1
2
3
4
5
6
7
8
9
10
11
12
13
    int main(){
    int n, i, a[100], b[100];
    cin>>n;
    for(i=0;i<n;i++)
     cin>>a[i];
    
     for(i=0;i<n;i++) 
        if(a[i]%10==a[i])
        int aux= a[i];
     else
        while(a[i]>9)
         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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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 :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
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
Topic archived. No new replies allowed.