21
This is part of the book COMPUTER PROGRAMMING THE C LANGUAGE by Adriana ALBU Conspress Publisher, Bucureşti, România, 2013 ISBN: 978-973-100-270-5

COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

This is part of the book

COMPUTER PROGRAMMING

THE C LANGUAGE

by Adriana ALBU

Conspress Publisher, Bucureşti, România, 2013 ISBN: 978-973-100-270-5

Page 2: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Chapter 5 Library functions

The C programming language is a very simple language. It only has few in-structions that can be used to solve different problems. But these instructions are not always enough. For instance, the C programming language doesn’t provide any method to read information from the keyboard or from a file, to display them on the screen or to write them in a file, to process strings, to work with mathematical functions and so on. For this reason, all C compilers also include a standard library of functions that implement the most frequently used tasks. This library contains several header files that gather certain categories of functions. The programmer can use (or can call) any library function; however, he is forced to specify, at the beginning of the program, in a #include di-rective, the name of the header file which contains the function that is used in the program.

In the following paragraphs some of the most frequently used library functions are described [BH92], [SL12]. These are gathered in several categories, accord-ing to the domain they are applied in.

5.1 Input/output functions This paragraph presents functions that are used to read information from the keyboard and to display them on the screen. The values that are read or written can be characters, strings or numbers of any type. The description begins with the output functions (used to print something on the screen: putchar, puts, printf) and continues with the input functions (used to read something from the keyboard: getchar, gets, scanf).

5.1.1 int putchar(int ch);

This function displays on the screen the character received as argument. If the function is performed successfully, it returns the character that was printed; otherwise, the constant EOF (end-of-file) is returned. The header file that con-tains this function is stdio.h.

Program 5.1.1 displays on the screen the character A. It can be observed that the header file required for the function putchar() was specified at the begin-ning of the program.

Page 3: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

2

Program 5.1.1 #include <stdio.h> void main(void){ putchar('A');

}

A second example (program 5.1.2) sends a variable of type char as argument to the function putchar(). This variable is declared, receives an initial value and then it is printed on the screen.

Program 5.1.2 #include <stdio.h> void main(void){ char var; var='A'; putchar(var);

}

In order to display a character on the screen, the function int putch(int c) from the conio.h header file can also be used. If succeeds, the function returns the character that was displayed; otherwise it returns EOF. The program example 5.1.3 uses this function to print the character A.

Program 5.1.3 #include <conio.h> void main(void){ putch('A');

}

5.1.2 int puts(const char *s);

The call of this function prints on the screen the string s received as argument and sets the position of the cursor to the next line. If succeeds, a non-negative value is returned; on error, the function returns the value EOF. This function is part of the stdio.h header file.

In program 5.1.4 the function puts()receives as argument directly the string that must be displayed. It is also possible to send a string variable that was previously declared, as argument to the function.

Page 4: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

3

Programul 5.1.4 #include <stdio.h> void main(void){ puts("This is a programming course.");

}

5.1.3 int printf(const char* format [, argument, ...]);

The function is used when formatted data has to be printed on the screen. The header file that must be included in the program is stdio.h. If succeeds, this function returns the number of printed characters; on error, it returns a negative value.

In a very simple way, this function can be used to print text on screen; in this case, the list of arguments [, argument, ...] is missing and the string format contains only the text that has to be written. Program 5.1.5 depicts this way of using function printf().

Program 5.1.5 #include <stdio.h> void main(void){ printf("The C programming language is useful.");

}

Nevertheless, function printf()proves its qualities when it is used to print formatted values on the screen. This function accepts a set of arguments (varia-bles or constants); a formatting specified through a string is applied to these arguments. The formatted arguments are then displayed on the screen.

The string format may contain:

a simple text, printed as it is;

the special character % followed by a format descriptor that, in turn, may contain:

o the minus sign (-) which sets that the printed element is to be aligned to the left (the default alignment is to the right);

o a number that specifies the minimum length of the field where the element is printed;

Page 5: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

4

o a dot (.) which separates the field’s length by the precision used for the displayed element;

o a number that specifies the precision (the number of decimals that will be displayed);

o the conversion type character – a character that indicates the type of the printed argument; some of the most frequently used con-version type characters are:

c – character;

s – string;

d, i – signed decimal integer;

u – unsigned decimal integer;

f – floating point number (float, double).

o for instance: %c prints a character, %d prints an integer number, %5.2f prints a real number with at least 5 characters, two of these characters being reserved to the decimal part, %-15s prints, using at least 15 characters, a left aligned string.

the special sign \ followed by:

o a character that specifies the place of the next printing:

\b – moves the cursor (the point where the printing be-gins) back with one character, deleting that character;

\n – the next printing will be done on a new line;

\t – moves the cursor with a horizontal tab to the right.

o a character that cannot be printed in any other way:

\\ – prints backslash (\);

\’ – prints apostrophe;

\" – prints quotation marks.

The program from the example 5.1.6 calls function printf() in order to print the value of the variable weight, which was previously declared and received an initial value. Once the program is run, the text The suitcase is 17 kg will be displayed on the screen. It can be observed that the value of the variable weight was inserted in the text where the descriptor %d appears.

Page 6: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

5

Program 5.1.6 #include <stdio.h> void main(void){ int weight=17; printf("The suitcase is %d kg.", weight);

}

Function printf()also allows the use of some expressions as arguments. Example 5.1.7 prints the sum of two numbers, sum that is calculated when function printf() is called. The result is a real number (float), displayed with two decimals precision. These features are specified by the format de-scriptor %.2f. Once the program is executed, the text The sum is: 7.50 is displayed on the screen.

Program 5.1.7 #include <stdio.h> void main(void){ float x=3.5, y=4; printf("The sum is: %.2f.", x+y);

}

When using function printf(), it is possible to print more than one argu-ment, as in example 5.1.8. The text that is displayed after the execution of the program is The student is 177 cm and 80.7 kg. The value of the weight is truncated due to the setting from the format descriptor %.1f.

Program 5.1.8 #include <stdio.h> void main(void){ int h=177; float w=80.73; printf("The student is %d cm and %.1f kg.", h,w);

}

As previously mentioned, function printf() allows to specify the position of the next printing. Program 5.1.9 shows how a text can be written on a new line.

Program 5.1.9 #include <stdio.h>

Page 7: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

6

void main(void){ int a=7, p=3; printf("Ann has:\n\t%d apples\n\t%d pears", a, p); printf("\nThere are %d fruits.", a+p);

}

Characters “\n” were used to move the cursor down, on the next line; this is the place where the printing of the text continues. In order to shift the text to the right (tab), there were used the characters “\t”. When the program is run, on the screen will be printed: Ann has: 7 apples 3 pears There are 10 fruits.

5.1.4 int getchar(void);

The function reads a character from the keyboard and returns that character after it converts it to an unsigned integer. On error, the constant EOF is re-turned. The header file that contains this function is stdio.h.

In example 5.1.10 a character is read from the keyboard using this function. The character is saved in the variable c and then it is printed on the screen using function printf(). When the program is run, the text Enter a charac-ter is displayed on the screen and the execution of the program waits for the user to type a character. If, for instance, the user types the character a, then the program will continue printing the message The read character is: a.

Program 5.1.10 #include <stdio.h> void main(void){ int c; printf("Enter a character "); c=getchar(); printf("The read character is: %c.", c);

}

Page 8: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

7

Another function, int getch(void) from the header file conio.h, can be also used to read a character from the keyboard. It returns the read character. This function is often used to force the program to wait until a key is pressed (in fact, the execution of the program is interrupted; the break will be finished when the user presses a key). The read character is not used by the program, but this trick is very good when some information is displayed and must be seen before it is deleted or before the execution of the program is ended.

The program example 5.1.11 prints a simple text on the screen and then calls the function getch() in order to avoid the ending of the program’s execution immediately after the text is printed; so, the execution is ended only when the user specifies this by pressing a key. It can be observed that this program needs two header files: stdio.h for the function printf() and conio.h for the function getch().

Program 5.1.11 #include <stdio.h> #include <conio.h> void main(void){ printf("Press any key to continue."); getch();

}

5.1.5 char *gets(char *s);

The function reads a string from the keyboard and is part of the stdio.h header file. The reading includes the whitespace characters (spaces, tabs) and ends when a new line (ENTER) appears. On error, the function returns EOF.

Example 5.1.12 shows how this function can be used. At the beginning of the program, a string of 100 characters is defined. More information on strings is given in the chapter committed to them. The text Enter a string is dis-played and then the execution of the program is interrupted, waiting for the user to type a sequence of characters ended with the ENTER key. If, for instance, the introduced string is Once upon a time, then the program will display the text Your string is: Once upon a time.

Program 5.1.12 #include <stdio.h>

Page 9: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

8

void main(void){ char s[100]; printf("Enter a string "); gets(s); printf("Your string is: %s.", s);

}

5.1.6 int scanf(const char* format [, address, ...]);

This function is used to read several fields that are converted according to a specified format and then are saved at the memory addresses sent as argu-ments after the formatting string. For each read element there must be a conver-sion specifier and a storing address. The function is part of the stdio.h head-er file. If succeeds, it returns the number of the read, converted and stored fields. If there is nothing to be read or if an error occurs before the reading is done, then the function returns EOF.

The arguments of this function are, somehow, similar to those of the function printf(). Therefore:

the string format contains several conversion characters, each one preced-ed by the special character %; some of the most frequently used conversion characters are:

o c – character;

o s – string;

o d, i – signed decimal integer;

o u – unsigned decimal integer;

o f – floating point number (float, double).

the address of each read element is in fact the name of the variable that stores the read value, preceded by the addressing operator & (e.g.: &n); if the variable is a string, then the addressing operator is missing because the address of the first element of the string is given directly by the name of the string.

In program 5.1.13 a couple of information about a person is read – name (de-fined as string) and age. At the end, this information is displayed on the screen. Warning: the addressing operator should not be omitted if a variable is not a

Page 10: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

9

string; in the example one can observe that the variable age needs this operator when it is read and stored.

Program 5.1.13 #include <stdio.h> #include <conio.h> void main(void){ char name[100]; int age; printf("Enter the name "); scanf("%s", name); printf("Enter the age "); scanf("%d",&age); printf("%s is %d years old.", name,age); getch();

}

If, for instance, the information entered by the user when the program is run is Ann for the name and 7 for the age, then the message Ann is 7 years old will be displayed on the screen. Function getch(), at the end of the program, is used to determine the program to wait for the pressing of a key before it ends its execution.

5.2 Mathematical functions The programs that are written to solve certain problems often involve the use of some mathematical functions. The standard library of the C programming lan-guage contains implementations for the most frequently used mathematical functions, grouped in the math.h header file. Some of them are hereby pre-sented.

double exp(double x);

o the exponential function;

o it calculates the value ex, where e ≈ 2.71828; double log(double x);

o the natural logarithm of x;

o the argument must be a strictly positive value, otherwise a do-main error is generated;

Page 11: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

10

double log10(double x);

o the base 10 logarithm of x, with x strictly positive;

double pow(double x, double y);

o the power function, x to the y;

double pow10(int x);

o the power function, 10 to the x;

double sqrt(double x);

o square root of x;

o the function is defined for positive numbers; if x is negative, a domain error is generated;

double fabs(double x);

o calculates the absolute value of a floating point number x;

double sin(double x);

o computes the sine of the input value x, where x is expressed in radians;

double cos(double x);

o the cosine of x, with x specified in radians;

double tan(double x);

o the tangent of x, with x expressed in radians;

There are implementations with similar prototypes for functions arc sine (asin()), arc cosine (acos()), arc tangent (atan()), hyperbolic sine (sinh()), hyperbolic cosine (cosh()), hyperbolic tangent (tanh()). All these functions receive a double value as argument, representing the angle specified in radians and also return a double value.

Two other functions, floor() and ceil(), are also part of this library; they are used to find the largest integer that is smaller than or equal to the argument and the smallest integer that is larger than or equal to the argument, respective-ly. The prototypes of these two functions are hereby presented.

double floor(double x);

Page 12: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

11

double ceil(double x);

In other words, floor() makes a down rounding and ceil() makes an up rounding of the argument. Both functions return the found integer as a dou-ble. For example:

floor(6.3)=6 ceil(6.3)=7

floor(-1.73)=-2 ceil(-1.73)=-1

floor(0.5)=0 ceil(0.5)=1

floor(-0.5)=-1 ceil(-0.5)=0

floor(7)=7 ceil(7)=7

Example 5.2.1 shows how some of the mathematical functions presented in this paragraph can be used in a program. During the program, a couple of variables x and y receive different values and are used as arguments for several function calls; the values that are returned are printed immediately or are firstly stored in a variable f.

It can be observed the use of the constant M_PI for the trigonometric functions. This constant has the value3.1415 and is part of the math.h library.

Program 5.2.1 #include <stdio.h> #include <conio.h> #include <math.h> void main(void){ double x, y, f; x=3; f=exp(x); printf("\nexp(%.2f) = %.2f",x,f); x=2; y=3; printf("\n%.0f to the %.0f=%.0f",x,y,pow(x,y)); x=49; printf("\nsquare root of %.1f is %.2f",x,sqrt(x)); x=1.7; f=log(x); printf("\nln(%.2f) = %.3f",x,f); x=-7; printf("\n|%.2f| = %.2f",x,fabs(x)); f=sin(M_PI/6); printf("\nsine of 30 degrees is %.2f", f);

Page 13: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

12

getch(); }

Once the program is run, the following results will be printed on the screen: exp(3.00) = 20.09 2 to the 3 = 8 square root of 49.0 is 7.00 ln(1.70) = 0.531 |-7.00| = 7.00 sine of 30 degrees is 0.50

5.3 Conversion functions In some situations, for different reasons, a number is represented as a string. In order to use it in arithmetical, logical or relational operations, this number must be converted. The following two functions can be used to convert a string into an integer and into a real number, respectively. These are declared in the stdlib.h header file.

int atoi(const char *str);

o converts the string received as argument to an integer value;

o the name of the function stands for “ASCII to integer”;

o the function returns 0 if the argument contains non-numerical sequences and cannot be converted.

double atof(const char *str);

o converts the string str, received as argument, in a floating point number;

o the name of the function stands for “ASCII to float”;

o the function returns 0 if str is a string that doesn’t have a nu-merical meaning.

Program 5.3.1 illustrates how these two functions can be used. A string is read from the keyboard and then the integer and the real number represented by this string are printed.

Program 5.3.1 #include <stdio.h>

Page 14: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

13

#include <conio.h> #include <stdlib.h> void main(void){ char str[20]; printf("Enter the string: "); scanf("%s", str); printf("Converted to integer: %d", atoi(str)); printf("\nConverted to real: %f", atof(str)); getch();

}

When the program is run, the user is asked to enter a string. If, for instance, the string is 14.7, then the program will print: Converted to integer: 14 Converted to real: 14.700000

If the user enters a non-numerical value (for instance abc2,7), then the printed result will be: Converted to integer: 0 Converted to real: 0.000000

5.4 Other functions This paragraph presents several functions that are frequently used. They are part of different categories; for this reason, they were grouped under the name “oth-er functions”.

5.4.1 void clrscr(void);

The function clears the screen in text mode (its name stands for “clear screen”) and places the cursor in the upper left corner of the window. It doesn’t have arguments and doesn’t return anything. The header file that contains this func-tion is conio.h. Example 5.4.1 uses this function.

Program 5.4.1 #include <stdio.h> #include <conio.h> #include <stdlib.h> void main(void){

Adriana
Text Box
For Code Blocks use system("cls");
Page 15: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

14

clrscr(); printf("This is an example.\n"); printf("Press any key to clear the screen."); getch(); clrscr(); printf("The screen was cleaned."); getch();

}

At the beginning of the program, function clrscr() clears the screen; this way, the results displayed by previous running sessions of other programs or of the current program are not visible anymore. Then, on several lines, the sen-tences This is an example. and Press any key to clear the screen. are printed. After that follows another call of the function clrscr() and the screen is cleared again. Next, the message The screen was cleaned. is displayed and the program ends after a key is pressed.

5.4.2 int random(int num);

Using this function a random integer number between 0 and num-1 is generat-ed. For example, the call random(100) (program 5.4.2) will generate an integer between 0 and 99.

Program 5.4.2 #include <stdio.h> #include <conio.h> #include <stdlib.h> void main(void){ clrscr(); printf("%d",random(100)); getch();

}

If the program is repetitively run, it can be observed that the generated number is the same. If this case is not accepted in a program, then the function void randomize(void); must be called before; this will initialize the generator of random numbers making the connection to the system clock, which, obvious-ly, is modifying continuously. This way, function random() that is called

Adriana
Text Box
For Code Blocks use rand()%MAX_NUM; where MAX_NUM is the maximum number you expect
Page 16: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

15

will not start from the same number. Program 5.4.3 is a complete example of random number generator.

Program 5.4.3 #include <stdio.h> #include <conio.h> #include <stdlib.h> void main(void){ clrscr(); randomize(); printf("%d",random(100)); getch();

}

Both functions, random() and randomize(), are part of the stdlib.h header file.

5.4.3 void exit(int status);

The call of this function causes the ending of the program. If there are other instructions after exit(), these will not be executed. The function doesn’t return anything and receives as argument the exit status of the program, status that is sent to the calling process (usually the operating system). Typically, the value zero of the argument status indicates a normal exit and a non-zero value is connected to a certain error. In order to use this function, the stdlib.h header file must be included in the program.

Example 5.4.4 calls function exit() to quit the program after the first mes-sage (The program is ending here.) is displayed. The instruction that prints the second message (This message won’t be dis-played.) is not executed.

Program 5.4.4 #include <stdio.h> #include <conio.h> #include <stdlib.h> void main(void){ clrscr(); printf("The program is ending here.");

Adriana
Text Box
For Code Blocks use srand(time(0)); #include <stdio.h> #include <stdlib.h> #include <time.h> void main(void){ srand(time(0)); printf("%d",rand()%100); }
Page 17: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

16

getch(); exit(0); printf("This message won’t be displayed.");

}

5.5 Questions and exercises A. Find the error.

1. #include <stdio.h> #include <math.h> void main(void){ float a=49,x; x=sqrt(a); printf("The result is: ",x); }

2. void main(void){ int a; float b,x; a=7; b=3.54; x=a+b; printf("The result is: %5.2f",x); }

3. #include <stdio.h> #include <math.h> void main(void){ int a,x; scanf("%d",a); x=fabs(a); printf("The absolute value is: %d",x); }

4. #include <stdio.h> void main(void){ int a,b,x; scanf("%d",&a); scanf("%d",&b); x=a+b; printf("The result is: " %5d,x); }

Page 18: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

17

5. #include <stdio.h> void main(void){ int a; float b,x; a=7; b=3.54; x=a+b; printf("The result is: %5.2d",x); }

6. #include <stdio.h> void main(void){ int a,b,x; a=7; b=3; x=a+b; printf("The result is: x=%4.1f",x); }

7. #include <stdio.h> #include <math.h> void main(void){ float a=-49.7,x; x=sqrt(a); printf("The result is: %.2f",x); }

B. Considering the following programs, specify what will be printed on the screen after these programs are executed.

8. #include <stdio.h> void main(void){ float x=39; printf("%.1f",x/4); }

9. #include <stdio.h> #include <conio.h> void main(void){ int x=7; printf("Sunday \\%d PM\\\t\"Tosca\" – Giacomo PUCCINI",x); }

Page 19: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

18

10. #include <stdio.h> #include <conio.h> #include <stdlib.h> void main(void){ float x=20, y=5.5; exit(0); printf("%.1f/%.1f=%.3f",x,y,x/y); getch(); }

C. Choose the correct answer (one only).

11. Which of the following functions is an output one?

□ a) gets(); □ b) getch(); □ c) printf(); □ d) scanf(); □ e) getchar().

12. Which of the following functions is an input one?

□ a) getch(); □ b) printf(); □ c) clrscr(); □ d) #include; □ e) all answers are wrong.

13. Which letter can be used to specify the type of the displayed argument in printf() function?

□ a) d; □ b) c; □ c) f; □ d) s; □ e) all of them.

14. Which of the following functions is an output one?

□ a) printf(); □ b) puts(); □ c) putch(); □ d) putchar(); □ e) all of them.

15. What happens when function scanf("%f",x) is executed?

□ a) a float variable is read; □ b) a float variable is printed; □ c) an image is scanned; □ d) the program ends because an error occurs during the execution of the function; □ e) all answers are wrong.

16. The default alignment when function printf() is used to display something is:

□ a) to the left; □ b) centered; □ c) to the right; □ d) justified; □ e) all an-swers are wrong.

17. Which of the following format descriptors (used in the printf() function) are wrong?

Page 20: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

5 – Library Functions

19

□ a) %-7s; □ b) %7.3f; □ c) %d; □ d) %c; □ e) all answers are wrong.

18. What type of variables are read by the call of the function scanf("%d%c", &x,a);?

□ a) a real number and a char; □ b) an integer and a char; □ c) an inte-ger and a string; □ d) a real number and a string; □ e) the instruction contains an error.

D. Write programs to solve the following problems.

19. Calculate and display the sum of two real numbers whose values are read from the keyboard.

20. Transform the dimension of an angle from degrees into radians (180°=π radians). Suppose that the number entered by the user is valid.

21. Use the mathematical functions sqrt, log, exp, pow, fabs. Check what happens during the execution of the program if the arguments sent to these functions are wrong (for instance, square root of a negative number).

22. Find and display the last digit of an integer.

23. Print on the screen (using a single instruction) the following text lines: "C language" \ Dennis RITCHIE

#1972

5.6 Answers to questions and exercises

A. 1. The format descriptor %f from printf() function is missing; the cor-rect instruction is printf("The result is: %f",x);. 2. The header file for printf() function was omitted; the directive #include <stdio.h> must be placed at the beginning of the program. 3. The addressing operator & is missing in the function that reads the value of variable a; the correct instruction is scanf("%d",&a);. 4. The format descriptor %5d must be placed inside the string that is sent as argument to printf() function; the correct instruction is printf("The result is: %5d",x);. 5. x is a float variable, therefore the letter that must be used in the format descriptor of the printing function is f, not d; the correct instruction is printf("The result is: %5.2f",x);. 6. Variable x is an integer, therefore the format descriptor used for its printing is wrong; the correct form is printf("The

Page 21: COMPUTER PROGRAMMING THE C LANGUAGEadrianaa/teaching/ICP/08_Chapter 05.pdf · The C programming language is a very simple language. It only has few in-structions that can be used

Computer Programming – The C Language

20

result is: x=%d",x);. 7. Variable a has a negative value; this will interrupt the execution of the program when function sqrt() is called; in order to have a functional program, variable a must be non-negative.

B. 8. The format descriptor %.1f specifies that the number is displayed with one decimal, therefore the result is 9.8. 9. The displayed text is Sunday \7 PM\ "Tosca" - Giacomo PUCCINI, written on a single line, with a tab before the word “Tosca”. 10. The program doesn’t display anything be-cause exit(0) instruction ends it before the call of printf() function.

C. 11. c). 12. a). 13. e). 14. e). 15. d) – the value read for variable x cannot be stored in the memory because the addressing operator & is missing; therefore, an error will be generated when the function is executed; if the value returned by scanf()function is not verified, then the program will stop. 16. c). 17. e) – because all the enumerated format descriptors are correct. 18. e) – a char needs the addressing operator.