slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 3 (continued) PowerPoint Presentation
Download Presentation
Chapter 3 (continued)

Chapter 3 (continued)

123 Views Download Presentation
Download Presentation

Chapter 3 (continued)

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Chapter 3 (continued) The C Programming Language(continued)

  2. Standard Input and Output

  3. Formatted Input and Output Considered our ‘standard input file’ Monitor is considered our ‘standard output file’ User provides input from a keyboard; read into memory via the scanf function. Output displayed on the monitor via the printf function. Formatted because the function converts internal forms to readable forms for user – and vice versa. Remember, people deal almost exclusively with text. Computer deals with our text in entirely different formats. Thus, all input and output must be converted.

  4. User enters data in text and the program converts input into internal forms and stores input according to descriptions. Input is ‘buffered’ until Enter key Formatted output converts internal forms into text for display. printf needs instructions on how to format and what to format. The printf statement requires a format (control) string (enclosed in quotes) as its first parameter. Contains constant data and optionally field specifications for data; this is followed by the list of data items. Field specifications begin with % and match with the variables in the data list.

  5. In the “HelloWorld” program, the statement: printf(“Hello World!\n”); displays the message between the double quotation marks on the screen. This statement is an example of a function call. The function being called is the printf() function. Note that the code for printf() is not in the “HelloWorld” program. When a function is used in a program that is not defined in the program, the compiler makes a note during compilation and leaves a message for the linker. When the linker later links the program it searches for the function’s code in the standard library <stdio.h> and links the code with the program. Standard Output

  6. The general form of the printf function is: printf(“control string”, argument list); requires one or two arguments control string - which is enclosed in double quotation marks and consists of two type of items: the characters that will be displayed on the screen and format specifiers or place holders. format specifier/place holder - defines the way in which the items in the argument list are to actually be displayed. The argument list consists of the list of items whose values are to be displayed. May be omitted! Example double angle = 45.5; printf(“Angle = %.2f degrees \n”, angle); Output: Angle = 45.50 degrees Standard Output Format specifier - 2 digits to right of decimal point, field width not specified Control string

  7. A format specifier begins with a (%) and is followed by a type conversion character, which is a one character code indicating the type of data to be printed. printf(“\n Volume of cylinder is: %10.4f”, volume); Format Specifiers control string argument list newline escape sequence format specifier - field width of 10 places, 4 fractional digits Examples: printf(“An integer number %d”, 100); printf(“A floating point number %f”, 100.232); printf(“A character %c”, ‘x’); printf(“Hello World!\n”);

  8. Conversion Specifiers for Output Statements • Note: %g (or %G) - a general format. Prints the value using a %f or %e specifier, depending on the size of he value. • Note: variables of type: short, int, or long can be printed with the %i or %d format. Similarly, float and double can be printed on %e or %f.

  9. Conversion Specifiers for Output Statements • After selecting the correct specifier, additional information can be added. • A minimum field width can be specified, along with an optional precision that controls the number of characters printed. • The field width and the precision can be used together or separately. • If the precision is omitted, a default of 6 is used for the %f specifier. • The decimal portion of a value is rounded to the specified precision; thus, the value 14.51678 will be printed as 14.52 if a %.2f is used. • The specification %5i indicates that a short or an int is to be printed with a minimum field width of 5. The field width will be increased, if necessary, to accommodate the value being printed. • If the field width is too long, the value is right justified. Justify left by inserting a minus sign before the field width (as in %-8i). • If a plus sign is inserted before the field width (as in %+6f), a sign will always be printed with the value.

  10. Conversion Specifiers for Output Statements

  11. Conversion Specifiers (continued) • If a control argument contains three conversion specifiers, then three corresponding identifiers or expressions would need to follow the control string. • printf(“Results: x =%5.2f, y = %5.2f, z = %5.2f \n”, x, y, z+3); • An example of output from this statement might be: • Results: x = 4.52, y = 0.15, z = -1.34 • If a prinf statement is long, you should split in into two lines. In general, to split text that is contained in quotation marks, you should split into two separate pieces, each in its own set of quotation marks. • printf(“The distance between the points is %5.2f \n”, dist); • printf(“The distance between the points is” “ %5.2f \n”, dist); • printf(“The distance between the “ “points is %5.2f \n”, dist);

  12. The format string can contain up to four modifiers used to specify formatting instructions, etc. Only the field specification token (%) and the conversion code (ahead) are required for any items in a data list. Format: %<flag><min width><precision><size>conversion-code We will only concern ourselves with integers floats, and character for now. Size parameter is used for short, long and long double. Width specifies the minimum number of output positions. In printing out columns without the width modifier, outputs take only what they need and output will appear crowded and unorganized. Important: Default is left justified.

  13. More Formatted Output For floats: precision modifier is very important as without it, a float results in six digits to the right of the decimal (default). You may want two digits to the right. So rather than printing 6.000000 you might wish 6.00. Normally, in printing floats (and doubles) you will likely want the precision modifier. For widthspecification, this represents the maximum number of print positions. For use of width and precision, you need to ensure that the field specification is large enough. e.g. %7.2f represents a field length of seven positions with two decimal positions. This includes the decimal point. Flag: with a minus and a width specification, data is left justified in the output field. With a zero and a width specification, output is zero-filled on the left and spaces inserted to the right. Only worry about integers, floats (double) and char for now – as stated. Also look at \t \n

  14. Practice! Assume that the integer variable sum contains the value 65, the double variable average contains the value 12.368 and that the char variable ch contains the value 'b'. Show the output line (or lines) generated by the following statements. • printf("Sum = %5i; Average = %7.1f \n", sum, average); • printf("Sum = %4i \n Average = %8.4f \n", sum, average); • printf("Sum and Average \n\n %d %.1f \n", sum, average); • printf("Character is %c; Sum is %c \n", ch, sum); • printf("Character is %i; Sum is %i \n", ch, sum);

  15. Practice! Note: The conversion code for a string is “s”. Examples: •printf(”%s%s\n”, “Hi, how “, “are you?”); • printf(“\t|%8s|%6d”, “ “, 1234); Note: \t == tab to character position 5 Result:^^^^|^^^^^^^^|^^1234 printf(“%d%%\n”, 10); /* prints “10%” */ • Say m = 1.0, c = 0.0, and y = 15.0; what is produced? printf("\n\nSlope of line = %8s%8.3f", " ",m); printf("\nIntercept of line = %4s%8.3f", " ", c); printf("\nY coordinate of point = %8.3f", y); Causes % to be displayed

  16. The scanf function allows the user to enter values from the keyboard while the program is executing. required arguments control string - that specifies the types of the variables whose values are to be entered from the keyboard. The remaining arguments in the scanf function are memory locations that correspond to the specifiers in the control string. These memory locations must be indicated with the address operator & (a unary operator that determines the memory address of the identifier with which it is associated). The & operator when applied to a variable evaluates to the memory address of the variable. Example: scanf(“%i”, &age); Standard Input

  17. scanf( ) • The reverse of printf( ) is the console input routine scanf( ). • A white space is a space, tab, or a newline character. • A white-space in the control string causes scanf( ) to skip over one or more white-space characters in the input stream. If there are any. • A non-white-space causes scanf to read and discard a matching character. For example, “%d,%d” causes scanf( ) to read an integer, then read and discard a comma, and finally read another integer. If the specified character is not found, scanf( ) terminates. • All variables used to receive values through scanf( ) must be passed by their addresses. “call by reference” • Input data items must be separated by white-space or a character matching that in the control string.: Example try to use “scanf(“%d%d”, &number1, &number2)” to read “10 20” then “10,20”

  18. Remember - White space in the control string causes scanf() to skip over one or more white space characters in the input. Examples: 1) scanf(“%d %d %c”, &num1, &num2, &ch); input is: “10 20 x” num1 = 10, num2 = 20, ch = “x” 2) scanf(“%d%d%c”, &num1, &num2, &ch); input is: “10 20 x” num1 = 10, num2 = 20, ch = 3) scanf(“%d%d %c”, &num1, &num2, &ch); input is: “10 20 x” num1 = 10, num2 = 20, ch = “x” 4) scanf(“%d,%d,%c”, &num1, &num2, &ch); input is: “10,20,x” num1 = 10, num2 = 20, ch = “x” (must match the commas) 5) scanf(“%d, %d, %c”, &num1, &num2, &ch); input is: “10,20,x” num1 = 10, num2 = 20, ch = “x” (blanks not needed) 6) scanf(“%d %d %c”, &num1, &num2, &ch); input is: “10 20 x” num1 = 10, num2 = 20, ch = “x” (multiple blanks in input not needed) Standard Input (continued)

  19. The precedence level of the address operator is the same as the other unary operators. (That is, if there are several unary operators in the same statement, they are evaluated right to left). Note: a common error is to omit the & (address operator) More than one value may be read using the same scanf statement. Input values must be separated by at least one delimiter (except characters), they can, however, be on the same line or on different lines. Example: double d; char u; scanf("%1f %c", &d, &u); However, it is very important to use a specifier that is appropriate for the data type of the variable Standard Input (continued) input: “10.5x” - output: “d = 10.500000, u = x” input: “10.5 x” - output: “d = 10.500000, u = x” input: “10.5 x” - output: “d = 10.500000, u = x”

  20. Have format string as usual. scanf stands for scan formatted. Requires a format string and an address list that identifies where data are to be placed in memory. Very tricky statement. ALL characters in format string are significant and represent delimiters. We will discuss… With the exception of %c, the scanf function skips leading white space. This means that the scanf function will skip leading spaces in the input stream. BUT, if the format string is character, then scanf will read exactly one character which can be almost anything. If you want to skip leading white space before a character, place a space before the field specification. Formatted Input

  21. scanf() Format Specifier • • The format specifier in the scanf() function has the following form: • %[*][width][size] type • The specifier consists of characters in the following order - • % - required in every format specifier • [*] - an optional assignment suppression operator. Following immediately behind the % sign suppresses assignment of the next input field; thus, allowing one or more input fields to be skipped. • optional field [width] - a positive number specifying the maximum number of characters to read. The actual number of characters read may be less than the field width if a whitespace or a nonmatching or incovertible character is encountered. Note: scanf() will not read more than the specified number of characters. • optional [size] modifier - one of the characters: h, l, or L indicating how the input data should be converted. This is important since the program has no before hand way of knowing what kind of data will be inputted to the program. Note: h, when used with the type d or i indicates that the input data should be converted to shortint. When used with the u type, it indicates a conversion to short unsigned. l, when used with the type d, i, or u indicates a conversion to long int (or long unsigned int in the case of u) l, can also be used with the floating point types: e, E, f, g, and G to indicate conversion to double. L, can be used with e, E, f, g, and G to indicate conversion to long double. • type - tells scanf() how the input is to be converted and stored.

  22. When input data are needed in an interactive program, you should include printf statements to display a prompt message that tells the user what data is to be entered and when. Your program should include statements similar to: printf(“Enter the distance in miles> “); scanf(“%lf”, &miles); The printf statement displays the format string and advances the cursor to the screen position following the string. The user can then enter the requested data which is processed by the scanf function. The cursor is advanced to the next line when the user presses the <enter> key. I/O (continued)

  23. Program has the following statements: int x,y,z; scanf(“%d%d%d”,&x,&y,&z); /*x=10,y=20,z=30*/ General rule of thumb is that the program will not advance beyond this statement until the variable list is satisfied. The same results are obtained for each of the following input: I/O (continued)

  24. The following code shows how to prompt the user for input, and how to use printf to display a computed answer. #include <stdio.h> int main(void) { int x, y; float avg; printf("Enter two integral values: "); scanf("%d %d",&x,&y); avg = (x + y) / 2; printf("The average of %d and %d is: %f",x,y,avg); return 0; } I/O Example Results as displayed by CodeWarrior

  25. Another C Program #include <stdio.h> /* Calculate quotient & remainder of two numbers */ int main (void) { /* Local Definitions */ int intNum1; int intNum2; int intCalc; /* Statements */ printf("Enter two integral numbers: "); scanf ("%d %d", &intNum1, &intNum2); intCalc = intNum1 / intNum2; printf("%d / %d is %d", intNum1, intNum2, intCalc); intCalc = intNum1 % intNum2; printf(" with a remainder of: %d\n", intCalc); return 0; } /* main */ /* Results: Enter two integral numbers: 13 2 13 / 2 is 6 with a remainder of: 1 */ Starts printing where the last printf left off.

  26. C allows a program to explicitly name a file from which the program will take input and a file to which the program will send output. Specific files to use must first be declared with a file pointer variable in which to store the address where the program can find the necessary information to permit access to the file. Example: FILE *inp, /* pointer to input file */ *outp; /* pointer to output file */ Declares that file pointer variables, inp and outp, will hold the address information allowing access to the program’s I/O files. Note: these are declarations; thus, must precede any executable statements (i.e., should be up front in the program) I/O Files

  27. The O/S must prepare a file for input or output before permitting the program to access them. This is done by making calls to the fopen() function. Example: inp = fopen(“pathToInputFile”, “r”); outp = fopen(“pathToOutputFile”,“w”); Declares that file pointer variables, inp and outp, will hold the address information allowing access to the program’s I/O files. Note: for this class, files are best located within the project folder that houses the associated C program that will use them. I/O Files (continued) read (input) write (output)

  28. Example: inp = fopen(“Lab1Data.txt”, “r”); outp = fopen(“Lab1Answers.txt”,“w”); printf and scanf statements are used to process data to/from standard input and output. fprintf and fscanf statements are used to redirect I/O to external files. Example: inp = fopen(“Lab1Data.txt”, “r”); outp = fopen(“Lab1Answers.txt”,“w”); . . . fscanf(inp, “%lf”, &miles); fprintf(outp, “The distance in miles is %.2f.\n”, miles); I/O Files (continued)

  29. The three most common modes of file use are: “r” - opens the file for reading, beginning at the start of the file “w” - opens the file for writing “a” - opens the file for appending (i.e., adding to the end of the file) Important: opening an existing file for writing results in the erasure of the current contents of the file. One of the most common ways to delete a file accidentally is to open it for writing when you really intended to open it either for reading or appending. If a nonexistent file is opened for writing, then a new file with that name will be created. fopen() returns a NULL pointer if it is unable to open the indicated file. We’ll see later how to make use of this information. Thus, before making use of the file pointer returned by fopen() it is best to check whether the attempt to open the file was successful (we’ll see how to do this later). I/O Files (continued)

  30. Clearly, The only formatting difference between printf and fprintf and scanf and fscanf, is that the first parameter of each must now specify a file name. The remainder of a call to fscanf or fprintf is identical to a call to scanf or printf. Note: when a program has no further use for its input and output files, it should close the files in order to avoid corruption to them. Example: fclose(inp) fclose(outp); Note: for this type of input file, any text editor (NotePad) or word processor may be used to create them. I/O Files (continued)

  31. The following code shows how to accept input from a file (user prompts are no longer necessary -- but will not do any harm if left in the program), and how to use fprintf to output the computed answers to a file. #include <stdio.h> int main(void) { int x, y; float avg; FILE *fin, *fout; fin = fopen("infile.dat","r"); fout = fopen("outfile.dat","w"); /* printf("Enter two integral values: "); statement is not needed*/ fscanf(fin,"%d %d",&x,&y); avg = (x + y) / 2; fprintf(fout,"The average of %d and %d is: %f",x,y,avg); fclose(fin); fclose(fout); return 0; } I/O using Files