Intro to C - Kirkwood Community College ·  · 2013-10-09The following code fragment outputs...

38
Intro to C Part 2: C Library functions & more I/O

Transcript of Intro to C - Kirkwood Community College ·  · 2013-10-09The following code fragment outputs...

Intro to C

Part 2: C Library functions & more I/O

2

Function Concept in Math

f ( x ) = 5 x - 3

When x = 1, f ( x ) = 2 is the returned value.

When x = 4, f ( x ) = 17 is the returned value.

Returned value is determined by the function definition and by the values of any parameters.

Name of function

Parameter of function

Function definition

3

Functions● C programs made up of functions; a program

must have a function called main● Program execution begins with the first

instruction in main● Any other functions are subprograms and must

be called

Functions

● A C function is a set of statements that perform a task– Encoded algorithm

– Function name is shorthand for the set of instructions it represents

– If a function returns a value, a call to the function is an expression that represents the return value

– We can pass data to the function in the form of arguments that match the function's parameter specification

5

Function Calls● One function calls another by using the name of the

called function together with a set of parentheses containing an argument list

● A function call temporarily transfers control from the calling function to the called function

● When the function’s code has finished executing, control is transferred back to the calling block

Function calls

● A function call in C has the following syntax:

functionName(arg1, arg 2, … argN)

– Where:● functionName is a valid C identifier representing the

name of a function either defined locally or included from a library

● The argument list is a set of 0 or more expressions (separated by commas) that match the function's parameter(s)

Value-returning vs. Non-value-returning

● All “procedures” in C are called functions, whether or not they return values

● A function that does NOT return a value will have the return type void:– Literally means nothing

– A call to such a function must be written as a standalone instruction; since the call doesn't represent a value, it isn't an expression

● A value-returning function has a C data type (such as int or double) as its return type

Functions from the C math library

● The math library contains a set of functions that (duh!) operate on numbers

● To use math library functions, use the preprocessor directive: #include <math.h>

● The program on the next slide illustrates use of some of the math functions

● The functions are:– double pow(double, double)

– double sqrt(double)

Example: find hypotenuse

#include <stdio.h>#include <math.h>

int main (){ double sideA, sideB, hypotenuse; printf("Enter length of side A: "); scanf("%lf", &sideA); printf("Enter length of side B: "); scanf("%lf", &sideB); hypotenuse = pow(sideA, 2) + pow(sideB, 2); /* sum of squares of both sides */ hypotenuse = sqrt(hypotenuse); /* takes the square root */ printf("A triangle with sides %lf and %lf has the hypotenuse %lf\n", sideA, sideB, hypotenuse); return 0;}

10

Other useful library functions

● The <math.h> library contains many useful functions for performing various types of calculations; they include:• log(x): returns the natural log (base e) of x, where x

and the result are both of type double• log10(x): returns the log base 10 of x, where x and

the result are both of type double• sin(x), cos(x), tan(x) calculate the sine, cosine, and

tangent of x, respectively, where x is an angle in radians, expressed as a double value

• exp(x) returns ex

11

Write C Expressions for● The square root of b2 - 4ac

● The square root of the average of myAge and yourAge

● The sum of the natural log of xy and the tangent of a 63 degree angle

12

Random numbers and ranges of values

● In the C standard library (stdlib.h), there is a function called rand() that produces pseudorandom integers in the range of 0 .. INT_MAX (the largest integer defined for your platform)

● For most applications, a random number in a narrower range is more useful; for example, a number between 1 and 50 might be used in a guessing game, or a number between 2 and 12 might be used to simulate a roll of dice

● Modulus can be used to narrow the range - see next slide

13

Random numbers and ranges of values

● The following code fragment outputs random numbers in the specified ranges:

int randNum;randNum = rand() % 10;printf( “A random number between 0 and 9: %d\n”, randNum );randNum = rand() % 50 + 1;printf( “A random number between 1 and 50: %d\n”, randNum );randNum = rand() % 11 + 2;printf( “A random number between 2 and 12: %d\n”, randNum );randNum = rand() % 21 - 10;printf( “A random number between -10 and +10: %d\n”, randNum );

14

Some notes on random numbers

● In order to use the rand() function, you need to place the following preprocessor directive at the top of your file:#include <stdlib.h>

● If you write a program containing the code presented on the previous slide, you will notice an odd phenomenon; the first time you run the program, the numbers generated by rand() will appear to be random, that is, unpredictable.

● But the next time you run the program, and all subsequent times, you will get the same set of “random” numbers

● To prevent this from happening, follow the directions on the next slide

15

Making random numbers random

● Along with <iostream.h> and <stdlib.h>, add the following preprocessor directive:#include <time.h>

● Place the following line of code near the beginning of main(), before any calls to the rand() function:srand(time(NULL));

● The line above should only appear once in your program, but you can call rand() as often as you need to

16

Program example

#include <stdio.h> // for printf()#include <stdlib.h> // for rand(), srand(), system()#include <time.h> // for time()

int main(){

int randNum; // random number for outputsrand(time(NULL)); // seeds rand() functionprintf( “A random number: %d\n”, rand() );randNum = rand() % 10; // stores # 0 .. 9 in randNum

printf( “Another one: %d\n”, randNum);randNum = (rand() % 20 + 1) * 2;

// even # 2 .. 40 printf( “One more: %d\n”, randNum);

system(“PAUSE”);return 0;

}

17

Strings and the string library

● Although C has no built-in data type for string data, there are many library functions that support the notion of a collection of characters as a single item

● One example is the printf function:

printf(“My name is %s\n”, “Cate”);● Several other examples are found in the C

string library (string.h)

18

Strings as char arrays

● An array is a collection of variables, all of the same type, stored in contiguous memory locations under a common name

● We'll look at arrays in general much later, but to understand strings, we have to look at them as C does: as arrays of type char

19

Strings as char arrays

● For example, suppose I wanted to store my name in a variable; the example below shows how:

char name[20] = “Cate Sheller”;● The data will be stored in memory like this:

20

Strings as char arrays

● Each character can be accessed via its index (0-11)

● Even the blank space ('') gets its own index● Very important: for a char array to be

considered a string, it must end with the null character ('\0')

21

Using a different string in a variable

● Suppose I changed my name● I would like to just assign this new (better!)

value to the name variable:

name = “Cate the Great”;● Unfortunately, this won't work:

22

Function strcpy to the rescue

● Revised code:char name[20] = "Cate Sheller";

printf("%s\n", &name);

/*name = "Cate the Great";*/

strcpy(name, "Cate the Great");

printf("%s\n", &name);

● Caution: the length of the string must not exceed the available space (in this example, 20 characters) – would cause a runtime error

23

More string functions

● strcat: concatenates (makes into one) two strings; example:strcpy(name, "Cate the Great");

printf("%s\n", &name);

printf("%s\n", strcat(name, " III"));

● strchr: checks for presence of a character in a string (returns its index if found)

● strcmp: compares two strings and returns an int indicating if the first is less, greater than, or equal to the the second

24

String input functions

● The scanf function can be used to read a string consisting of a single word (no spaces)printf("Enter your name: ");

scanf("%s", name); <<<<<< Note: no & !

printf("Your name is: %s\n", name);

● Sample runs:

25

String input functions

● Another stdio function, fgets, can read a string with multiple words (separated by spaces)printf("Enter your name: ");

fgets(name, 20, stdin);

printf("Your name is: %s\n", name);

● Note: if you're going to read input with fgets, make sure it is not preceded by calls to scanf

26

Speaking of I/O ...

● Recap of where we've been so far:– printf: function that writes out data to the screen

– Arguments:● Formatting string: set of characters enclosed in double

quotes; may contain formatting specifiers● If the formatting string contains formatting specifiers,

additional arguments in the form of expressions that match the specified data types are required

27

Recap of printf, continued

● Format specifiers we'll use most often (others exist, we just probably won't use them)

%d (for int expressions)

%c (for single char expressions)

%s (for strings)

%lf (for double expressions)

● The same format specifiers are used with scanf, which we'll review next

28

What we know about scanf()

● Reads input from the keyboard● Two arguments

– Format specifier

– Address of a variable (use & notation, unless reading a string)

● Always precede an input statement with a prompt!

29

And now some stuff you maybe didn't know

● Function printf is a variation of a more general function called fprintf

● Syntax for fprintf is the same, except there is an additional argument before the formatting string: the data destination, represented by an entity called a file pointer (or FILE*)

● You could use fprintf instead of printf if you specified the FILE* called stdout, as below:

fprintf(stdout, “%s\n”, “Bet you didn't know that”);

30

The input side of things

● In a similar way, scanf is a variant of fscanf● The FILE* associated with scanf is stdin (the

standard input stream, or keyboard), so you could use fscanf instead of scanf if you started with stdin as the first argument:

fscanf(stdin, “%d”, &x); /* would read int value into x */

fscanf(stdin, “%s”, word); /* would read a string into word */

31

Why they call it printf

● The name printf (or fprintf, for that matter) has the f on the end because it stands for “formatted”

● Using numbers embedded within format specifiers, we can control:– The orientation (right or left justified) of output

– The amount of space (field width) that should be allowed for output

– The number of decimal places displayed in a floating-point number

Formatting Output

● We call the space occupied by an output value the field. The number of characters allocated to a field is the field width. The diagram shows output right-justified in a field width of 6 (spaces are represented by dashes)

Control Strings

● Integers%<field width>d

● Example:printf(“The result is:%5d\n”, 100);

Output:

The result is: 100● In the example above, the number is printed right-

justified in a field of 5 spaces

Control strings

● Real Numbers (doubles)%<field width>.<decimal places>lf

● Example:printf(“You owe: $%7.2lf\n”, 3.15679e2);

Output:You owe: $ 315.68

● In the example, the specified field width was one space wider than required to print the number with 2 decimal places

● If you specify a field width that is too narrow for the output, the field width value is simply ignored

Control strings

● Strings%s

● Example:printf("%10s%10s%10s\n", "Yours", "Mine", "Ours");

● Output: Yours Mine Ours

Right and Left Justification in printf

● The codedouble value = 12.123;printf("Start%8.2fEnd\n", value);printf("Start%-8.2fEnd\n", value);

will output the followingStart 12.12EndStart12.12 End

● The format string "Start%8.2fEnd\n" produces output that is right justified with three blank spaces before the 12.12

● The format string "Start%-8.2fEnd\n" produces output that is left justified with three blank spaces after the 12.12

Write a printf statements that produces the output below given the following:

double v = 42.70145;

/* output */

The value is: $42.70

Suppose you want to print the value of π, as follows:

● With 2 digits after the decimal point● Left-justified● In a field of 8 characters

const double PI = 3.14159;

/* With what should you replace the blank space below? */

printf(“%____f”, PI);