...

View Full Version : combining or adding two integers... how?? help please



pika29chu
01-08-2005, 11:34 PM
hi,

im stuck on a bit of programming in C++.

say for example, i have the following code:

for(int i=1; i<6; i++)
{
for(int j=1; j<6; j++)
{
int number = i+j;

cout << number << endl;
}
}

the function above would obviously add i+j together so you get numbers from 2 to a maximum of 10.

however, what i would really like to do is combine the two integers.

so instead of having 1+1 = 2... i would like 1 and 1 = 11 or 2 and 1 = 21. if you understand what i mean? i basically would like to combine the two integers together.

does anyone know how to write the code for this please?

help in this matter would be much appreciated... thank you!

alex

jkd
01-09-2005, 12:00 AM
well:

int number = 10*i+j;

If you can guarentee i and j < 10, this is fine.

pika29chu
01-09-2005, 12:24 AM
thanks for the help.

well... i can't guarantee that it will be limited to 10.

is there a way to make it work for any number up to 500 for example.

so if... i = 500 and j = 349 then number is 500349??

thanks

Celtboy
01-09-2005, 03:40 AM
I would do a type cast, and then type cast back.... so like...

char num[10] = char(i) + char(j);
int myNum = (int)num;


I think?

-Celt

shmoove
01-09-2005, 08:52 AM
Those casts would take the number as an ascii value though. What you need to do is use a function to convert the number to a string (itoa() for example), concatenate the string and the use a function that converts back to numeric (atoi()).

shmoove

Dr. Evil
01-09-2005, 01:32 PM
You could have an extra variable to keep track of the multiplication.

If you were appending j to i:


int i, j, k, out;

for(i=0; i<500; i++)
{
k = 10;
for(j=0; j<500; j++)
{
if(j == k) k *= 10;
out = (i * k) + j;
}
}


I don't know if that works, but it should.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum