Sams Teach Yourself C in 24 Hours (17 page)

BOOK: Sams Teach Yourself C in 24 Hours
4.87Mb size Format: txt, pdf, ePub

The C language uses
scientific notation
to help you write lengthy floating-point numbers.

In scientific notation, a number can be represented by the combination of the
mantissa
and the
exponent
. The format of the notation is that the mantissa is followed by the exponent, which is prefixed by e or E. Here are two examples:

mantissaeexponent

and

mantissaEexponent

Please note that mantissa and exponent above are both placeholders and you need to replace them with numerical values.

For instance, 5000 can be represented by 5e3 in scientific notation. Likewise, -300 can be represented by -3e2, and 0.0025 by 2.5e-3.

Correspondingly, the format specifier, %e or %E, is used to format a floating-point number in scientific notation. The usage of %e or %E in the printf() function is the same as %f.

06 067231861x CH04 4.10.2000 11:00 AM Page 68

68

Hour 4

Naming a Variable

There are a few things to keep in mind when creating your own variable names.

Remember that since variable names are identifiers, you must follow the rules for identifiers that were outlined in the previous hour.

Just as function names should ideally reflect the task that the function performs, variable names should describe the value stored in the variable and what purpose it serves in your program or function. Most of the code samples so far have used single-letter variable names such as i, but as you write larger programs and more complicated functions it becomes increasingly more important to give your variables meaningful names.

Never use the C keywords reserved in the C language, or the names of the standard C library functions, as variable names in your C program.

Summary

In this lesson you learned about the following important C keywords and data types:

• The C keywords reserved in the C language

• The char data type and the %c format specifier

• The int data type and the %d format specifier

• The float data type and the %f format specifier

• Floating-point numbers can be suffixed with f or F to specify float. A floating-point number without a suffix is double by default.

• The possible ranges of the char, int, and float data types

• The double data type

• Scientific notation and the %e and %E format specifiers

• The rules you have to follow to make a valid variable name

In the next lesson you’ll learn more about the printf() function and other functions to deal with input and output.

Q&A

Q Why do characters have their unique numeric values?

A
Characters are stored in computers in the form of bits. The combinations of bits can be used to represent different numeric values. A character has to have a unique 06 067231861x CH04 4.10.2000 11:00 AM Page 69

Understanding Data Types and Keywords

69

numeric value in order to distinguish itself. Many computer systems support the ASCII character set, which contains a set of unique numeric values for up to 256 characters.

Please note that your computer may use a different character set than the ASCII character set. Then, all characters used by the C language except the null character may have different numeric values from the values represented by the ASCII character set.

Q How can you declare two character variables?

A
There are two ways to do the declaration. The first one is

...char variable-name1, variable-name2;

The second one is

char variable-name1;

char variable-name2;

Q What are
%c
,
%d
, and
%f
?

A
These are format specifiers. %c is used to obtain the character format; %d is for the integer format; %f is for the floating-point format. %c, %d, and %f are often used with C functions such as printf().

4

Q What are the main differences between the
int
data type (integer) and the
float
data type (floating-point)?

A
First, an integer does not contain any fraction parts, but a floating-point number does. A floating-point number must have a decimal point. In C, the float data type takes more bits than the int data type. In other words, the float data type has a larger range of numeric values than the int data type.

Also, the integer division truncates the fraction part. For instance, the integer division of 16/10 produces a result of 1, not 1.6.

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix C, “Answers to Quiz Questions and Exercises.”

Quiz

1. Are the integer divisions of 134/100 and 17/10 equal?

2. Is the result of 3000 + 1.0 a floating-point number? How about 3000/1.0?

06 067231861x CH04 4.10.2000 11:00 AM Page 70

70

Hour 4

3. How can you represent the following numbers in scientific notation?

• 3500

• 0.0035

• –0.0035

4. Are the following variable names valid?

• 7th_calculation

• Tom’s_method

• _index

• Label_1

Exercises

1. Write a program that prints out the numeric values of characters Z and z.

2. Given two numeric values, 72 and 104, write a program to print out the corresponding two characters.

3. For a 16-bit integer variable, can you assign the variable with an integer value of 72368?

4. Given the declaration double dbl_num = 123.456;, write a program that prints out the value of dbl_num in both floating-point and scientific notation formats.

5. Write a program that can print out the numeric value of the newline character (\n).

(Hint: assign ‘\n’ to a character variable.)

07 067231861x CH05 4.10.2000 11:00 AM Page 71

HOUR 5

Handling Standard Input

and Output

I/O, I/O, it’s off to work we go…

—The Seven Dwarfs (sort of)

In the last lesson you learned how to print out characters, integers, and floating-point numbers to the screen by calling the printf() function. In this lesson you’re going to learn more about printf(), as well as about the following functions, which are necessary to receive the input from the user or to print the output to the screen:

• The getc() function

• The putc() function

• The getchar() function

• The putchar() function

Before we jump into these new functions, let’s first get an idea about standard input and output (I/O) in C.

07 067231861x CH05 4.10.2000 11:00 AM Page 72

72

Hour 5

Understanding Standard I/O

A file contains related characters and numbers. Because all characters and numbers are represented in bits on computers, and a byte is a series of bits, the C language treats a file as a series of bytes. A series of bytes is also called a
stream
. In fact, the C language treats all file streams equally, although some of the file streams may come from a disk or tape drive, from a terminal, or even from a printer.

Additionally, in C, there are three file streams that are pre-opened for you — that is to say, they are always available for use in your programs:

• stdin—The standard input for reading.

• stdout—The standard output for writing.

• stderr—The standard error for writing error messages.

Usually, the standard input (stdin) file stream links to your keyboard, while the standard output (stdout) and the standard error (stderr) file streams point to your terminal screen. Also, many operating systems allow the user to redirect these file streams.

In fact, you’ve already used stdout. When you called the printf() function in the last lesson, you were actually sending the output to the default file stream, stdout, which points to your screen.

You’ll learn more on stdin and stdout in the following sections.

The C language provides many functions to manipulate file reading and

writing (I/O). The header file stdio.h contains the declarations for those functions. Therefore, always include the header file stdio.h in your C program before doing anything with file I/O.

Getting Input from the User

These days, typing on the keyboard is still the de facto standard way to input information into computers. The C language has several functions to tell the computer to read input from the user (typically through the keyboard.) In this lesson the getc() and getchar() functions are introduced.

Using the
getc()
Function

The getc() function reads the next character from a file stream, and returns the character as an integer.

07 067231861x CH05 4.10.2000 11:00 AM Page 73

Handling Standard Input and Output

73

Syntax Entry

AX

The syntax for the getc() function is

#include

YNT

int getc(FILE *stream);

S

Here FILE *stream declares a file stream (that is, a variable). The function returns the numeric value of the character read. If an end-of-file or error occurs, the function returns EOF.

For now, don’t worry about the FILE structure. More details about it are introduced in Hours 21, “Reading and Writing with Files,” and 22, “Using Special File Functions.” In this section, the standard input stream stdin is used as the file stream specified by FILE *stream.

Defined in the header file stdio.h, EOF is a constant. EOF stands for
end-of-file
. Usually, the value of EOF is -1. But keep using EOF, instead of -1, to indicate the end-of-file in your programs. That way, if you later use a compile or operating system that uses a different value, your program will still work.

Listing 5.1 shows an example that reads a character typed in by the user from the keyboard and then displays the character on the screen.

TYPE

LISTING 5.1

Reading in a Character Entered by the User

1: /* 05L01.c: Reading input by calling getc() */

5

2: #include

3:

4: main()

5: {

6: int ch;

7:

8: printf(“Please type in one character:\n”);

9: ch = getc( stdin );

10: printf(“The character you just entered is: %c\n”, ch);

11: return 0;

12: }

The following is the output displayed on the screen of my computer after I run the executable file, 05L01.exe, enter the character H, and press the Enter key: Please type in one character:

OUTPUT
H

The character you just entered is: H

07 067231861x CH05 4.10.2000 11:00 AM Page 74

74

Hour 5

You see in line 2 of Listing 5.1 that the header file stdio.h is included for both
ANALYSIS
the getc() and printf() functions used in the program. Lines 4–12 give the name and body of the main() function.

In line 6, an integer variable, ch, is declared; it is assigned the return value from the getc() function later in line 9. Line 8 prints out a message that asks the user to enter one character from the keyboard. As I mentioned earlier in this lesson, the printf() function call in line 8 uses the default standard output stdout to display messages on the screen.

In line 9, the standard input stream stdin is passed to the getc() function, which indicates that the file stream is from the keyboard. After the user types in a character, the getc() function returns the numeric value (that is, an integer) of the character. You see that, in line 9, the numeric value is assigned to the integer variable ch.

Then, in line 10, the character entered by the user is displayed on the screen via the help of printf(). Note that the character format specifier (%c) is used within the printf() function call in line 10. (Exercise 1 in this lesson asks you to use %d in a program to print out the numeric value of a character entered by the user.)

Using the
getchar()
Function

The C language provides another function, getchar(), that performs a similar function to getc(). More precisely, the getchar() function is equivalent to getc(stdin).

Syntax Entry

AX

The syntax for the getchar() function is

#include

YNT

int getchar(void);

S

Here void indicates that no argument is needed for calling the function. The function returns the numeric value of the character read. If an end-of-file or error occurs, the function returns EOF.

The program in Listing 5.2 demonstrates how to use the getchar() function to read the input from the user.

TYPE

LISTING 5.2

Reading in a Character by Calling getchar()

1: /* 05L02.c: Reading input by calling getchar() */

Other books

Plague: Death was only the beginning! by Donald Franck, Francine Franck
Count Zero by William Gibson
Shadow Country by Peter Matthiessen
Cryonic by Travis Bradberry
Stones for My Father by Trilby Kent
Poisoned Pearls by Leah Cutter
Strangers at Dawn by Elizabeth Thornton
Styxx (DH #33) by Sherrilyn Kenyon