How to Make a Simple Comparisons in C Programming - dummies

How to Make a Simple Comparisons in C Programming

By Dan Gookin

You make comparisons all the time, so you shouldn’t avoid comparisons in C programming. What will you wear in the morning? Should you avoid Bill’s office because the receptionist says he’s “testy” today? And how much longer will you put off going to the dentist? The computer is no different, albeit the comparisons it makes use values, not abstracts.


#include <stdio.h>
int main()
  int a,b;
  a = 6;
  b = a - 2;
  if( a > b)
    printf("%d is greater than %dn",a,b);

Exercise 1: Create a new project using the source code shown in A Simple Comparison. Build and run. Here’s the output you should see:

6 is greater than 4

Fast and smart, that’s what a computer is. Here’s how the code works:

Line 5 declares two integer variables: a and b. The variables are assigned values in Lines 7 and 8, with the value of variable b being calculated to be 2 less than variable a.

Line 10 makes a comparison:

if( a > b)

Programmers read this line as, “If a is greater than b.” Or when they’re teaching the C language, they say, “If variable a is greater than variable b.” And, no, they don’t read the parentheses.

Lines 11 through 13 belong to the if statement. The meat in the sandwich is Line 12; the braces (curly brackets) don’t play a decision-making role, other than hugging the statement at Line 12. If the comparison in Line 10 is true, the statement in Line 12 is executed. Otherwise, all statements between the braces are skipped.

Exercise 2: Edit the source code from A Simple Comparison so that addition instead of subtraction is performed in Line 8. Can you explain the program’s output?