﻿ ﻿Programs with Sequence Logic - C Programming For Beginners (2015)

# C Programming For Beginners (2015)

### Programs with Sequence Logic

In this chapter, we will explain the following:

§ The idea of reading data supplied by a user

§ How the scanf statement works

§ How to read numeric data using scanf

§ How to read string data using gets

§ Important principles of program writing using several examples

3.1 Introduction

In the last chapter, we introduced some of C’s basic data types—int, double and float—and used simple statements to illustrate their use. We now go a step further and introduce several programming concepts by writing programs using these types.

The programs in this chapter will be based on sequence logic—that simply means the statements in the programs are executed one after the other, from the first to the last. This is the simplest kind of logic, also called straight-linelogic. In the next chapter we will write programs which use selection logic—the ability of a program to test some condition and take different courses of action based on whether the condition is true or false.

3.2 Read Data Supplied by a User

Consider, again, Program P1.3.

Program P1.3

// This program prints the sum of 14 and 25. It shows how

// to declare variables in C and assign values to them.

#include <stdio.h>

int main() {

int a, b, sum;

a = 14;

b = 25;

sum = a + b;

printf("%d + %d = %d\n", a, b, sum);

}

C allows us to declare a variable and give it an initial value in one statement so we could write the program more concisely (without the comment) as Program P3.1:

Program P3.1

#include <stdio.h>

int main() {

int a = 14;

int b = 25;

int sum = a + b;

printf("%d + %d = %d\n", a, b, sum);

}

And since, as discussed earlier, we do not really need the variable sum, this program can be written as Program P3.2.

Program P3.2

#include <stdio.h>

int main() {

int a = 14;

int b = 25;

printf("%d + %d = %d\n", a, b, a + b);

}

This program is very restrictive. If we wish to add two other numbers, we will have to change the numbers 14 and 25 in the program to the ones required. We would then have to re-compile the program. And each time we want to add two different numbers, we would have to change the program. This can become very tedious.

It would be nice if we could write the program in such a way that when we run the program, we will have the opportunity to tell the program which numbers we wish to add. In this way, the numbers would not be tied to the program, and the program would be more flexible. When we ‘tell’ the program the numbers, we say we are supplying data to the program. But how do we get the program to ‘ask’ us for the numbers and how do we ‘tell’ the program what the numbers are?

We can get the program to prompt us for a number by printing a message such as:

Enter first number:

using a printf statement. The program must then wait for us to type the number and, when it is typed, read it. This can be done with the scanf statement. (Strictly speaking, printf and scanf are functions, but the distinction is not too important for us.) Before we look at this statement, let us rewrite the algorithm using these new ideas:

prompt for the first number

read the number

prompt for the second number

read the number

find the sum

print the sum

We can implement this algorithm in C as Program P3.3.

Program P3.3

//prompt for two numbers and find their sum

#include <stdio.h>

int main() {

int a, b;

printf("Enter first number: ");

scanf("%d", &a);

printf("Enter second number: ");

scanf("%d", &b);

printf("%d + %d = %d\n", a, b, a + b);

}

When run, the first printf statement will print:

Enter first number:

The scanf statement, explained shortly, will cause the computer to wait for the user to type a number.

Suppose she types 23; the screen will look like this:

Enter first number: 23

When she presses the “Enter” or “Return” key on the keyboard, scanf reads the number and stores it in the variable a.

The next printf statement then prompts:

Enter second number:

Again, scanf causes the computer to wait for the user to enter a number. Suppose she enters 18; scanf reads the number and stores it in the variable b. At this stage, the number 23 is stored in a and 18 is stored in b. We can picture this as follows:

 a 23 b 18

The program then executes the last printf statement and prints the following:

23 + 18 = 41

At the end, the screen will look as follows. Underlined items are typed by the user, everything else is printed by the computer:

Enter first number: 23

Enter second number: 18

23 + 18 = 41

Since the user is free to enter any numbers, the program will work for whatever numbers are entered, provided the numbers are small enough to be stored in an int variable. If not, strange results will be printed.

3.3 scanf

In Program P3.3, the statement

scanf("%d", &a);

causes the computer to wait for the user to type a number. Since a is an integer variable, scanf expects the next item in the data to be an integer or a value (like 3.8, say) which can be converted into an integer but dropping the fractional part. If it is not (for example, if it is a letter or or a special character) the program will give an error message such as “Invalid numeric format” and stop. We say the program will crash. If the data is valid, the number will be stored in the variable a. The statement

scanf("%d", &b);

works in a similar manner.

The statement consists of:

§ The word scanf

§ Left and right brackets

§ Two items (called arguments) inside the brackets, separated by a comma

As with printf, the first item is a string called the format string. In this example, the string consists of the format specification %d only. It specifies the type of data to be read. Here, %d is used to indicate that an integer value is to be read.

The second argument specifies where to store the value read. Even though we want the value stored in a, scanf requires us to specify this by writing &a. The quick explanation is that we must tell scanf the address of the memory location where the value is to be stored; &a stands for “address of a”. You will need to take it on faith that in order to read a value into a variable using scanf, the variable must be preceded by &, as in &a and &b. Note that this applies to the scanf statement only. Other than this, the variable is used in its normal form (without &) as in:

printf("%d + %d = %d\n", a, b, a + b);

We can use scanf to read more than one value at a time. For example, suppose we want to read 3 integer values for variables a, b and c. To do so, we would need to write %d three times in the format specification, thus:

scanf("%d %d %d", &a, &b, &c);

When this statement is executed, it looks for three integers. The first one is stored in a, the second in b and the third in c. It is up to the user to ensure that the next three items in the data are integers. If this is not so, an “Invalid numeric format” message will be printed and the program will crash.

When entering the data, the numbers must be separated by one or more spaces, like this:

42 -7 18

When using scanf, data can be supplied in flexible ways. The only requirement is that the data be supplied in the correct order. In this example, the three numbers could be supplied as above or like this:

42

-7

18

or this:

42 -7

18

or even with a blank line:

42

-7 18

Spaces, tabs and blank lines (so-called whitespace) do not matter; scanf will simply keep reading data, ignoring spaces, tabs and blank lines, until it finds the three integers. However, we emphasize that if any invalid character is encountered while reading the data, the program will crash. For instance, if the user types

42 -7 v8

or

42 = 18 24

the program will crash. In the first case, v8 is not a valid integer and, in the second case, = is not a valid character for an integer.

3.3.1 Read Data Into a float Variable

If we wish to read a floating-point number into a float variable x, we can use

scanf("%f", &x);

The specification %f is used to read a value into a float (but not double, see next section) variable. When executed, scanf expects to find a valid floating-point constant in the data. For example, any of the following will be acceptable:

4.265

-707.96

2.345E+1

In the last case, there must be no spaces, for instance, between the 5 and the E or between the E and the + or between the + and the 1. The following will all be invalid for reading the number 23.45:

2.345 E+1

2.345E +1

2.345E+ 1

3.3.2 Read Data Into a double Variable

If we wish to read a floating-point number into a double variable, y, we can use

scanf("%lf", &y);

The specification %lf (percent ell f) is used to read a value into a double variable. Apart from the specification, data is entered the same way for float and double variables. Be careful—you cannot use %f for reading data into a double variable. If you do, your variable will contain nonsense. However, as you have seen, you can use %f for printing the value of a double variable.

When entering data for a float/double variable, an integer is acceptable. If you enter 42, say, it will be interpreted as 42.0. But, as discussed above, if you enter a floating-point constant (e.g. 2.35) for an int variable, it will be truncated (to 2, in this example).

If you need to, you can read values into more than one variable using one scanf statement. If x and y are double variables, you can use

scanf("%lf %lf", &x, &y);

to read values into x and y. When executed, scanf expects to find two valid floating-point (or integer) constants next in the data. The first is stored in x and the second in y. Any number of spaces or blank lines can come before, between or after the numbers.

You can also read values for int, double or float variables in the same scanf statement. You just have to ensure that you use the correct specification for each variable. Suppose item and quantity are int, and price is double. The statement

scanf("%d %lf %d", &item, &price, &quantity);

expects to find 3 numbers next in the data.

§ The first must be an int constant which will be stored in item.

§ The second must be a double (or int) constant which will be stored in price.

§ The third must be an int constant which will be stored in quantity.

The following are all valid data for this scanf statement:

4000 7.99 8.7 // 8.7 is truncated to 8

3575 10 44 // price will be interpreted as 10.00

5600 25.0 1

As usual, any amount of whitespace may be used to separate the numbers.

The following are all invalid data for this scanf statement:

4000 7.99 x.8 // x.8 is not an integer constant

25cm 10 44 // 25cm is not an integer constant

560 25 amt = 7 // a is not a valid numeric character

When scanf fetches a number, it remains poised just after the number; a subsequent scanf will continue to read data from that point. To illustrate, suppose some data is typed as

4000 7.99 8

and consider the statements

scanf("%d", &item);

scanf("%lf", &price);

scanf("%d", &quantity);

The first scanf will store 4000 in item. On completion, it remains poised at the space after 4000. The next scanf will continue reading from that point and will store 7.99 in price. This scanf will stop at the space after 7.99. The third scanf will continue reading from that point and store 8 in quantity. This scanf will stop at the character after 8; this may be a space or the end-of-line character. Any subsequent scanf will continue reading from that point.

It is useful to imagine a “data pointer” moving through the data as data items are read. At any time, it marks the position in the data from which the next scanf will start looking for the next item of data.

3.4 Read Strings

In Section 2.6, we saw how to declare a variable to hold a string value. For example, the declaration

char item[50];

lets us store a string value (of maximum length 49) in item. We also saw how we can assign a string value to item using the standard string function, strcpy.

Now we show you how to read a value from the input into item. There are several ways to do this in C. We will use the gets (usually pronounced get s not gets) statement (more precisely, a function), as in:

gets(item);

This reads characters and stores them in item starting from the current position of the data pointer until the end-of-line is reached. The end-of-line character is not stored. The data pointer is positioned at the beginning of the next line.

For example, if the data line is

Right front headlamp

then the string Right front headlamp is stored in item. The effect is the same as if we had written

strcpy(item, "Right front headlamp");

The alert reader will notice that we did not put an & before item, as we have been doing for reading numbers with scanf. For now, just note that item is a “character array” and the rule in C is that we must not put & before an array name when reading data into it. You may understand this better after we discuss arrays in Chapter 8. The quick explanation is that an array name denotes the “address of the first element of the array” so there is no need for & to get the address. For now, just think of it as a rule that you need to follow.

Consider the following statements (assume the declaration char name[50]):

printf("Hi, what’s your name? ");

gets(name);

printf("Delighted to meet you, %s\n", name);

When executed,

§ The printf statement will ask for your name

§ gets will wait for you to type your name. When typed, the name will be stored in the variable name

§ printf will then print a greeting using your name

Your computer screen will look as follows (assuming Birdie is typed as the name):

Hi, what’s your name? Birdie

Delighted to meet you, Birdie

3.5 Examples

We now write programs to solve a few problems. You should try solving the problems before looking at the solutions. In the sample runs, the underlined items are typed by the user; everything else is printed by the computer.

3.5.1 Problem 1 - Average

Write a program to request 3 integers and print their average to 1 decimal place. The program should work as follows:

Enter 3 integers: 23 7 10

Their average is 13.3

A solution is shown as Program P3.4.

Program P3.4

//request 3 integers; print their average

#include <stdio.h>

int main() {

int a, b, c;

double average;

printf("Enter 3 integers: ");

scanf("%d %d %d", &a, &b, &c);

average = (a + b + c) / 3.0;

printf("\nTheir average is %3.1f\n", average);

}

Points to note about Program P3.4:

§ The variable average is declared as double instead of int since the average may not be a whole number.

§ If whole numbers are not entered in the data, the program will crash or, at best, give incorrect results.

§ We use 3.0 instead of 3 in calculating the average. This forces a floating-point division to be performed. If we had used 3, an integer division would be performed, giving 13.0 as the answer for the sample data, above.

§ In the last printf, the first \n is used to print the blank line in the output.

§ We could have declared average and assigned to it in one statement, like this:

double average = (a + b + c) / 3.0;

§ The variable average is not really necessary in this program. We could calculate and print the average in the printf statement with

printf("\nTheir average is %3.1f\n", (a + b + c) / 3.0);

3.5.2 Problem 2 - Square

Write a program to request a whole number and print the number and its square. The program should work as follows:

Enter a whole number: 6

Square of 6 is 36

A solution is shown as Program P3.5.

Program P3.5

//request a whole number; print its square

#include <stdio.h>

int main() {

int num, numSq;

printf("Enter a whole number: ");

scanf("%d", &num);

numSq = num * num;

printf("\nSquare of %d is %d\n", num, numSq);

}

Points to note about Program P3.5:

§ To make the output readable, note the space after f and the spaces around is. If these spaces are omitted, the sample output will be

Square of6is36

§ The variable numSq is not really necessary. It can be omitted altogether and the same output printed with

printf("\nSquare of %d is %d\n", num, num * num);

§ The program assumes an integer will be entered; if anything other than an integer is entered, the program will crash or give incorrect results. To cater for numbers with a point, declare num (and numSq, if used) as double.

3.5.3 Problem 3 - Banking

The following data are given for a customer in a bank: name, account number, average balance and number of transactions made during the month. It is required to calculate the interest earned and service charge.

The interest is calculated as follows:

interest = 6% of average balance

and the service charge is calculated by this:

service charge = 50 cents per transaction

Write a program to read the data for the customer, calculate the interest and service charge, and print the customer’s name, average balance, interest and service charge.

The following is a sample run of the program:

Name? Alice Wonder

Account number? 4901119250056048

Average balance? 2500

Number of transactions? 13

Name: Alice Wonder

Average balance: \$2500.00

Interest: \$150.00

Service charge: \$6.50

A solution is shown as Program P3.6.

Program P3.6

//calculate interest and service charge for bank customer

#include <stdio.h>

int main() {

char customer[30], acctNum[30];

double avgBalance, interest, service;

int numTrans;

printf("Name? ");

gets(customer);

printf("Account number? ");

gets(acctNum);

printf("Average balance? ");

scanf("%lf", &avgBalance);

printf("Number of transactions? ");

scanf("%d", &numTrans);

interest = avgBalance * 0.06;

service = numTrans * 0.50;

printf("\nName: %s\n", customer);

printf("Average balance: \$%3.2f\n", avgBalance);

printf("Interest: \$%3.2f\n", interest);

printf("Service charge: \$%3.2f\n", service);

}

This problem is more complicated than those we have seen so far. It involves more data and more processing. But we can simplify its solution if we tackle it in small steps.

Firstly, let us outline an algorithm for solving the problem. This can be:

prompt for and read each item of data

calculate interest earned

calculate service charge

print required output

The logic here is fairly straightforward and a little thought should convince us that these are the steps required to solve the problem.

Next, we must choose variables for the data items we need to store.

§ For the customer’s name, we need a string variable—we call it customer.

§ We may be tempted to use an integer variable for the account number but this is not a good idea for two reasons: an account number may contain letters (as in CD55887700) or it may be a very long integer, too big to fit in an int variable. For these reasons, we use a string variable which we call acctNum.

§ The average balance may contain a decimal point and must be stored in a double variable; we call it avgBalance.

§ The number of transactions is a whole number so we use an int variable, numTrans.

Next, we need variables to store the interest and service charge. Since these may contain a decimal point, we must use double variables—we call them interest and service.

Prompting for and reading the data are fairly straightforward, given what we have covered so far. We need only emphasize that when numeric data is being entered, it must be a numeric constant. We cannot, for instance, enter the average balance as \$2500 or as 2,500. We must enter it as 2500 or 2500.0 or 2500.00.

The calculation of the interest and service charge presents the biggest challenge. We must specify the calculation in a form which the computer can understand and execute.

We cannot, for instance, write

interest = 6% of avgBalance;

or even

interest = 6% * avgBalance;

or

service = 50 cents per transaction;

We must express each right-hand side as a proper arithmetic expression, using appropriate constants, variables and operators. Therefore,

“6% of average balance” must be expressed as

avgBalance*0.06

or

0.06*avgBalance

and “50 cents per transaction” must be expressed as

0.50*numTrans

or

numTrans*0.5

or something similar, even

numTrans/2.0

Printing the output is fairly straightforward. Even though, for example, we cannot use \$ when entering data for average balance, we can print a dollar sign in front of it when we print its value. All we need to do is print \$ as part of a string. How this is done is shown in the program. Similarly, we print the interest and service charge labelled with a dollar sign.

We use the specification %3.2f for printing avgBalance. We intentionally use a small field width of 3 so that avgBalance is printed using only the exact number of print columns needed for printing its value. This ensures that its value is printed right next to the dollar sign. Similar remarks apply to interest and service.

3.5.4 Problem 4 – Tickets

At a football match, tickets are sold in 3 categories: reserved, stands and grounds. For each of these categories, you are given the ticket price and the number of tickets sold. Write a program to prompt for these values and print the amount of money collected from each category of tickets. Also print the total number of tickets sold and the total amount of money collected.

We will write the program to operate as follows when run:

Reserved price and tickets sold? 100 500

Stands price and tickets sold? 75 4000

Grounds price and tickets sold? 40 8000

Reserved sales: \$50000.00

Stands sales: \$300000.00

Grounds sales: \$320000.00

12500 tickets were sold

Total money collected: \$670000.00

As shown, we prompt for and read two values at a time, the price and the number of tickets sold.

For each category, the sales is calculated by multiplying the ticket price by the number of tickets sold.

The total number of tickets sold is calculated by adding the number of tickets sold for each category.

The total money collected is calculated by adding the sales for each category.

An outline of the algorithm for solving the problem is as follows:

prompt for and read reserved price and tickets sold

calculate reserved sales

prompt for and read stands price and tickets sold

calculate stands sales

prompt for and read grounds price and tickets sold

calculate grounds sales

calculate total tickets

calculate total sales

print required output

A solution is shown as Program P3.7. The price can be entered as an integer or double constant; the number of tickets must be entered as an integer constant.

Program P3.7

//calculate ticket sales for football match

#include <stdio.h>

int main() {

double rPrice, sPrice, gPrice;

double rSales, sSales, gSales, tSales;

int rTickets, sTickets, gTickets, tTickets;

printf("Reserved price and tickets sold? ");

scanf("%lf %d", &rPrice, &rTickets);

rSales = rPrice * rTickets;

printf("Stands price and tickets sold? ");

scanf("%lf %d", &sPrice, &sTickets);

sSales = sPrice * sTickets;

printf("Grounds price and tickets sold? ");

scanf("%lf %d", &gPrice, &gTickets);

gSales = gPrice * gTickets;

tTickets = rTickets + sTickets + gTickets;

tSales = rSales + sSales + gSales;

printf("\nReserved sales: \$%3.2f\n", rSales);

printf("Stands sales: \$%3.2f\n", sSales);

printf("Grounds sales: \$%3.2f\n", gSales);

printf("\n%d tickets were sold\n", tTickets);

printf("Total money collected: \$%3.2f\n", tSales);

}

EXERCISES 3

1. For each of the following, give examples of data which will be read correctly and examples of data which will cause the program to crash. Assume the declaration

2. int i, j; double x, y;);

3. (a) scanf("%d %d", &i, &j);

4. (b) scanf("%lf %lf", &x, &y);

5. (c) scanf("%d %lf %d", &i, &x, &j);

6. For 1(c), state what will be stored in i, x and j for each of the following sets of data:

7. (a) 14 11 52

8. (b) -7 2.3 52

9. (c) 0 6.1 7.0

10. (d) 1.0 8 -1

11. Write a program which requests a user to enter a weight in kilograms, and converts it to pounds. (1 kilogram = 2.2 pounds).

12. Write a program which requests a length in centimetres and converts it to inches. (1 inch = 2.54 cm).

13. Assuming that 12 and 5 are entered as data, identify the logic error in the following statements (a, b, c, d and e are int):

14. scanf("%d %d", &a, &b);

15. c = (a - b) * 2;

16. d = e + a;

17. e = a / (b + 1);

18. printf("%d %d %d\n", c, d, e);

19. When the error is corrected, what is printed?

20. What is printed by the following (a, b, and c are int)?

21. a = 13;

22. b = a + 12;

23. printf("%d %d\n", a, b);

24. c = a + b;

25. a = a + 11;

26. printf("%d %d %d\n", a, b, c);

27. Write a program which requests a price and a discount percent. The program prints the original price, the discount amount and the amount the customer must pay.

28. Same as 7, but assume that 15% tax must be added to the amount the customer must pay.

29. Write a program to calculate electricity charges for a customer. The program requests a name, previous meter reading and current meter reading. The difference in the two readings gives the number of units of electricity used. The customer pays a fixed charge of \$25 plus 20 cents for each unit used.

30. Print all the data, the number of units used and the amount the customer must pay, appropriately labelled.

31. Modify 9 so that the program requests the fixed charge and the rate per unit.

32. Write a program to request a student’s name and marks in 4 subjects. The program must print the name, total marks and average mark, appropriately labelled.

33. Write a program which requests a person’s gross salary, deductions allowed and rate of tax (e.g. 25, meaning 25%) and calculates his net pay as follows:

34. Tax is calculated by applying the rate of tax to the gross salary minus the deductions.

35. Net pay is calculated by gross salary minus tax.

36. Print the gross salary, tax deducted and net pay, appropriately labelled.

37. Also print the percentage of the gross salary that was paid in tax.

38. Make up appropriate sets of data for testing the program.

39. Write a program which, when run, works as follows (underlined items are typed by the user):

40. Hi, what’s your name? Alice

41. Welcome to our show, Alice

42. How old are you? 27

43. Hmm, you don’t look a day over 22

44. Tell me, Alice, where do you live? Princes Town

45. Oh, I’ve heard Princes Town is a lovely place

46. A ball is thrown vertically upwards with an initial speed of U metres per second. Its height H after time T seconds is given by

47. H = UT - 4.9T2

48. Write a program which requests U and T and prints the height of the ball after T seconds.

49. Write a program to calculate the cost of carpeting a rectangular room in a house. The program must do the following:

§ Request the length and breadth of the room (assume they are in metres)

§ Request the cost per square metre of the carpet

§ Calculate the area of the room

§ Calculate the cost of the carpet for the room

§ Print the area and the cost, appropriately labelled

1. Write a program which, given a length in inches, converts it to yards, feet and inches. (1 yard = 3 feet, 1 foot = 12 inches). For example, if the length is 100 inches, the program should print 2 yd 2 ft 4 in.

﻿