Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 6 of 6

01082005, 11:34 PM #1
 Join Date
 Jan 2005
 Posts
 2
 Thanks
 0
 Thanked 0 Times in 0 Posts
combining or adding two integers... how?? help please
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
01092005, 12:00 AM
#2
well:
int number = 10*i+j;
If you can guarentee i and j < 10, this is fine.
01092005, 12:24 AM
#3
 Join Date
 Jan 2005
 Posts
 2
 Thanks
 0
 Thanked 0 Times in 0 Posts
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
01092005, 03:40 AM
#4
 Join Date
 May 2002
 Location
 Virginia, USA
 Posts
 621
 Thanks
 0
 Thanked 6 Times in 6 Posts
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
01092005, 08:52 AM
#5
 Join Date
 Dec 2003
 Posts
 367
 Thanks
 0
 Thanked 0 Times in 0 Posts
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
01092005, 01:32 PM
#6
 Join Date
 Nov 2004
 Location
 Netherlands
 Posts
 87
 Thanks
 0
 Thanked 0 Times in 0 Posts
You could have an extra variable to keep track of the multiplication.
If you were appending j to i:
I don't know if that works, but it should.Code: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; } }