08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ■ Programs with Repetition Logic

We will then add lastName with

strcat(name, lastName);

Using our example, at the end of all this, name will contain Robin Hood.

In our program, we will use the specification %-15s to print name. This will print name left

justified in a field width of 15. In other words, all names will be printed using 15 print columns.

This is necessary for the output to line up neatly. To cater for longer names, you can increase the

field width.

To use the string functions, we must write the directive

#include <string.h>

at the head of our program if we want to use the string functions supplied by C.

Our program will need to check if the value in firstName is the string "END". Ideally, we

would like to say something like

while (firstName != "END") { //cannot write this in C

but we cannot do so since C does not allow us to compare strings using the relational operators.

What we can do is use the predefined string function strcmp (string compare).

If s1 and s2 are strings, the expression strcmp(s1, s2) returns the following values:

• 0 if s1 is identical to s2

• < 0 if s1 is less than s2 (in alphabetical order)

• > 0 if s1 is greater than s2 (in alphabetical order)

For example,

strcmp("hello", "hi") is < 0

strcmp("hi","hello") is > 0

strcmp("allo","allo") is 0

Using strcmp, we can write the while condition as

while (strcmp(firstName, "END") != 0)

If strcmp(firstName, "END") is not 0, it means that firstName does not contain the

word END so we have not reached the end of the data; the while loop is entered to process that

employee.

When faced with a program that requires so many things to be done, it is best to start by

working on part of the problem, getting it right, and then tackling the other parts. For this

problem, we can start by getting the program to read and process the data without counting,

finding the total or finding the highest-paid employee.

Program P5.8 is based on program P4.7 (Section 4.6.2).

115

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!