Programming in C

(Barry) #1

80 Chapter 6 Making Decisions


which is TRUE if cis within the range of characters 'A'through 'Z'; that is, if cis an
uppercase letter.These tests work on all computer systems that store characters inside the
machine in a format known as ASCII format.^1
If the variable cis an alphabetic character, the first iftest succeeds and the message
It's an alphabetic character.is displayed. If the test fails, the else ifclause is
executed.This clause determines if the character is a digit. Note that this test compares
the character cagainst the characters'0'and '9'and notthe integers0 and 9.This is
because a character was read in from the terminal, and the characters '0'to '9'are not
the same as the numbers 0–9. In fact, on a computer system that uses the ASCII format
mentioned previously, the character '0'is actually represented internally as the number
48, the character '1'as the number 49, and so on.
If cis a digit character, the phrase It's a digit.is displayed. Otherwise, if cis not
alphabetic and is not a digit, the final elseclause is executed and displays the phrase
It’s a special character.Execution of the program is then complete.
You should note that even though scanfis used here to read just a single character,
the Enter (or Return) key must still be pressed after the character is typed to send the
input to the program. In general, whenever you’re reading data from the terminal, the
program doesn’t see any of the data typed on the line until the Enter key is pressed.
For your next example, suppose you want to write a program that allows the user to
type in simple expressions of the form
number operator number
The program evaluates the expression and displays the results at the terminal, to two
decimal places of accuracy.The operators that you want to have recognized are the nor-
mal operators for addition, subtraction, multiplication, and division. Program 6.8 makes
use of a large ifstatement with many else ifclauses to determine which operation is
to be performed.

Program 6.8 Evaluating Simple Expressions
/* Program to evaluate simple expressions of the form
number operator number */

#include <stdio.h>

int main (void)
{
float value1, value2;
char operator;


  1. It’s better to use routines in the standard library called islower and isupper and avoid the internal
    representation issue entirely. To do that, you need to include the line #include <ctype.h>in
    your program. However, we’ve put this here for illustrative purposes only.

Free download pdf