ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Similar documents
C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Unit 4. Input/Output Functions

printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n",stringptr); return 0;

Fundamentals of Programming

Fundamental of Programming (C)

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

UNIT-I Input/ Output functions and other library functions

Introduction to Computing Lecture 03: Basic input / output operations

Should you know scanf and printf?

Programming for Engineers Introduction to C

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Advanced C Programming Topics

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Fundamentals of Programming Session 4

Data Input and Output 187

THE FUNDAMENTAL DATA TYPES

LESSON 4. The DATA TYPE char

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Formatted Input/Output

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Work relative to other classes

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C

Formatted Output Pearson Education, Inc. All rights reserved.

Fundamentals of Programming. Lecture 11: C Characters and Strings

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

C - Basic Introduction

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Standard I/O in C and C++

AWK - PRETTY PRINTING

11 Console Input/Output

Chapter 2, Part I Introduction to C Programming

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Stream Model of I/O. Basic I/O in C

Input/Output Week 5:Lesson 16.1

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

The C++ Language. Arizona State University 1

Lecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

CSC 1107: Structured Programming

Fundamentals of Programming Session 8

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Basic Types and Formatted I/O

A Fast Review of C Essentials Part I

Number Systems, Scalar Types, and Input and Output

CC112 Structured Programming

CSC 1107: Structured Programming

Console Input and Output

UNIT 3 OPERATORS. [Marks- 12]

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

بسم اهلل الرمحن الرحيم

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Reserved Words and Identifiers

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Chapter 7. Basic Types

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

C: How to Program. Week /Mar/05

Input/Output: Advanced Concepts

Chapter 2 - Introduction to C Programming

These are reserved words of the C language. For example int, float, if, else, for, while etc.

ANSI C Programming Simple Programs

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

BSM540 Basics of C Language

Programming in C. Session 2. Seema Sirpal Delhi University Computer Centre

Programming and Data Structures

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

Introduction to Programming

Data Types and Variables in C language

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Course organization. Course introduction ( Week 1)

Input/output functions

Input/output functions

Full file at

Fundamental of Programming (C)

Computers Programming Course 5. Iulian Năstac

Basic Elements of C. Staff Incharge: S.Sasirekha

Have the same meaning as variables in algebra Single alphabetic character Each variable needs an identifier that distinguishes it from the others a =

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Chapter 2 THE STRUCTURE OF C LANGUAGE

C mini reference. 5 Binary numbers 12

Input / Output Functions

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

C Language, Token, Keywords, Constant, variable

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Full file at C How to Program, 6/e Multiple Choice Test Bank

CYSE 411/AIT681 Secure Software Engineering Topic #12. Secure Coding: Formatted Output

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

IT 374 C# and Applications/ IT695 C# Data Structures

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

Transcription:

ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Lecture 07: Data Input and Output Readings: Chapter 4

Input /Output Operations A program needs to read data in variable names: input operation Also data stored in variables need to be displayed: output operation C language does not define any keyword to perform these input/output operations C language provides functions to perform input/output operations getchar, putchar, scanf, printf, gets and puts All these functions are prototyped under stdio.h Bhaskar Shrestha 3

Reading a Single Character through getchar The getchar function reads the next character available from the standard input device (typically a keyboard) and returns the character read Returns EOF when it encounters end of file The character returned can be assigned to a variable for further use In general terms, a function reference would be written as variable_name = getchar(); where variable_name refers to some previously defined character variable char ch; ch = getchar(); Bhaskar Shrestha 4

Writing a Single Character through putchar The putchar function can be used to write a single character to a standard output device (typically a monitor) It takes the form as shown below: putchar(character_value) where character_value can be a character variable or an expression that evaluates to a character value that is going to be printed ch1 = getchar(); ch2 = ch1 - 'a' + 'A'; putchar(ch2); putchar(ch1 - 'a' + 'A'); putchar('\n'); Bhaskar Shrestha 5

Formatted Output Function: printf Can be used to output data of different types in different formats Can perform rounding, aligning columns, right/left justification, inserting literal characters, exponential format, hexadecimal format, and fixed width and precision The general from of an output function is: printf(format-string, arg1, arg2,..., argn) Here, format-string is a string and arg1, arg2,..., argn are any valid C expressions Bhaskar Shrestha 6

Formatted Output Function: printf format-string describes the output format format-string consists of two types of items ordinary characters, which are exactly printed as written conversion specifications that define the way the subsequent arguments are displayed Other-arguments (arg1, arg2,..., argn): correspond to each conversion specification in format-string Bhaskar Shrestha 7

Example There must be exactly the same of number of arguments (after the format string) as there are conversion specifications, and the conversion specifications and the arguments are matched in order from left to right The arguments can be any valid expression and they must match the data type as specified in the conversion specification printf("answer x = %d \n", x); printf("a = %d, b = %f \n", a, b); printf("square of %d is %d\n", a, a*a); Bhaskar Shrestha 8

Conversion Specifications Controls the type and format of the value to be printed Each conversion specification begins with a % and ends with a conversion character. Conversion character tells the data type of the corresponding argument Between the % and the conversion character there may be, in order: A minus sign, which specifies left adjustment of the converted argument A number that specifies the minimum field width A period, which separates the field width from the precision A number, the precision: exact meaning depends on type printed An h if the integer is to be printed as a short, or l if as a long Bhaskar Shrestha 9

Conversion Characters Conversion Character c d, i e E f g G o s u x X % Printed as single character signed decimal integers floating-point value in scientific notation (lowercase e) floating-point value in scientific notation (uppercase E) floating-point value without an exponent uses e or f, whichever is shorter uses E or f, whichever is shorter unsigned octal string of characters unsigned decimal integers unsigned hexadecimal (lowercase letters) unsigned hexadecimal (uppercase letters) prints a % sign Bhaskar Shrestha 10

Printing Integers Only negative integers are preceded by a sign To print short integers place h before the conversion character To print long integers place l before the conversion character listed below Conversion Character d, i o u x X Corresponding Argument Printed as signed decimal integers unsigned octal unsigned decimal integers unsigned hexadecimal (uses lowercase letters, a-f) unsigned hexadecimal (uses uppercase letters, A-F) Bhaskar Shrestha 11

Printing Floating-Point Numbers Use the f conversion character to print floating-point numbers There is at least one digit to left of decimal 6 digits are printed after decimal point Use either e or E character to print in exponential form Using g or G conversion character tells print to use either f or e whichever results in shorter output No trailing zeros (1.2300 becomes 1.23) Precede the conversion character with l to print a long double Bhaskar Shrestha 12

Printing Characters and Strings c: Prints a char argument Cannot be used to print the first character of a string s: prints a string, argument must be a pointer to char 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') Bhaskar Shrestha 13

Other conversion character 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 %% Bhaskar Shrestha 14

Specifying the Minimum Field Width An integer placed between the % sign and the conversion character acts as a minimum field width It specifies the minimum number of character position to be taken by the output data If width larger than data, output will be filled with leading spaces to reach the field width If output data is larger than width, it will be printed in full If you wish to fill with 0 s, place a 0 before the field width specifier printf(":%10d:",12); printf(":%010d:",12); : 12: :0000000012: Bhaskar Shrestha 15

The Precision Specifier It consists of a period followed by an integer Its exact meaning depends upon the type of data to which it is applied When applied to %f, %e, %g, it determines the number of decimal places displayed When applied to %s, it specifies the maximum field length When applied to integers, it determines the minimum number of digits that will appear for each number printf("%5.2f\n", 12345.267); printf("%3.8d\n", 1002); printf("%10.15s\n", "This is a sample text"); Bhaskar Shrestha 16

Justifying Output If the field width is larger than the data printed, the data will be placed on the right edge of the field You can force output to be left justified by placing a minus sign directly after the % For example, %-10.2f left justifies a floating-point number with two decimal places in a 10-character field printf("... \n"); printf("right-justified: %8d \n", 100); printf(" left-justified: %-8d \n", 100);... right-justified: 100 left-justified: 100 Bhaskar Shrestha 17

Flags in Conversion specification A flag is placed immediately after % specifier -, 0: discussed earlier +: A sign (either + or -) will precede each numerical data # (with o and x type conversion): Causes octal and hexadecimal values to be preceded by 0 and 0x respectively # (with f, e and g type conversion): Causes a decimal point to be present in all floating point numbers Prevents truncation of trailing zeros in g type conversion Space: Prints a space before a positive value not printed with + flag Bhaskar Shrestha 18

Formatted Input Function: scanf General-purpose console input routine Can read all the built-in data types and automatically convert numbers into the proper internal format The general form of scanf is scanf(format-string, arg1, arg2,..., argn) scanf reads characters from the standard input, interprets them according to the specification in format-string, and stores the results in the remaining arguments arg1, arg2,..., argn, each of which must be a pointer that indicate where the corresponding converted input should be stored Bhaskar Shrestha 19

Format-string The format string usually contains conversion specifications, which are used to control conversion of input. The format string may contain: Blanks or tabs, which are not ignored Ordinary characters (not %), which are expected to match the next nonwhite space character of the input stream Conversion specifications, consisting of the character % followed by a conversion character that determines the type of data to be read next A conversion specification directs the conversion of the next input field Any character that cannot be interpreted according to the conversion specification terminates the current input field, and is put back into the input buffer. This character is then the first one read for the next input item Bhaskar Shrestha 20

Conversion Character Conversion Character c d i u x o e, f, g s [...] p n % Meaning Reads a single character Reads a decimal integer Reads an integer. The integer may be in octal (with leading 0) or hexadecimal (leading 0x or 0X) Reads an unsigned decimal integer Reads a hexadecimal integer Reads a octal integer Reads a floating-point number (float) Reads a string Scans for a sets of characters Reads an address Does not read, stores no of characters read up to the point %n was encountered Reads a percent sign Bhaskar Shrestha 21

Reading Integers To read integers, use either the %d or %i For %i you can enter the number either in decimal, octal or hexadecimal form (0 must precede an octal integer and 0x or 0X must precede an octal form) Use %o to read an integer in octal form and %x or %X to read in hexadecimal form No need to precede with 0 or 0x To read unsigned integer, use %u scanf function stops reading a integer when the first nonnumeric character is encountered To read a long integer, put an l in front of any conversion character mentioned above To read a short integer, put an h in front of any conversion character Bhaskar Shrestha 22

Reading floating-point values To read a floating-point number, use %f, %e, or %g Inputted number can begin with optional sign, optional decimal point and optional exponent To read a double-precision number, put l before any of the above conversion character To read a long double, put L before any of the above conversion character As with integers, scanf stops reading when the first invalid character is encountered Bhaskar Shrestha 23

Reading single characters Use %c to read a single character Although spaces, tabs and newlines are used as field separates when reading other types of data; when reading a single character, white-space characters are read like any other character For example, with input x y, this code fragment scanf("%c%c%c", &a, &b, &c); stores x in a, a space in b and the character y in c Bhaskar Shrestha 24

Reading Strings Use %s to read a string Reads characters until it encounters a white-space character Characters read are put into the character array pointed to by the corresponding argument The result is null terminated Skips leading white-spaces For example char str[80]; scanf("%s", str); If input was This is a test, str only contains This Bhaskar Shrestha 25

Scanset Set of characters enclosed in square brackets [] Preceded by % sign Scans input stream, looking only for characters in scan set Whenever a match occurs, stores character in specified array Stops scanning once a character not in the scan set is found Inverted scan sets Use a caret ^: [^aeiou] Causes characters not in the scan set to be stored Bhaskar Shrestha 26

Skipping characters A white-space character in format-string causes scanf to skip one or more white-space characters A non-white-space character in format-string causes scanf to read and discard matching characters in the input Suppressing input An * placed before conversion character tells scanf to read a field but not assign to any variable In effect, that input field is skipped. Such a conversion specification corresponds to no variable argument Bhaskar Shrestha 27

Maximum Field Width Specifier An unsigned integer placed between % and conversion character acts as a maximum field width specifier It indicates the maximum number of characters to be read and converted The next input field begins with the first character not yet processed For example scanf("%3d%d", &a, &b); If the input was 12345, a contains 123 and b contains 45 Bhaskar Shrestha 28

Printing strings with puts The puts function writes its string argument to the screen followed by a newline puts recognizes the same backslash escape sequence as printf does, such as \t for tab A call to puts requires less overhead than the same call to printf because puts can only output a string of characters it cannot output numbers or do format conversions Example char str[] = "Hello World"; puts(str); puts("\twelcome!!"); Hello World Welcome Bhaskar Shrestha 29

Reading strings with gets The gets function reads characters from input and places them into the character array pointed by the given argument Characters are read until a newline or an EOF is received The new line character is not made part of the string; instead it is translated into a null character to terminate the string Unlike using %s in scanf, gets does terminate input on white-space character For example char str[80]; gets(str); If input was This is a test, str contains the entire string This is a test Bhaskar Shrestha 30