user17725027
user17725027

Reputation: 29

C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

i am new to programing, i want to know that how we can find the odd digits in a number. the condition in this program is we should only use concept of arrays.I tried a code for this as follows:

#include <stdio.h>

int main()
{
  int A[50],i,x,y,n,sum=0;
  scanf("%d",&n);
  printf("the value is %d\n",n);
  for(i=0;i<n;i++)
    scanf("%d",&A[i]);
  for(i=0;i<n;i++){
    x=A[i]%10;
    if(x%2!=0)
      sum=sum+x;
     A[i]=A[i]/10;
     printf("the sum of odd numbers  is %d\n",sum);
   }

   return 0;
 }

but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number. so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?

Upvotes: 1

Views: 1937

Answers (2)

atru
atru

Reputation: 4744

You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,

#include <stdio.h>

int main()
{

    int A[50], i, x, y, n, sum=0;

    printf("How many numbers will you input?\n");
    scanf("%d",&n);
    printf("the value is %d\n",n);

    for(i=0; i<n; i++) {
        scanf("%d",&A[i]);
    }

    for(i=0; i<n; i++) {
        sum = 0;
        while (A[i] > 0) {
            x = A[i]%10;
            if(x%2 != 0) {
                sum = sum + x;
            }
            A[i] = A[i]/10;
        }
        printf("the sum of odd numbers is %d\n",sum);
    }

     return 0;
}

The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.

Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.

Upvotes: 3

Bartosz R&#243;życki
Bartosz R&#243;życki

Reputation: 78

int temp;
int sum = 0;

temp = number;
do {
    lastDigit = temp % 10;
    temp = temp / 10;
    sum += (lastDigit %2 != 0) ? lastDigit : 0; 
} while(temp > 0);

Upvotes: 2

Related Questions