Main Content

Decisions - small ones, or big ones?

Archive - Originally posted on "The Horse's Mouth" - 2007-12-18 07:30:56 - Graham Ellis

When you're traveling, you'll sometimes come to a point at which you make a decision - to go one way or to go another. Sometimes the decision is a small one - for example, if I'm driving through Marlborough there's a choice of the town centre or the road around the back; whichever I take, they come back together again very quickly. And at other times the decision is much bigger - we decided to fly on our recent trip to Slovenia, and once that decision was made and we started to act on it, the whole course of our time from Sunday lunchtime through to the following Friday evening was mapped out as alternative "B" rather than "A".

All the programming languages that we teach have conditional statements - if statements, or commands - and there's a requirement in every language to define the start and end of the conditional code - where the two tracks merge again, as well as where they separate. There are a variety of ways of doing this - using insets (Python), using an endif, if or do, done pair (Shell programming) but perhaps the most common is to use curly braces. That applies in PHP and in C (today's example) and - slightly varied - in Perl and Tcl.

#include <stdio.h>
  
int main() {
  int dayslong;
  printf("How long is the course ");
  scanf("%d",&dayslong);
  
  /* Condition applies only to first printf */
  if (dayslong < 5)
    printf ("Less than a week\n");
    printf ("No weekend activities\n");
  printf ("First Job done\n");
  
  /* Condition applies to TWO printf-s */
  if (dayslong < 5) {
    printf ("Less than a week\n");
    printf ("No weekend activities\n"); }
  printf ("Second Job done\n");
}


In the first section, no curly braces are used and so the condition applies ONLY to the first printf, but in the second section with curly braces, the condition applies to the first and second printfs.

Let's run that ...

How long is the course 7
No weekend activities
First Job done
Second Job done
[trainee@daisy cd07]$ ./cb
How long is the course 4
Less than a week
No weekend activities
First Job done
Less than a week
No weekend activities
Second Job done
[trainee@daisy cd07]$