Presentation is loading. Please wait.

Presentation is loading. Please wait.

Input & Output Operations Week 6 SCP1103 Basic C Programming SEM1 2010/2011.

Similar presentations


Presentation on theme: "Input & Output Operations Week 6 SCP1103 Basic C Programming SEM1 2010/2011."— Presentation transcript:

1 Input & Output Operations Week 6 SCP1103 Basic C Programming SEM1 2010/2011

2 Formatted input / output In C, data must be input to and output from a program through a file

3 Formatted input / output Other then printf and scanf, C provides other function for input and output operation using library & Example: conio.h: clrscrgetchinport stdio.h: scanfgetcharfeof

4 6.1 Formatting Output

5 Formatting Output with printf –Precise output formatting Conversion specifications: flags, field widths, precisions, etc. –Can perform rounding, aligning columns, right/left justification, inserting literal characters, exponential format, hexadecimal format, fixed width and precision

6 Formatting Output with printf Format of printf statement printf( format-control-string, other- arguments ); Format control string: –describes output format –Ordinary characters - copy to output stream: –Example – printf(“this is an output\n”);

7 Formatting Output with printf Format of printf statement printf( format-control-string, other- arguments ); Other-arguments: –correspond to each conversion specification in format-control-string –Each specification begins with a percent sign ( % ), ends with conversion specifier

8 Formatting Output with printf Format of printf statement

9 Formatting Output with printf Format of printf statement –printf( format-control-string, other- arguments ); Other-arguments: –Conversion specifications: leading with character ‘%’ –Format: %-w.p[d,f,c,s,…] [-]: optional  left justification, if exists [w]: optional  minimal width (wider if necessary). [.]: optional  separates field w and p [p]: optional  maximum field width for a string  precision of floating number [d,f,c,s,…] : match to variable data type

10 Printing variable values To print an integer: int degreesF = 68; printf("The temperature is %d degrees.", degreesF); Specifier for “print an integer value” “Read value from this variable” > The temperature is 68 degrees. Output:

11 printf() Format specifiers: – %c for single characters – %d for integers – %f for float/double (fractions): 1234.56 – %g for float/double (scientific): 1.23456E+3 – %s for phrases or ‘ strings ’ (coming soon!)

12 Integer Conversion Specifier

13 Printing Character char a; printf("%c %d %x %0", a, a, a, a); A 65 41 101

14 Printing Integers Integer –Whole number (no decimal point): 25, 0, -9 –Positive, negative, or zero –Only minus sign prints by default

15 Example 1 455 -455 32000 2000000000 707 455 4294966841 1c7 1C7 Output:

16 Printing Floating-Point Numbers Floating Point Numbers –Have a decimal point ( 33.5 ) –Exponential notation (computer's version of scientific notation) 150.3 is 1.503 x 10² in scientific 150.3 is 1.503E+02 in exponential ( E stands for exponent) use e or E –f – print floating point with at least one digit to left of decimal –g (or G ) - prints in f or e with no trailing zeros ( 1.2300 becomes 1.23 )

17 Floating-point conversion specifiers

18 Example 1.234568e+006 -1.234568e+006 1.234568E+006 1234567.890000 1.23457e+006 1.23457E+006 Program Output

19 Printing Strings and Characters c –Prints char argument –Cannot be used to print the first character of a string s –Requires a pointer to char as an argument –Prints characters until NULL ( '\0' ) encountered –Cannot print a char argument Remember –Single quotes for character constants ( 'z' ) –Double quotes for strings "z" (which actually contains two characters, 'z' and '\0' )

20 Other Conversion Specifiers p –Displays pointer value (address) n –Stores number of characters already output by current printf statement –Takes a pointer to an integer as an argument –Nothing printed by a %n specification –Every printf call returns a value Number of characters output Negative number if error occurs % –Prints a percent sign –%

21 Printing with Field Widths and Precisions Field width –Size of field in which data is printed –If width larger than data, default right justified If field width too small, increases to fit data Minus sign uses one character position in field –Integer width inserted between % and conversion specifier –%4d – field width of 4

22 Printing with Field Widths and Precisions Precision –Meaning varies depending on data type –Integers (default 1 ) Minimum number of digits to print –If data too small, prefixed with zeros –Floating point Number of digits to appear after decimal ( e and f ) –For g – maximum number of significant digits –Strings Maximum number of characters to be written from string –Format Use a dot (. ) then precision number after % %.3f

23 Printing with Field Widths and Precisions Field width and precision –Can both be specified %width.precision %5.3f –Negative field width – left justified –Positive field width – right justified –Precision must be positive

24 Example printf("|%d|\n", 987); printf("|%2d|\n", 987); printf("|%8d|\n", 987); printf("|%-8d|\n", 987); printf("|%0.2f|\n", 9876.54); printf("|%4.2f|\n", 9876.54); printf("|%3.1f|\n", 9876.54); printf("|%10.3f|\n", 9876.54); printf("|%10.3e|\n", 9876.54); |987| |9876.54| |9876.5| | 9876.540| | 9.876e+03|

25 ▪ ▪ ▪ 1 ▪ ▪ 12 ▪ 123 1234 12345 ▪ ▪ -1 ▪ -12 -123 -1234 -12345 Example

26 Using precision for integers 0873 000000873 Using precision for floating-point numbers 123.945 1.239e+002

27 Printing Literals and Escape Sequences Printing Literals –Most characters can be printed –Certain "problem" characters, such as the quotation mark " –Must be represented by escape sequences Represented by a backslash \ followed by an escape charact er

28 Printing Escape Sequences

29 Exercise Week 6_1 Identify the output of the following statements: 1.printf(“Ant’s Length:%2.2f sm",2.445e-2); 2.printf("%c %d %u", 66, 0x50, 'C'); 3.printf("%-8d\n%6.3f %-6.3f", 4356, 1.52, 1.52);

30 6.2 Formatted Input

31 Formatting Input with scanf scanf –Input formatting (i.e. will scan formatted input from the keyboard – data entry purpose) –Capabilities Input all types of data Input specific characters Skip specific characters

32 Formatting Input with scanf Format –scanf(format-control-string, other-arguments); –Format-control-string Describes formats of inputs –Other-arguments Pointers to variables where input will be stored

33 Keyboard input: scanf() Example - to read an integer: int num_students; scanf(" %d", &num_students); Specifier for “read an integer value” VERY IMPORTANT special symbol (&) ‘address of’ operator “Place value into this variable”

34 Formatting Input with scanf

35

36

37

38 Example

39

40 Enter a string: Sunday The input was: the character "S" and the string "unday" Program Output Example

41 Exercise Week 6_2 Refer to Exercise 2 No. 1 in pg. 56. What will be displayed if the following characters are entered in Program 6.1 & 6.2. Explain the program output with the following input. AV TY

42 6.3 Simple Input Output

43 getchar() & putchar() Use library stdio.h getchar() - to read a single character from standard input - keyboard. –Pressing Enter causes the block of characters you typed to be made available to your program. putchar() - to write a single character to standard output – output monitor. Example: char huruf; huruf = getchar(); putchar (huruf); putchar (huruf+1); Output with input ‘E’: EF

44 getch() & putch() Use library conio.h getch() - to read a single character from standard input - keyboard. –The block of characters you typed available directly to your program. No need to press enter. –Does not echo the input. putch() - to write a single character to standard output - monitor. Example: char huruf; huruf = getch(); putch (huruf+1); Output with input ‘E’: F

45 getc() & putc() Use library conio.h getc() - to read a single character from standard input device – e.g. keyboard & file. –With stdin device type work similar with getchar(). putc() - to write a single character to standard output device – e.g. monitor & file. Example: char huruf; huruf = getc(stdin); putc (huruf, stdout);

46 gets() & puts() Use library stdio.h gets() - to read strings standard input device –Pressing Enter causes the strings you typed to be made available to your program. –The new line character will be stored as null (‘\0’) puts() - to write string to standard output device. –To change null (‘\0’) to new line. Example – input string “Dayang Norhayati” & store as: DayangNorhayati\0

47 gets() & puts() #include void main () { char nama[30]; printf("\nEnter Your Name please >>"); gets(nama); /*read string*/ printf("Good day "); puts(nama); /*print string*/ puts("It's your lucky day !!"); getch(); return 0; } Good day Dayang Norhayati It's your lucky day !!

48 Exercise Week 6_3 Write C program to solve the flow chart.

49 6.4 Hand Tracing a Program

50 Hand trace a program: act as if you are the computer, executing a program: –step through and ‘execute’ each statement, one-by-one –record the contents of variables after statement execution, using a hand trace chart (table) Useful to locate logic or mathematical errors

51 Hand Tracing a Program int main () { float num1, num2,num3, avg; printf("Enter the first number> "); scanf("%f", &num1); printf("Enter the second number> "); scanf("%f", &num2); printf("Enter the third number> "); scanf("%f", &num3); avg=(num1+num2+num3)/3; printf("The average is %f", avg); getch(); return 0; } num1num2num3avg ???? 1.1??? 2.2?? 1.12.23.3? 1.12.23.31.1 The average is 1.1

52 Exercise Week 6_4 Trace the following programs void main(){//Prog 6_42 int n, m, x, y; m=10; n=m*2/(m+2); m%=n+2; cout <<"n: "<<n; cout <<"\nm: "<<m; x=4; y=x*2+10%3-1*x; x*=(y/m); cout<<"\nx: "<< x; cout<<"\ny: "<<y; getch(); } void main(){ //Prog 6_41 int x, y, z; x =10; y = 17; z = x + y; y = y - x; printf ("x: %d y: %d z: %d”, x, y, z); x = y * z; z = x / 20; y = z % x; cout<<"\nx: "<<x<< " y: “ <<y<<" z: "<<z; getch(); }

53 6.5 Introduction to File Input and Output

54 Can use files instead of keyboard, monitor screen for program input, output Allows data to be retained between program runs We use a file for three purposes: –reading data from it –writing or printing data into it –reading and writing data from/into it These are called file modes

55 Introduction to File Input and Output A file that is used for reading is called an input file (or data file) A file that is used for writing is called an output file We cannot read data from an output file & we cannot write data into an input file

56 Files: What is Needed Steps: –Create the file –Open the file –Use the file (read from, write to, or both) –Close the file

57 Creating File To cerate internal name Creating an internal name means declaring a variable for the file - using pointer data type, FILE e.g. declaration of file variable

58 Opening Files Create a link between file name (outside the program) and file stream object (inside the program) Use the fopen member function: file_variable = fopen(“filename”, “file_mode”); Filename may include drive, path info. File mode tells the program how you intend to use the file –for reading or writing or both.

59 Opening Files – File Mode File modeMeaning rOpen file for reading => an input file If file exists, the file marker is positioned at beginning. & If file doesn’t exist errors returned. wOpen file for writing => an output file If file exists, it is emptied. & If file doesn’t, it is created. aOpen file for appending = > an output file If file exists, the file marker is positioned at end of file. & If file doesn’t exist, it is created. r+Open an existing file for both reading & writing w+Open a new file for both reading & writing a+Open an existing file for both reading & writing & append at the end of the file

60 Using Files Can use output file using fprintf : fprintf(file_variable,”format string”,value_list); Can use input file using fscanf : fscanf(file_variable,”format string”,address_list); fgetc & fputc : to read or print a character from file or to file. fgets & fputs : to read or print strings from file or to file.

61 Closing Files Use the close member function: fopen(file_variable); Don’t wait for operating system to close files at program end: –may be limit on number of open files –may be buffered output data waiting to send to file

62 Files - example #include #define PI 3.14159 int main(void) { double radius,area, circumference ; FILE *inp, *outp; inp = fopen("bulat.dat", "r"); outp = fopen("bulat.out", "w"); fscanf(inp,"%lf", &radius); area = PI*radius*radius; circumference = 2*PI*radius; fprintf(outp,"Radius of a circle is %0.2f\n", radius); fprintf(outp,"Area of the circle is %0.2f\n", area); fprintf(outp,"circumference of the circle is %0.2f", circumference); fclose(inp); fclose(outp); return 0; } Create 2 files Open file to read Open file to write Use file Close 2 files

63 Closing Files - example Created by programmer Created automatically by program

64 Exercise Week 6_5 Refer to Exercise 4 No. 1-4 in pg. 58. Solve the problem

65 Thank You Q & A


Download ppt "Input & Output Operations Week 6 SCP1103 Basic C Programming SEM1 2010/2011."

Similar presentations


Ads by Google