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

Slides:



Advertisements
Similar presentations
Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
Advertisements

CS1061 C Programming Lecture 16: Formatted I/0 A. O’Riordan, 2004.
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
1 IPC144 Session 11 The C Programming Language. 2 Objectives To format a #define statement correctly To use a #define statement in a C program To construct.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 Pearson Education, Inc. All rights reserved Formatted Output.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Chapter 18 I/O in C.
1 Pertemuan 4 Fungsi-Fungsi Bahasa C Matakuliah: T0016/Algoritma dan Pemrograman Tahun: 2005 Versi: versi 2.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Dale Roberts Basic I/O (Chap. 9) CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
3. FORMATTED INPUT/OUTPUT. The printf Function The first argument in a call of printf is a string, which may contain both ordinary characters and conversion.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Files A collection of related data treated as a unit. Two types Text
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
28 Formatted Output.
Chapter 9 - Formatted Input/Output
C Formatted Input/Output
Chapter 9 C Formatted Input/Output
Jonathan C.L. Liu, Ph.D. CISE Department University of Florida, USA
Input/output.
TMF1414 Introduction to Programming
Input & Output Operations
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
Programming in C Input / Output.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Formatted Input/Output
توابع ورودي-خروجي.
Lecture 13 Input/Output Files.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Formatted Input/Output
Chapter 9 - Formatted Input/Output
File Input and Output.
Department of Computer and Information Science
Formatted Input, Output & File Input, Output
Programming in C Input / Output.
Formatted Input/Output
Conversion Check your class notes and given examples at class.
Introduction to Java Applications
Formatted Input/Output
Module 12 Input and Output
Introduction to C EECS May 2019.
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

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

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

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

6.1 Formatting Output

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

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”);

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

Formatting Output with printf Format of printf statement

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

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:

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

Integer Conversion Specifier

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

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

Example c7 1C7 Output:

Printing Floating-Point Numbers Floating Point Numbers –Have a decimal point ( 33.5 ) –Exponential notation (computer's version of scientific notation) is x 10² in scientific 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 ( becomes 1.23 )

Floating-point conversion specifiers

Example e e E e E+006 Program Output

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' )

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 –%

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

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

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

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

▪ ▪ ▪ 1 ▪ ▪ 12 ▪ ▪ ▪ -1 ▪ Example

Using precision for integers Using precision for floating-point numbers e+002

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

Printing Escape Sequences

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);

6.2 Formatted Input

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

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

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”

Formatting Input with scanf

Example

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

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

6.3 Simple Input Output

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

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

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);

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

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 !!

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

6.4 Hand Tracing a Program

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

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?? ? The average is 1.1

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(); }

6.5 Introduction to File Input and Output

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

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

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

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

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.

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

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.

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

Files - example #include #define PI 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

Closing Files - example Created by programmer Created automatically by program

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

Thank You Q & A