# adding odd numbers

• 09-06-2001
Unregistered
hi
if i have a list of numbers , say 2345678
and want to add up the odd position digits
ie 2+4+6+8

how can i do this ?

i tried it with nums[20]
and using atoi to convert the type

but it seems i can't do things like

sum=atoi(nums[0]) + atoi(nums[1]);

can someone plz help me~~~~
• 09-06-2001
Sebastiani
Try this:

PHP Code:

``` char nums[]="2345678" int i; int add=0; for(i=0; i < strlen(nums); i + 2) { add = add + (atoi(nums[i]) );   /// OR add += (atoi(nums[i]) ) } printf("%i", add);  ```
• 09-06-2001
Stoned_Coder
try changing :-

for(i=0; i < strlen(nums); i + 2)
to
for(i=0; i < strlen(nums); i += 2)
• 09-06-2001
no-one
this will do it for any number
Code:

``` #include <stdlib.h> #include <string.h> #define MAX_SIZE 15 int function(int num) {     int ret = 0;     char number[MAX_SIZE];     memset(number,'\0',MAX_SIZE);     _itoa(num,number,10);     for(int i = 0;number[i] != '\0';i++)   {         if((i % 2 != 0) || i == 1)             ret += i;   }   return ret; }```
• 09-06-2001
bigtamscot
Does it have to be a string

int num[7] ={2,3,4,5,6,7,8};

then

for(i =0; i < 7;i++)
if(i % 2 == 0)
total += num[i];

should do the trick
• 09-06-2001
zoo
A third way.

Code:

```#include <stdlib.h> #include <stdio.h> int add_odd_digits(int number); int main() {   int num = 12345;   int sum;   sum = add_odd_digits(num);   printf("sum of odd digits:%d\n",sum);   return 0; } int add_odd_digits(int number) {   int digit, odd_sum;   int sum1 = 0;   int sum2 = 0;   while (number > 0)   {       digit = number % 10;       number /= 10;       sum1 += digit;       if (number <=0)         return sum1;       digit = number % 10;       number /= 10;       sum2 += digit;       if (number <=0)         return sum2;   } }```