Difficulty: ★ ★ ★ ★
The challenge for last month’s Exercise was to generate repeated output without using a looping statement. The solution is to use recursion, though this choice is obvious only to experienced programmers who know about recursion. The challenge for this month’s exercise is far more devious, hence the four stars.
A conditional statement in C programming is one that evaluates two expressions. The common one is the if keyword, but the ?: operator also counts. Mixed in are the comparison operators: ==, !=, <, >, <=, and >=. It’s also possible to use if or ?: with a single expression, providing that the expression evaluates TRUE (non-zero) or FALSE (zero).
Your task is to write a program that generates a random value, 0 through 99. The program then outputs whether the value is odd or even without using any of the standard comparison tools.
Here are a few sample runs from my solution:
The value 86 is even The value 19 is odd The value 44 is even The value 19 is odd
Working with this problem, I developed two approaches though they both rely upon the same mechanism to generate the “odd” or “even” text output. I will also be exploring further ways to fake comparisons in C later this mornth.
This exercise can be a tough one. You really need to think outside of the box. And, yes, your solution cannot use if or ?: or any of the comparison operators to generate the output.
I post my solution in a week.
This uses the LSB as an odd/even flag to index a string array.
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int r;
const char* oddeven[] = {“even”, “odd”};
int am = 1;
int oei = 0;
srand(time(NULL));
printf(“%s\n\n”, “iflessness\n———-“);
for(int n = 0; n < 32; n++)
{
r = rand() % 100;
oei = r & am;
printf(“%2d is %s\n”, r, oddeven[oei]);
// single line alternative without
// oei (odd even index) variable
// printf(“%2d is %s\n”, r, oddeven[r & am]);
}
}
Sample output:
iflessness
———-
28 is even
16 is even
95 is odd
0 is even
36 is even
85 is odd
18 is even
69 is odd
63 is odd
66 is even
20 is even
77 is odd
26 is even
5 is odd
8 is even
30 is even
12 is even
96 is even
63 is odd
83 is odd
94 is even
42 is even
9 is odd
37 is odd
53 is odd
14 is even
22 is even
40 is even
24 is even
24 is even
94 is even
53 is odd
I found this https://www.bbc.co.uk/news/magazine-20559052 about 0 being even.