Chapter chap5 section 4
It is now time to consider some new types of statement. The first of these are the if-statement and the else-statement . The syntax of an if-statement is
if (<expression>) <statement>
and the meaning is that if the expression has a non-zero value then the statement included within the
if-statement , sometimes called the controlled statement, is executed. If the value of the expression is
zero then the controlled statement is not executed.
An if-statement may be followed immediately by an else-statement . The syntax of an else-statement is else <statement>
and the meaning is that the controlled statement is executed if the controlling expression of the immediately preceding if-statement had the value zero.
A simple example program called if1 is in order. main()
{
int x;
printf("Enter a number "); scanf("%d",&x);
if(x%2 == 1) printf("%d is odd\n",x); else printf("%d is even\n",x); }
and a typical dialogue is $ if1 Enter a number 27 27 is odd $ if1 Enter a number 0 0 is even $ if1 Enter a number 1000 1000 is even
To understand the behaviour of this program it is only necessary to remember what the "%" operator does. The value of the expression "x%2" is the remainder when x is divided by 2, i.e. 0 when x is even and 1 when x is odd, so the value of "x%2 == 1" is 1 if x is odd and 0 if x is even.
It is quite common practice to omit the "== 1" in the condition in cases such as this since the value of "x%2" is 0 or 1 anyway.
The next example uses the relational and logical operators. It reads in three numbers and determines whether the middle number lies between the other two. Note how the controlled statements are indented for greater readability, this is common practice. This program is called if2.
main() {
int p,q,r;
printf("Enter three numbers "); scanf("%d%d%d",&p,&q,&r);
if(( p<q && q<r ) || ( p>q && q>r))
printf("%d lies between %d and %d\n",q,p,r); else
printf("%d does not lie between %d and %d\n", q,p,r);
}
and a typical dialogue is shown below $ if2
Enter three numbers 1 2 3 2 lies between 1 and 3 $ if2
Enter three numbers 3 2 1 2 lies between 3 and 1 $ if2
Enter three numbers 10 10 11
10 does not lie between 10 and 11
The expression associated with the "if" could have been written p<q && q<r || p>q && q>r
The parentheses were not essential because "&&" has a higher precedence than "||", however the human reader may well have forgotten this and the extra typing is a small price to pay for greater readability and clarity.
The controlled statement associated with an if-statement may be any valid statement including another
if-statement , however it can only be a single statement. In the following program called if3 the programmer has attempted to associate two statements with the if .
main() { int x; printf("Enter a number "); scanf("%d",&x); if(x%3 == 0) printf("The number %d",x); printf("is divisible by 3\n"); }
The program is intended to report whether the input number is divisible by 3. Remember that the value of the expression x%3 is non-zero if x is not divisible by 3. What actually happened is shown below. $ if3
Enter a number 27
The number 27 is divisible by three $ if3
Enter a number 10
The problem here is, of course, that the final printf() statement is not controlled by the if and is, in fact, the statement after the if-statement so it is always executed. What is required is some way of grouping statements together in a single "super" statement. C provides just such a mechanism known as a
compound statement. A compound statement is simply a list of ordinary statements enclosed in braces, i.e. {..}. A compound statement can be used anywhere where the ANSI standard requires a statement. The correct version of the if3 program, called if4, is shown below.
main() { int x; printf("Enter a number "); scanf("%d",&x); if(x%3 == 0) { printf("The number %d",x); printf("is divisible by 3\n"); } }
and a typical dialogue $ if4
Enter a number 27
The number 27 is divisible by three $ if4
Enter a number 10 $
The expression associated with the "if" could have been written !(x%3)
the parentheses being necessary since the ! operator has a higher precedence than the % operator. A further, slightly more complex example is shown below. This program is called if5.
main() { double x; printf("Enter a number "); scanf("%lf",&x); if(x > 0.0) { printf("%10.5lf is positive\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); } else { if (x == 0.0) { printf("Zero - no reciprocal\n"); } else http://www.scit.wlv.ac.uk/~jphb/cbook/html/chap5.if.else.html (3 of 7) [02/04/2002 09:22:45]
{
printf("%10.5lf is negative\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); }
} }
and a typical dialogue $ if5
Enter a number 3.5
A positive number It's reciprocal is 0.28571 $ if5
Enter a number 0.0 Zero - no reciprocal $ if5
Enter a number -2.89
A negative number It's reciprocal is -0.34602
Notice how the if and else keywords and the { and } symbols marking out the controlled compound statements are all lined up. This is highly desirable and makes understanding complex programs much easier for the human reader. As in all examples in these notes the indentation has been achieved using TABs in the source file.
Some programmers prefer to lay this program out in a slightly different way. The initial "{" appears on the same line as the condition, the statements within the controlled compound statement are indented and the final "}" is lined up with the if keyword.
main() { double x; printf("Enter a number "); scanf("%lf",&x); if(x > 0.0) { printf("%10.5lf is positive\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); } else {
if (x == 0.0) {
printf("Zero - no reciprocal\n"); } else {
printf("%10.5lf is negative\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); }
} }
There are some other conventional layouts, consult any reputable textbook to see examples. The choice of layout is left to personal taste and local standards. However it is important to be consistent in layout once you have decided what convention to adopt.
In the both the previous examples there was a compound statement associated with the condition "x==0.0". The list of statements within the {..} consisted of a single statement. Under these
circumstances there is no need for the braces and the following is perfectly correct. The program could be further shortened and simplified by combining successive printf() s into a single printf().
{ double x; printf("Enter a number "); scanf("%lf",&x); if(x > 0.0) { printf("%10.5lf is positive\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); } else { if (x == 0.0) printf("Zero - no reciprocal\n"); else { printf("%10.5lf is negative\n",x);
printf("%10.5lf is the reciprocal\n",1.0/x); }
} }
A more interesting example of the use of multiple if statements is illustrated by the following example. This program reads in a simple expression with a very restricted format and prints out its value.
main() {
int n1,n2; int val; char op;
printf("Enter a simple expression "); scanf("%d%c%d",&n1,&op,&n2); if(op == '+') val = n1 + n2; else if(op == '-') val = n1 - n2; else if(op == '/') val = n1 / n2; else if(op == '*') val = n1 * n2; else {
printf("?? operator %c\n",op); exit(1);
}
printf("%d%c%d = %d\n",n1,op,n2); }
A typical dialogue is shown below. $ if6
Enter a simple expression 2+2
2+2 = 4 $ if6
Enter a simple expression 29-11 29-11 = 18
$ if6
Enter a simple expression 23*5 23*5 = 115
$ if6
Enter a simple expression 11%5 Unknown operator %
A particularly interesting point concerns the sequence of else if lines. To understand this, you should note that an else statement is associated with the immediately preceding if statement in spite of any impressions to the contrary given by program layout. If you're uncertain about this it is illustrative to rearrange the text of the program to conform to the layout described earlier.
Program execution proceeds by evaluating the relational expressions "c == '+'", "c == '-'", etc., one after the other until one has the value 1. The associated controlled statement is then executed and then the statement after the final else statement is executed.
main() {
int n1,n2; int val; char op;
printf("Enter a simple expression "); scanf("%d%c%d",&n1,&op,&n2); if(op == '+') val = n1 + n2; else if(op == '-') val = n1 - n2; else if(op == '/') val = n1 / n2; else if(op == '*') val = n1 * n2; else {
printf("?? operator %c\n",op); exit(1);
}
printf("%d%c%d = %d\n",n1,op,n2); }
This program was obtained from the previous one simply by changing the indentation to show the structure more clearly. Either layout is correct and acceptable, if there are a large number of conditions the advantages of the first form are obvious.
A new library function, exit(), appears in this program. The effect of this library function is to terminate the program immediately and return to the host operating system. The integer parameter of exit() may be accessible to the host operating system as a program return or exit code. The details of this mechanism are, of course, host operating system dependant. Different values can be used to indicate successful or unsuccessful operation of the program. Returning 0 to indicate succesful operation and using non-zero integer values to indicate various errors is a common practice. If you don't include a call to exit() in your program, it simply "drops off the end", this is perfectly safe but does mean that the value returned to the
The dangling else problem.
●
equality and assignment operator confusion
●
Local Variables in compound statements
●
Loops and Conditions -
Exercises
Chapter chap5 section 11
Write a program that will read in 4 numbers and print out their average. 1.
Write a program to read in a set of numbers and print out their average. The program will start by prompting the user for the number of numbers to be read in and will then prompt for the individual numbers with a prompt such as
Enter Number 23
to indicate to the user which data item is currently being entered. Do something special when prompting for the last number.
Note that there is no need to store all the individual numbers, it is sufficient to maintain a running total.
2.
Modify the previous program to print out the largest and smallest number read in as well as the average. Also change the prompt to show the number of numbers still to be entered.
3.
Write a program to prompt the user for an integer and calculate the sum of all the integers up to and including the input value. Print out the result.
4.
Modify the previous program to use floating point arithmetic to add up the reciprocals of all the integers up to and including the input value.
5.
Further modify the previous program to print out a list of reciprocal sums for every integer up to and including the input value.
I.e. print out the sum of the reciprocals of the integers up to and including 1, up to and including 2, up to and including 3 etc., etc.
6.
Write a program to print out the integers from 40 to 127 in decimal, octal, hexadecimal and also print out the equivalent character.
7.
Modify the previous program to list the values 4 to a line. 8.
As a seasonal amusement some programmers like to print out a picture of a Chirstmas Tree looking like this.
* *** * *** ***** * 9. http://www.scit.wlv.ac.uk/~jphb/cbook/html/chap5.exercises.html (1 of 2) [02/04/2002 09:22:48]
*****
*******
|
---+---
The tree consists of a series of tiers (three in this case) of increasing size. Write a program to produce such a display having prompted the user for the number of tiers.
You could try putting a few baubles on the tree (using o or O).
A year is a leap year if it is divisble by 4 unless it is a century year (one that ends in 00) in which case it has to be divisible by 400. Write a program to read in a year and report whether it is a leap year or not.
10.