c program to check digits in number are even -
input , output format:
input consists of number corresponds bill number. bill number 3-digit number , 3 digits in number even.
output consists of string either 'yes' or 'no'. output yes when customer receives prize , no otherwise.
samples:
input output 565 no 620 yes 66 no # not 3-digit number (implicit leading zeros not allowed) 002 yes # 3-digit number i have solved problem getting single digit "number" mod 10 , checking if "digit" mod 2 0 or not......
but in case if give input "002", prints "no" instead want should "yes".
code — copied , formatted comment:
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> int main() { int num, t, flag, count = 0; while (num) { t = num % 10; num = num / 10; if (t % 2 == 0) { flag = 1; } else { flag = 0; } count++; } if (flag == 1 && count == 3) { printf("yes"); } else { printf("no"); } return 0; }
you have work strings instead of numbers, otherwise cannot represent 002 value.
recognize digits:
int even(char c) { switch (c) { case '0': case '2': case '4': case '6': case '8': return 1; default: return 0; } } recognize strings digits:
int all_even(char* s) { while (*s != '\0') { if (!even(*s)) { return 0; } s++; } return 1; } return "yes" strings of 3 digits, , return "no" other strings:
char* answer(char* s) { return (strlen(s) == 3 && all_even(s)) ? "yes" : "no"; }
Comments
Post a Comment