English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Let's say I have an array where a[0] = 9, a[1] = 8, a[2] = 7, a[3] = 6
I want to place each element together to form just one number, so that i could have int num = 9876. Is this possible?

2007-05-20 07:56:02 · 4 answers · asked by Bouken SocratiCat 6 in Computers & Internet Programming & Design

4 answers

Sure it's possible... a *hint* would be... Use multiples of 10!

2007-05-20 08:00:02 · answer #1 · answered by Kasey C 7 · 1 0

Here is a function for you.

//values is the array and size is the length of the array
// do not pad the array with zeros on the left.
int combine(int* values, int size)
{
// setup and initial value as the first one in the array
int result = values[0];

// loop through all the rest of the values
// push the old numbers over by 1 place *10
// and add the new one on the end + val
for(i=1;i result += result*10 + values[i];

return result;
}

2007-05-20 15:35:56 · answer #2 · answered by Math Guy 4 · 0 0

You could try using:

String.Concat(x);

to create a string from the elements of array x. You would then have "9876", but it would be a string, not a number. You could then cast it into an integer easily if you needed to carry out mathematical functions on it. I'm a bit rusty, so I'm not sure whether you will need to import String.h or whether it will be included in system namespace.

Good luck.

2007-05-20 15:15:35 · answer #3 · answered by Anonymous · 0 1

Here is a way:

#include
#define SIZE 4

int powers( num, power )
{
if ( power == 0 )
return 1;
else
{
return ( num * powers( num, power-1 ) );
}
}

int main()
{
int arr[SIZE] = { 9, 8, 7, 6 };
int i;
int num = 0;
int largest = powers( 10, SIZE );

for ( i = 0; i < SIZE; ++i )
{
largest = largest/10;
num += arr[ i ] * largest;
}

printf( "The number is: %d\n", num );
return 0;
}

2007-05-20 15:20:22 · answer #4 · answered by cainofnod 2 · 0 0

fedest.com, questions and answers