Write a program that examines three variables — x, y, and z — and
prints the largest odd number among them. If none of them are odd, it
should print a message to that effect.
This is my source code:
#include <stdio.h>
int main() {
int x,y,z;
x = 11;
y = 15;
z = 18;
if (x > y && x > z && x % 2 != 0)
printf("%d", x);
else if (y > z && y > x && y % 2 != 0)
printf("%d", y);
else if (z > x && z > y && z % 2 != 0)
printf("%d", z);
else
printf("error");
return 0;
}
The program is compiling and running but is giving the wrong answer. For the above it gives "error" as the output, but the greatest odd number is 15.
You are just printing the largest integer of the three if it is odd. For not to change you code so much and if you doesn't care about the others values, you can set the even variables to -INF. That is:
//INF can be whatever big even value you think that works fine (1e9), 0x3ffffffe, etc
#define INF 1e9
if (x % 2 == 0) x = -INF;
if (y % 2 == 0) y = -INF;
if (z % 2 == 0) z = -INF;
//here the rest of your code
In your example, y is the largest odd number, but it is not the largest number. z is larger, so "y>z" evaluates to false, and the path you want is not taken.
You may have noticed that your code is very repetitive. And the next exercise in the book is likely to be "OK, now do this for ten input numbers", which would be too tedious to contemplate, or "... for any number of input numbers", which just plain can't be done the way you're doing it.
So instead you should be thinking about a code structure like this:
int current_largest_odd_number = 0; /* note: zero is even */
for (;;) {
int n = read_a_number();
if (n == -1) break; /* read_a_number returns -1 on EOF */
if (is_even(n)) continue;
if (n > current_largest_odd_number)
current_largest_odd_number = n;
}
if (current_largest_odd_number > 0)
printf("largest odd number: %d\n", current_largest_odd_number);
The code is not printing the largest odd number, but is printing the largest number if it happens to be odd.
You need to keep track of the largest odd number you've found and then print that.
For example:
int found = false, largest = 0;
if (x%2 != 0) {
found = 1;
largest = x;
}
if (y%2 != 0) {
found = 1;
if (y > largest) {
largest = y;
}
}
if (z%2 != 0) {
found = 1;
if (z > largest) {
largest = z;
}
}
if (found) {
printf("%d", largest);
} else {
printf("error");
}
Your code prints the largest number if and only if is is odd.
You could instead test each number in turn and update a pointer to the maximum odd value if any.
#include <stdio.h>
int main() {
int x = 11;
int y = 15;
int z = 18;
int *largest = NULL;
if (x % 2 != 0) {
largest = &x;
}
if (y % 2 != 0) {
if (!largest || y > *largest) {
largest = &y;
}
}
if (z % 2 != 0) {
if (!largest || z > *largest) {
largest = &z;
}
}
if (largest) {
printf("%d\n", *largest);
} else {
printf("error\n");
}
return 0;
}
Here is an alternative approach with an indicator instead of a pointer:
#include <stdio.h>
int main() {
int x = 11;
int y = 15;
int z = 18;
int largest = 0;
int found = 0;
if (x % 2 != 0) {
largest = x;
found = 1;
}
if (y % 2 != 0) {
if (!found || y > largest) {
largest = y;
found = 1;
}
}
if (z % 2 != 0) {
if (!found || z > largest) {
largest = z;
found = 1;
}
}
if (found) {
printf("%d\n", largest);
} else {
printf("error\n");
}
return 0;
}
My version examines all possible three integer numbers and prints the largest
odd number (As an absolute beginner.)
x = int(input("number x = "))
y = int(input("number y = "))
z = int(input("number z = "))
/*Ask the user to input three variables*/
ans=0
if x%2==0 and y%2==0 and z%2==0:
print("There are no odd numbers.")
else:
if x<=y<=z and z%2!=0:
ans=z
elif y%2!=0:
ans=y
elif x%2!=0:
ans=x
if x<=y>=z and y%2!=0:
ans=y
elif x>=z and x%2!=0:
ans=x
elif z%2!=0:
ans=z
if x>=y<=z and x>=z and x%2!=0:
ans=x
elif z%2!=0:
ans=z
elif y%2!=0:
ans=y
if x>=y>=z and x%2!=0:
ans=x
elif y%2!=0:
ans=y
elif z%2!=0:
ans=z
print("The largest odd number is "+str(ans))
Related
So, here is my code to calculate L.C.M (Least common multiple) without using G.C.D:
int lcm(int x, int y){
int max = 0, min = 0, ans = 0;
if(y >= x){
max = y;
min = x;
if(y % x == 0) return y;
}else {
max = x;
max = y;
if(x % y == 0) return x;
}
for(int i = 1; i <= max ; i++){
if( (max*i) % min == 0){
ans = max * i;
break;
}
}
return ans;
}
and here is the main:
int main(){
int u, v;
printf("Input two numbers: ");
scanf("%d%d", &u, &v);
puts("");
printf("LCM(%d, %d): %d",u , v, lcm(u, v));
return 0;
}
It works perfectly for inputs like 4 8,7 21 and everything else in which the first number is smaller. An example:
It takes a lot of time to run if the value of first input is higher and does nothing
What am I doing wrong here?
I am using Dev-C++.
In the else statement inside the lcm function, it should be min = y.
That was the mistake I was making. Thanks TotallyNoob for pointing it out.
#include <stdio.h>
int main() {
int rangeValue;
int x;
printf("Please input a number to be considered in the range:\n");
scanf("%d", &rangeValue);
while (rangeValue != 1) {
x = rangeValue;
if ((x % 2) == 0) {
x = x / 2;
printf("%d,", x);
} else {
x = (3 * x) + 1;
printf("%d,", x);
}
rangeValue--;
}
return 0;
}
My goal is to do the Collatz sequence of every number from 1 to the number I give to rangeValue. I expected this to work. Can anyone help me make it work?
You are mixing the range of sequences to print, the maximum number of iterations and the current number in the sequence.
Here is how to fix the code:
#include <stdio.h>
int main(void) {
int rangeValue;
printf("Please input a number to be considered in the range:\n");
if (scanf("%d", &rangeValue) != 1)
return 1;
// iterate for all numbers upto rangeValue
for (int n = 1; n <= rangeValue; n++) {
printf("%d", n);
for (long long x = n; x != 1; ) {
if ((x % 2) == 0) {
x = x / 2;
} else {
x = (3 * x) + 1;
}
printf(",%lld", x);
}
printf("\n");
}
return 0;
}
What I am trying to do in the code below is to to make the input a four-digit number (if it's not already) and then sort the digits in the number in an ascending and descending order. x is ascending, y is descending. Then I want to subtract x and y until I get the result 6174 of the subtraction.
#include <stdio.h>
int main() {
int number, count = 0, digit, pow = 0, result = 1, counter, temp,
x = 0, y = 0, i, j, substract = 0, count1 = 0;
scanf("%d", &number);
while (substract != 6174 && substract >= 0) {
substract = 0;
if (count1 > 0) {
temp = substract;
} else {
temp = number;
}
while (temp > 0) {
digit = temp % 10;
temp = temp / 10;
count++;
}
if (count < 4) {
pow = 4 - count;
/* Calculate base^exponent */
for (counter = 0; counter < pow; counter++) {
result = result * 10;
}
number = number * result;
}
for (i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
int tmpNumber = number;
while (tmpNumber > 0) {
int digit = tmpNumber % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmpNumber /= 10;
}
}
substract = x - y;
count++;
printf("\n x %d", x);
printf("\n y %d", y);
printf("\n substract %d", x - y);
}
return 0;
}
When I input 3542 What I expect as an output is this
input:
3524
output:
x 5432
y 2345
subtract 3087
x 8730
y 0378
subtract 8352
x 8532
y 2358
subtract 6174
But what I get is actually this:
input:
3524
output:
x 5432
y 2345
subtract 3087
x 54325432
y 23452345
subtract 30873087
I think the problem is something with the x and y. I have to reset them to zero at some point. But I don't know where. I've tried every single place in the code. If anyone knows where I do wrong I will really appreciate the help.
The program fails for multiple reasons:
You do not reset x and y to 0 for each iteration
result should also be reset to 1
The initial phase of the loop is too complicated: you should test if substract is 0 or 6174 to stop the loop and store substract to number at the end of the loop.
Here is a simpler version that does not need to make number have 4 digits:
#include <stdio.h>
int main(void) {
int number;
if (scanf("%d", &number) == 1 && number >= 0 && number < 10000) {
for (;;) {
int x = 0, y = 0, substract;
for (int i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
for (int tmp = number, n = 0; n < 4; n++) {
int digit = tmp % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmp /= 10;
}
}
substract = x - y;
printf("x %d\n", x);
printf("y %d\n", y);
printf("substract %d\n", substract);
if (substract == 0 || substract == 6174)
break;
number = substract;
}
}
return 0;
}
I am attempting to print integers to the console in C with a few constraints, the most significant of which being that I may only write individual characters to the console as follows:
void my_char(char ch)
}
write(1, &ch, 1);
}
Other constraints include NO predefined methods (printf, log, etc). No recursion. Lastly, I may NOT create an array.
So far I have come up with a method that prints the numbers out perfectly well... backwards.
int main()
{
int i = -345320;
my_int(i);
return 0;
}
void my_int(int x)
{
char *a;
int n;
if(x < 0)
{
x = x * -1;
my_char('-');
}
while(x)
{
n = x % 10;
a = (char*)&n;
my_char(*a + 48);
x /= 10;
}
}
Are there other good ways to approach this or am I at least going in the right direction? I would ideally like to expand this to print an integer in any base I provide, but I need to start here.
I was playing with iterating a pointer over each Byte of the integer but I can't grasp how I would use those character values to re-create the integer.
Any advice is appreciated. I'd much rather receive some insight than just a code solution. I'd also love input on making it more lean.
Here's a general (ugly!) solution following your constraints. It uses the idea I gave in the comment above. It assumes 32-bit ints.
void my_int(int x) {
int n = 1000000000;
if (x == 0) {
my_char('0');
return;
}
if (x == INT_MIN) { // INT_MIN is in limits.h
my_char('-'); my_char('2'); my_char('1');
my_char('4'); my_char('7'); my_char('4');
my_char('8'); my_char('3'); my_char('6');
my_char('4'); my_char('8');
return;
}
if (x < 0) {
x *= -1;
my_char('-');
}
while (n > x) n /= 10;
while (n != 0) {
my_char(x / n % 10 + '0');
n /= 10;
}
}
This should do the trick. It prints the integer forwards.:
void my_int(int x)
{
int temp = 0;
int divFactor = 10;
if(x==0)
{
my_char('0');
return;
}
if(x < 0)
{
x = x * -1;
my_char('-');
}
temp = x;
while((temp /= 10) > 10) {divFactor *= 10;}
for(;divFactor > 0;divFactor /= 10)
{
temp = x;
temp /= divFactor;
my_char(temp + '0');
x -= divFactor * temp;
}
printf("\n done!");
}
int main()
{
int i = -1234001;
my_int(i);
return 0;
}
void my_int(int x)
{
int n;
int copy;
char digit;
// handle 0
if (!x)
{
my_char('0');
return;
}
// emit sign
if(x < 0)
{
x = x * -1;
my_char('-');
}
// count base-10 digits in x, store 10^n in n
n = 1;
copy = x/10; // shorten loop by 1 iteration
while (copy)
{
n *= 10;
copy /= 10;
}
// 'n' is now a digit selector
while (n)
{
digit = x/n;
my_char(digit + '0'); // print the most significant digit
x -= digit*n; // remove the most significant digit from x
n /= 10;
}
}
Write a program that will find the largest number smaller than N that is totally different from a given number X. One number is totally different from other only if it doesn't contain any of the digits from the other number. N and X are read from standard input. The problem should be solved without the use of arrays.
Example Input 1: 400 897
Example Output 1: 366
Example Input 2: 1000 1236498
Example Output 2:777
No it's not homework, it was on one of the midterms and it's been killing me. I though about taking the first numbers last digit with %10 then taking the second numbers digit with %10 comparing them but...I just can't get it to work...I ended up with an endless loop...I just don't understand how to get every digit of the numbers and compare them to the other number.
#include <stdio.h>
int main () {
int N, X, num_N, num_X, i, lastDigit_N, lastDigit_X, flag, smaller_than_N;
scanf("%d%d", &N, &X);
smaller_than_N = N - 1;
for (i = smaller_than_N; i > 0; i--) {
num_N = i;
num_X = X;
flag = 0;
while (num_N > 0) {
lastDigit_N = num_N % 10;
while (num_X > 0) {
lastDigit_X = num_X % 10;
if (lastDigit_N == lastDigit_X) {
break;
}
else {
flag = 1;
}
num_X /= 10;
}
num_N /= 10;
}
if(flag) {
printf("%d", i);
break;
}
}
return 0;
}
You could build a bitmask for your numbers showing the digits which are contained.
uint16_t num2bitmask(int number)
{
uint16_t result = 0;
while (number) {
int digit = number % 10;
number /= 10;
result |= (1 << digit);
}
return result;
}
With this function, you can create your bitmask for X and then iterate from N-1 down to 1 until you find a value which doesn't have any bits in common with the other value.
If you have a number with digits d_1, d_2, ..., d_n, and you're allowed to use digits in the set D, then possible solutions look like:
d_1, ..., d_{i-1}, max(d in D | d < d_i), max(d in D), ..., max(d in D).
That is, the digits are the same up to some point, then the next digit is as large as possible while being below the input digit, then the rest are just as large as possible.
Not all these "solutions" will be valid, but if you iterate through them in reverse order (there's exactly n for an input number of size n), the first valid one you find is the answer.
Some code, including tests:
#include <stdio.h>
int digit_length(int a) {
int r = 0;
while (a) {
a /= 10;
r += 1;
}
return r;
}
int get_digit(int a, int k) {
while (k--) a /= 10;
return a % 10;
}
int largest_different(int a, int b) {
int lena = digit_length(a);
int invalid = b ? 0 : 1;
for (; b; b /= 10) invalid |= 1 << (b % 10);
int max_valid = 9;
while (max_valid >= 0 && (invalid & (1 << max_valid)))
max_valid--;
if (max_valid == -1) return -1;
for (int i = 0; i < lena; i++) {
int d = get_digit(a, i) - 1;
while (d >= 0 && (invalid & (1 << d)))d--;
if (d < 0) continue;
int solution = 0;
for (int k = lena - 1; k >= 0; k--) {
solution *= 10;
solution += (k < i ? max_valid : k > i ? get_digit(a, k) : d);
}
return solution;
}
return -1;
}
int main(int argc, char *argv[]) {
struct {int n; int x; int want;} examples[] = {
{400, 897, 366},
{1000, 1236498, 777},
{998, 123, 997},
};
int error = 0;
for (int i = 0; i < sizeof(examples) / sizeof(*examples); i++) {
int got = largest_different(examples[i].n, examples[i].x);
if (got != examples[i].want) {
error = 1;
printf("largest_different(%d, %d) = %d, want %d\n",
examples[i].n, examples[i].x, got, examples[i].want);
}
}
return error;
}
There's not always a solution. In that case, the function returns -1.