1

Given an array of ints

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?

2

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 ints 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.

6
  • I want to store, but it is not the result, because I get 4 chars (1, 1, 9, 7) my goal is to make all those chars into one int called year (that represents date of birth) like this: int year = 1997; – Joao Turolla Jun 26 '14 at 16:03
  • @Joao Turolla updating my answer! – kzidane Jun 26 '14 at 16:05
  • and what would be += and *=, and this * position is pointer or multiplly? – Joao Turolla Jun 26 '14 at 16:14
  • 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. – kzidane Jun 26 '14 at 16:19
  • @JoaoTurolla and also * in arr[i] * position is the multiplication operator. I didn't use pointers in the code above! – kzidane Jun 26 '14 at 16:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .