LearnFrenzy
Sign in Take a free test

C Programming · Topic 21 of 23

Decision Making

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Decision Making · Study material

Decision making in C is about writing the conditions behind every if, while and ?: correctly: combining tests with &&, || and !, ordering them so each guard protects the next, checking ranges, and replacing tangled nested ifs with clear rules or tables. Most real bugs in decisions are not syntax errors but logic errors – a range test that is always true, a NULL check after the dereference, a branch that can never run. This page teaches decision logic the way professionals think about it, then gives you 40 practice questions checked on a real compiler.

On this page

  • Truth values, truth tables and De Morgan's laws
  • Range checks and the order of conditions
  • Guards that rely on short-circuit evaluation
  • Decision tables, branchless selection and safe comparisons

Truth values and truth tables

In C every scalar value can be a condition: 0 (or a null pointer) is false, anything else is true. Logical operators always produce exactly 0 or 1. A truth table lists the result for every combination of inputs – the quickest way to check a complicated condition.

#include <stdio.h>

int main(void) {
    printf(" a  b | a&&b a||b !a\n");
    for (int a = 0; a <= 1; a++)
        for (int b = 0; b <= 1; b++)
            printf(" %d  %d |  %d    %d    %d\n", a, b, a && b, a || b, !a);
    return 0;
}

Output

 a  b | a&&b a||b !a
 0  0 |  0    0    1
 0  1 |  0    1    1
 1  0 |  0    1    0
 1  1 |  1    1    0

De Morgan's laws

To negate a combined condition, negate each part and swap && with ||: !(a && b) is !a || !b, and !(a || b) is !a && !b. "Not between 10 and 20" is x < 10 || x > 20, never x < 10 && x > 20.

#include <stdio.h>

int main(void) {
    int holds = 0;
    for (int a = 0; a <= 1; a++)
        for (int b = 0; b <= 1; b++)
            if ((!(a && b)) == (!a || !b) && (!(a || b)) == (!a && !b))
                holds++;
    printf("De Morgan's laws hold in %d of 4 cases\n", holds);
    return 0;
}

Output

De Morgan's laws hold in 4 of 4 cases

Ranges and the order of tests

A value is inside [lo, hi] when x >= lo && x <= hi – C has no lo <= x <= hi. In an else-if ladder, reject invalid input first and then go from one boundary to the next; every later test may assume the earlier ones failed, so each needs only one comparison.

#include <stdio.h>

const char *age_group(int age) {
    if (age < 0 || age > 130)      /* reject impossible input first */
        return "invalid";
    if (age < 13)                  /* each test can assume the ones above failed */
        return "child";
    if (age < 20)
        return "teen";
    if (age < 60)
        return "adult";
    return "senior";
}

int main(void) {
    int ages[] = {-1, 8, 15, 42, 75};
    for (int i = 0; i < 5; i++)
        printf("%d: %s\n", ages[i], age_group(ages[i]));
    return 0;
}

Output

-1: invalid
8: child
15: teen
42: adult
75: senior

Guards and short-circuit evaluation

&& evaluates its right side only if the left side is true, so put the cheap, protective test first: p != NULL && p->count > 0, n != 0 && total / n > 5, i < len && a[i] == key. Reversing the order turns a safe guard into a crash.

#include <ctype.h>
#include <stdio.h>
#include <string.h>

size_t safe_len(const char *s) {
    return s != NULL ? strlen(s) : 0;
}

int starts_with_upper(const char *s) {
    return s && s[0] && isupper((unsigned char) s[0]);   /* each test protects the next */
}

int main(void) {
    printf("%zu %zu %d %d %d\n", safe_len("C23"), safe_len(NULL),
           starts_with_upper("Hello"), starts_with_upper(""), starts_with_upper(NULL));
    return 0;
}

Output

3 0 1 0 0

Decision tables

When a result depends on combinations of inputs, a table indexed by those inputs is shorter, faster and easier to check than nested ifs – and changing a rule means changing one number.

#include <stdio.h>

/* shipping charge (Rs.) by zone (row) and weight class (column) */
static const int charge[3][3] = {
    {40, 60, 90},      /* zone 0 */
    {60, 90, 140},     /* zone 1 */
    {90, 140, 200},    /* zone 2 */
};

int weight_class(double kg) {
    return kg < 1 ? 0 : kg <= 5 ? 1 : 2;
}

int main(void) {
    printf("%d %d %d\n", charge[0][weight_class(0.5)], charge[1][weight_class(3)], charge[2][weight_class(12)]);
    return 0;
}

Output

40 90 200

Comparisons that need care

ComparingWrongRight
Stringss == "yes"strcmp(s, "yes") == 0
Doublesa == bfabs(a - b) < tolerance
Ranges1 < x < 31 < x && x < 3
ctype resultsisdigit(c) == 1isdigit((unsigned char) c) (any non-zero is true)
Signed vs unsignedi < strlen(s) - 1i + 1 < strlen(s)
Logical XORa ^ b on non-0/1 values!a != !b

Key points to remember

  • 0 is false, everything else is true; &&, ||, ! return 0 or 1.
  • Negate with De Morgan: flip each part and swap && / ||.
  • Test ranges with two comparisons joined by &&.
  • Order guards so that each one makes the next safe.
  • Give complex conditions names (bool age_ok = …;) or move them into a table.

Frequently asked questions

Is there a logical XOR operator in C?

No. For truth values use !a != !b (or (a != 0) != (b != 0)); ^ is bitwise and gives wrong answers for values such as 2 and 4.

Should I use nested ifs or &&?

if (a) { if (b) … } and if (a && b) … are equivalent. Use && when both conditions belong together; nest when each level has its own else-branch.

Why are my conditions "always true"?

Typically an || that should be && (x >= 18 || x <= 60), an assignment instead of a comparison, or a comparison of an unsigned value with 0. Compile with -Wall -Wextra: compilers flag most of these.

Where can I learn more?

Read if, else and switch in C and Operators in C, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links