Sorry for my english.
I am taking an introductory course in C, and I have some problems with the logic of my program. He will sometimes produce the required output.
The task is to write a function that takes the elements of the array, to return the largest even digit in the element.
int ary1[] = {123, 456, -7890, 12}; Would -7890 as the largest value with 8 as the largest even number and its occurrences.
int ary2[5] = {-123, 654, 78, 15, 189}; Would return 189 as the largest value with 8 as the largest even number and its occurrences.
int ary3[2] = {9, 9}; Would not return anything.
int ary4[] = {123, 123, 0, 12}; Would return 123 as the largest value, with 2 as the largest even digit and its occurrences.
int ary5[] = {24, 45, -789, 24, 1}; Would -789 as the largest value with 8 as the largest even number and its occurrences.
int ary6[] = {-749, -241, 1, 45}; Would return 45 as the largest value, with 4 as the largest even number and its occurrences.
Here is my code:
#include <stdio.h> void digitExtract(int[], int); int main() { int ary1[] = { 123, 456, -7890, 12 }; int ary2[5] = { -123, 654, 78, 15, 189 }; int ary3[2] = { 9, 9 }; int ary4[] = { 123, 123, 0, 12 }; int ary5[] = { 24, 45, -789, 24, 1 }; int ary6[] = { -749, -241, 1, 45 }; int ary7[] = { 1, 3, 5 }; printf("\nCalling function in ary1[]:\n"); digitExtract(ary1, 4); printf("\nCalling function in ary2[]:\n"); digitExtract(ary2, 5); printf("\nCalling function in ary3[]:\n"); digitExtract(ary3, 2); printf("\nCalling function in ary4[]:\n"); digitExtract(ary4, 4); printf("\nCalling function in ary5[]:\n"); digitExtract(ary5, 5); printf("\nCalling function in ary6[]:\n"); digitExtract(ary6, 4); printf("\nCalling function in ary7[]:\n"); digitExtract(ary7, 3); } void digitExtract(int Array[], int array_size) { int tempValue; int x; int myArr[10] = { 0 }; int evenCount = 0; int max = Array[0]; for (int i = 1; i < array_size; i++) { if (Array[i] < 0) { Array[i] = -Array[i]; if (Array[i] > max) { max = Array[i]; } } } tempValue = (max < 0) ? -max : max; do { myArr[tempValue % 10]++; tempValue /= 10; } while (tempValue != 0); for (x = 8; x > 0; x -= 2) { if (myArr[x]>0) { printf("Displaying from inside of function():\n"); printf("\nThe largest even digit: %d\n", x ); printf("\nThe digit %d occurs %d times.\n", x, myArr[x]); evenCount++; break; } } if (evenCount == 0) printf("\nNo even digits found!\n\n"); }
I know that there is an error in my logic, since for ary2[] it gives an even number 6 , and it occurs when it should be 8 , but I do not know where.
The function will work for an array with odd values as its element.
Where or what am I doing wrong?
Thanks.