Given an array of int
s
int arr[] = {2, 0, 1, 4};
and I want to manipulate them so that I get the value 2014
and store it in an int
variable
How can I do that?
Assuming you don't want to add them and store the result in a new variable. To print them concatenated to each other like 15
, you may write something like this.
printf("%d%d\n", x, y);
To add them and store the result in a new variable, you may multiply x
by 10
first, then add them and store the result in a new int
variable
int sum = (x * 10) + y;
printf("%d\n", sum);
Update: in case you have an array of 4 int
s and you want to add them in such a way as the first, the second, the third, the fourth elements are positioned in the ones, tens, hundreds, thousands places respectively, you may write something like this
int arr[] = {2, 0, 1, 4};
int position = 1;
int year = 0;
for (int i = 3; i >= 0; i--)
{
year += arr[i] * position;
position *= 10;
}
After the loop ends execution, year
should be 2014
.
x += y;
means x = x + y;
. Similarly, x *= y;
means x = x * y;
. And of course the asterisk (i.e., *
) in position *= 10;
is the multiplication operator.
*
in arr[i] * position
is the multiplication operator. I didn't use pointers in the code above!