1
\$\begingroup\$

I don't want to use the if-statement chain. Can I write the code in a different way? I want to use the smallest amount of if-statements.

#include <stdio.h>
#include <stdlib.h>
main()
{
    int temp;

    printf("type a number: "),
    scanf("%d", &temp);
    printf("\n\n");

    if (temp == 18)
    {
        printf("The temperature is normal, stable conditions. \n");
    }
    else if (temp < 5)
    {
        printf("The temperature is too cold. Massive damage. \n");
    }
    else if (temp > 25)
    {
        printf("The temperature is too hot. Massive damage. \n");
    }

    else
    {
        printf("The temperature is unstable. This condition can make damages. \n");
    }
    system("PAUSE");
}
\$\endgroup\$
10
  • 1
    \$\begingroup\$ Why do you want to use less if..else? Do you want to obfuscate your code? \$\endgroup\$
    – haccks
    Mar 3, 2017 at 13:58
  • 3
    \$\begingroup\$ There's nothing wrong with this code; it's concise and easy to understand. \$\endgroup\$ Mar 3, 2017 at 13:58
  • \$\begingroup\$ well, first, if you write if(...) { and } else if (...) {, } else { it will look much better :) \$\endgroup\$
    – khachik
    Mar 3, 2017 at 13:59
  • \$\begingroup\$ Short answer: Yes, you can certainly reduce the amount of if statements to zero. But you will need to use different code instead, it will just be different or even get worse overall. \$\endgroup\$
    – grek40
    Mar 3, 2017 at 14:00
  • 1
    \$\begingroup\$ A table of structs describing a temperature interval with a "description", This way you can add an in definite number of intervals/descriptions without changing the code. \$\endgroup\$
    – Michael Walz
    Mar 3, 2017 at 14:07

5 Answers 5

1
\$\begingroup\$

Some comment mentioned the ternary operator, that would be an option. However, with nested ternary operators it's essential to have a well readable formatting. Note that this is not better than the if-else. Just different.

printf(
    temp == 18
    ? "The temperature is normal, stable conditions. \n"
    : temp < 5
    ? "The temperature is too cold. Massive damage. \n"
    : temp > 25
    ? "The temperature is too hot. Massive damage. \n"
    : "The temperature is unstable. This condition can make damages. \n");

A solution which doesn't rely on bad spaghetti-code could involve a helper function that is abstracting the task of printing a text for some given number range. Note, I changed the 5 and 25 numbers in order to compare them as an inclusive range rescription.

int PrintIfInRange(int temp, int lower, int upper, const char* text)
{
    if (temp >= lower && temp <= upper)
    {
        printf(text);
        return 1;
    }
    return 0;
}

int main()
{
    int temp;

    printf("type a number: "),
    scanf("%d", &temp);
    printf("\n\n");

    if (!PrintIfInRange(temp, 18, 18, "The temperature is normal, stable conditions. \n") &&
        !PrintIfInRange(temp, INT_MIN, 4, "The temperature is too cold. Massive damage. \n") &&
        !PrintIfInRange(temp, 26, INT_MAX, "The temperature is too hot. Massive damage. \n"))
    {
        printf("The temperature is unstable. This condition can make damages. \n");
    }

    system("PAUSE");
}

This second part is less of an answer to your question about least number of if statements or smallest amount of code, but more an addition to show, how the code could be changed to be more expressive about what is happening.

\$\endgroup\$
6
  • 8
    \$\begingroup\$ I will surely fire that developer who will use this code in production. \$\endgroup\$
    – haccks
    Mar 3, 2017 at 14:14
  • \$\begingroup\$ Drat, didn't post fast enough for the green check! Damn you @grek40 ;-) \$\endgroup\$
    – Toby
    Mar 3, 2017 at 14:15
  • 1
    \$\begingroup\$ Terrible code. Don't us that in production code. \$\endgroup\$
    – Michael Walz
    Mar 3, 2017 at 14:16
  • 2
    \$\begingroup\$ @haccks I'll be careful not to make you my boss :) other than that, I'd probably do something like WriteIfRange(temp, x, y, text) function or something completely different. However, I'd first fire the one who is requesting "smallest amount of if-statement" in production code. \$\endgroup\$
    – grek40
    Mar 3, 2017 at 14:18
  • 3
    \$\begingroup\$ @Eduardo; Shortest doesn't mean better. Always write clear and detailed program. \$\endgroup\$
    – haccks
    Mar 3, 2017 at 14:26
4
\$\begingroup\$

One single if and you can add an indeterminate number of temperature conditions without adding a single if.

And this code is very short, the struct stuff isn't code

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct
{
  int low;
  int high;
  const char *text;
} temperatures[] = 
{
  { 18, 18, "The temperature is normal, stable conditions. \n" },
  { -INT_MAX, 5, "The temperature is too cold. Massive damage. \n" },
  { 25, INT_MAX, "The temperature is too hot. Massive damage. \n" },
};

int main()
{
  int temp;

  printf("type a number: "),
    scanf("%d", &temp);
  printf("\n\n");

  for (int i = 0; i < sizeof(temperatures) / sizeof(temperatures[0]); i++)
  {
    if ((temp > temperatures[i].low && temp < temperatures[i].high) || (temp == temperatures[i].low && temp == temperatures[i].high))
    {
      printf("%s", temperatures[i].text);
      return 0;
    }
  }

  printf("The temperature is unstable. This condition can make damages. \n");
}
\$\endgroup\$
4
  • 2
    \$\begingroup\$ I completely agree that a solution like this is correct for any usage that transcends bad-teacher-requirements. \$\endgroup\$
    – grek40
    Mar 3, 2017 at 14:29
  • 1
    \$\begingroup\$ You could use temp >= temperatures[i].low && temp <= temperatures[i].high instead of two separate expressions. \$\endgroup\$
    – 2501
    Mar 3, 2017 at 14:30
  • \$\begingroup\$ @2501 thanks, this was just quickly written code. \$\endgroup\$
    – Michael Walz
    Mar 3, 2017 at 14:33
  • 1
    \$\begingroup\$ Suggest using INT_MAX/INT_MIN rather than 1000/-273. \$\endgroup\$ Mar 3, 2017 at 19:55
1
\$\begingroup\$

I simplified the messages for this example, which has one if.

#include <stdio.h>

#define VALUES 5

int main(void) 
{
    char *message[VALUES] = { "too high", "unstable", "stable", "unstable", "too low" };
    int tempers[VALUES] = { 25, 18, 17, 4, };
    int loop;
    int temp;

    scanf("%d", &temp);

    for(loop = 0; loop < VALUES-1; loop++) {
        if(temp > tempers[loop]) {
            break;
        }
    }
    printf("The temperature is %s\n", message[loop]);
    return 0;
}
\$\endgroup\$
0
\$\begingroup\$

As I commented, for no if statements (very pedantically):

#include <stdio.h>
#include <stdlib.h>

static const char *NORMAL = "The temperature is normal, stable conditions.";
static const char *COLD = "The temperature is too cold. Massive damage."
static const char *HOT = "The temperature is too hot. Massive damage."
static const char *UNSTABLE = "The temperature is unstable. This condition can make damages."

int main(int argc, char *argv[])
{
    int temp;

    printf("type a number: "),
    scanf("%d", &temp);
    printf("\n\n");

    printf("%s \n", temp < 5 ? COLD : temp > 25 ? HOT : temp == 18 ? NORMAL : UNSTABLE);
    system("PAUSE");
}

But really this is just code golfing

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Terrible code. Don't us that in production code. \$\endgroup\$
    – Michael Walz
    Mar 3, 2017 at 14:16
  • 2
    \$\begingroup\$ @MichaelWalz Thank you for commenting that on every. single. answer... the OP clearly stated that this is for homework. Even for homework it's a pretty redundant request to start with \$\endgroup\$
    – Toby
    Mar 3, 2017 at 14:17
0
\$\begingroup\$

I really don't know why you don't want to use if statements despite it make easier for other developers to understand what is the motive of the written code. Using ternary operator in this case will obfuscate the code and make it difficult to read and understand.

I would suggest leave it as it is (with all if/else statements) which makes more sense.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.