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];
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?
CodePudding user response:
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];
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.
Note that you also print the intermediate sums (good for debugging), and that I changed to formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
CodePudding user response:
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum = (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);
