Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Chapter 3: Number Systems, Scalar Types, and Input.

Slides:



Advertisements
Similar presentations
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
Advertisements

1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Data types and variables
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
Chapter 2 Data Types, Declarations, and Displays
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
Introduction to programming Language C, Data Types, Variables, Constants. Basics of C –Every program consists of one or more functions and must have main.
First Program in C With Output. C Language Keywords.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects Seventh.
 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.
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.
 2005 Pearson Education, Inc. All rights reserved Formatted Output.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
Lecture #5 Introduction to C++
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 2: Getting Started.
CS115 FALL Senem KUMOVA-METİN1 The Fundamental Data Types CHAPTER 3.
Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists: An Interpretive Approach Chapter 7: Preprocessing.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Number Systems and Bitwise Operation.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Introduction to C++ Starting Out with C++ Early Objects.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 MT258 Computer Programming and Problem Solving Tutorial 03.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 Objects Types, Variables, and Constants Chapter 3.
7. BASIC TYPES. Systems of numeration Numeric Types C’s basic types include integer types and floating types. Integer types can be either signed or unsigned.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Chapter 2: Introduction to C++
ECE Application Programming
Tokens in C Keywords Identifiers Constants
Chapter 2: Problem Solving Using C++
INC 161 , CPE 100 Computer Programming
Number Systems and Bitwise Operation
Chapter 2: Introduction to C++
Introduction to C Programming
A First Book of ANSI C Fourth Edition
Lectures on Numerical Methods
DATA TYPES There are four basic data types associated with variables:
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Presentation transcript:

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Chapter 3: Number Systems, Scalar Types, and Input and Output Outline: Binary, Octal, Hexadecimal, and Decimal Numbers Character Set Comments Declaration Data Types and Constants Integral Data Types Floating-Point Numbers and Metanumbers Pointer Type Initialization Implicit Type Conversion Introduction to Formatted Input and Output Redirection of Input and Output Debug Programs Using ChIDE

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Binary, Octal, Hexadecimal, and Decimal Binary Binary numbering system has only two possible values for each digit: 0 and 1. For example, binary number decimal number

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Decimal Numbers Decimal The digits' weight increases by powers of 10. The weighted values for each position is determined as follows: For example, A decimal number 4261 can be thought of as follows. 4 * * * * 1 = = 4261 (decimal)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Binary, Octal, Hexadecimal, and Decimal Binary The digits' weight increases by powers of 2. The weighted values for each position is determined as follows: For example, binary 10 is decimal 2. the binary value represents the decimal value * * * * * * * * 1 = = 202 (decimal)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Binary Two’s Complement The left-most bit is the sign bit. If it is 1, then the number is negative. Otherwise, it is positive. Give a negative value, represent it in binary two’s complement form as follows. 1. write the number in its absolute value. 2. complement the binary number. 3. plus 1. Example, represent –2 in binary two’s complement with 16 bits for short int. Binary value of 2: 0b Binary complement of 2: 0b Plus 1: +1 Binary two’s complement representation of -2: 0b

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Give binary two’s complement form of a negative number, find the absolute value of the negative value as follows. 1.Complement the binary number. 2.Plus 1. Example, find the decimal value of (0b ) 2 in binary two’s complement form with 16 bits. Binary two’s complement (0b ) 2 Binary complement (0b ) 2 Plus 1 +1 Absolute value: (0b ) 2 = 2 10 Negative value: -2

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Subtraction of a value in the computer can be treated as addition of its two’s complement. For example, the subtraction of (2-2) can be performed as 2+(-2) as follows: 0b (binary representation of 2) 0b (two’s complement representation of -2) 0b (2+(-2))

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Example > short i, j > i = 0b > j = 0b > i+j 0

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Octal The octal system is based on the binary system with a 3-bit boundary. The octal number system uses base 8 includes 0 through 7. The weighted values for each position is as follows: Binary to Octal Conversion Break the binary number into 3-bit sections from the least significant bit (LSB) to the most significant bit (MSB). Convert the 3-bit binary number to its octal equivalent. For example, the binary value equals to octal value ( ) 8.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists 2.Octal to Binary Conversion Convert the octal number to its 3-bit binary equivalent. Combine all the 3-bit sections. For example, the octal value equals to binary value Octal to Decimal Conversion To convert octal number to decimal number, multiply the value in each position by its octal weight and add each value together. For example, the octal value (167) 8 represents decimal value *64 + 6*8 + 7*1 = 119

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Hexadecimal Similar to octal, the hexadecimal system is also based on the binary system but using 4-bit boundary. The hexadecimal number system uses base 16 including the digits 0 through 9 and the letters A, B, C, D, E, and F. The letters A through F represent the decimal numbers 10 through 15. For the decimal values from 0 to 15, the corresponding hexadecimal values are listed below FEDCBA Decimal Hexadecimal

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists The weighted values for each position is as follows: The conversion between binary value and hexadecimal value is similar to octal number,but using four-bit sections. The hexadecimal value 20A represents decimal value * * *1 = 522

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Following table provides all the information you need to convert from one type number into any other type number for the decimal values from 0 to16. BinaryOctalDecimalHexBinaryOctalDecimalHex A B C D E F

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Character Set The character set in C includes the following members: –the 26 uppercase letters of the Latin alphabet A B C D E F G H I J K L M N O P Q R S T U V W X Y Z –the 26 lowercase letters of the Latin alphabet a b c d e f g h i j k l m n o p q r s t u v w x y z –the 10 decimal digits –the following 31 graphic characters ! " # % & ' ( ) * +, -. / : ; ? [ \ ] ^ _ { | } ~ $ `

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Comments Comments of a C program can be enclosed within a pair of delimiters /* and */. The symbol // will comment out a subsequent text terminated at the end of a line. For example, /* This is a comment */ /* This is a comment across multiple lines */ printf(”Hello, world\n”); // This is a comment terminated at the end of line

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists –An identifier for a variable shall consist of lowercase and uppercase letters, underscore _, and digits. It shall not start with digits. –A variable has to be declared before it can be used inside a program. The following format can be used to declare a variable of simple type. dataType varName; where dataType is one of valid data types and varName is an identifier. –In C99, variables can be declared almost anywhere even after executable statements. int main() { int i; i = 90; int j; j = 20; return 0; } Declaration

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Integer Data Types Integer is a basic data type and can be represented by one of the following data types. char long long signed charsigned long long unsigned charunsigned long long short signed short unsigned short int signed int unsigned int long signed long unsigned long Data Types and Constants

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists > int i > sizeof(int) 4 > sizeof(i) 4 > sizeof(2*i) 4 > sizeof(long long) 8 The sizeof operator gives the size of types or expression in bytes. One byte equals 8 bits.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Int Data Representation –An int data is a signed integer. An int number is a whole number that can be negative, positive, or zero. –An int data uses 4 bytes for storage with 1 bit for the sign. –The int ranges from INT_MIN to INT_MAX, which are – (–2 31 ) and (2 31 –1), respectively. –The unsigned int ranges from 0 to UINT_MAX, which is equal to (2 32 –1). INT_MAX 0b INT_MIN 0b UINT_MAX 0b

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists #include Int main() { printf(”INT_MAX = %d\n”, INT_MAX); printf(”INT_MIN = %d\n”, INT_MIN); printf(”UINT_MAX = %d\n”, UINT_MAX); return 0; } Output: INT_MAX = INT_MIN = UINT_MAX = Program: limits.c

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Short Data Representation –A short data uses 2 bytes for storage. –The macros for minimum and maximum values of signed short are SHRT_MIN and SHRT_MAX defined in header file limits.h. SHRT_MIN is equal to (-2 15 ) and SHRT_MAX is equal to 32767( ). –The macro USHRT_MAX, defined in the header file limits.h, specifies the maximum value of unsigned short. It is equal to 65535( ).

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Long Long Data Representation –Data of long long integral type contains 8 bytes. They have the similar representation as the data type of int. –The long long int ranges from LLONG_MIN to LLONG_MAX, which are LL (-2 63 ) and LL (2 63 –1), respectively. –The long long int ranges from 0 to ULLONG_MAX, which is 2 64 –1.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Integer Constants –An integer can be specified in decimal, binary, octal, or hexadecimal. –A leading 0(zero) on an integer constant indicates an octal integer. –A leading 0x or 0X indicates a hexadecimal integer. –A leading 0b or 0B indicates a binary integer. Example: 30 (decimal) = 036 (octal) = 0X1e or 0x1E (hexadecimal) = 0b11110 or 0B11110 (binary)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Example: C:/Ch> int i C:/Ch> i = C:/Ch> i = 0x1e 30 C:/Ch> i = 0b C:/Ch> printf(”i = %d\n”, i) i = 30 C:/Ch> printf(”i = 0%o\n”, i) i = 036 C:/Ch> printf(”i = 0x%x\n”, i) i = 0x1e C:/Ch> printf(”i = 0b%b\n”, i) i = 0b11110

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Boolean Type The keyword bool of a declarator in header file stdbool.h can be used to declare variables with boolean data type. For example, the following statement b ool b; declares a boolean variable b. A boolean variable only has only two possible values: 1 and 0. Value 1 stands for true and value 0 stands for false. Macro true and false are defined in header file stdbool.h.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Char Data Representation –The char data are used to store characters such as letters and punctuation. An array of char can be used to store a string. –A character is stored as an integer according to a certain numerical code such as the ASCII code that ranges from 0 to 127, which only requires 7 bits to represent it. –Typically, a char constant or variable occupies 1-byte (8 bits) of unit memory. Memory Address Binary valueCharacter H e l l o !

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists –The macros for minimum and maximum values of signed char are CHAR_MIN and CHAR_MAX defined in header file limits.h. CHAR_MIN is equal to -128(-2 7 ) and CHAR_MAX is equal to 127(2 7 -1). –The macro UCHAR_MAX, defined in the header file limits.h, specifies the maximum value of unsigned short. It is equal to 255(2 8 -1). CHAR_MAX = 127 0b CHAR_MIN = b UCHAR_MAX = 255 0b

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Character Constants A character constant, stored as an integer, can be written as one character within a pair of single quotes like ‘x’. A character constant can be assigned to the variable of type char. For example, > char c = ’x’ > c x

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Escape Characters

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists String Literals –A character string literal is a sequence of zero or more multibyte characters enclosed in double quotes, such as “xyz”. –Remember that strings represented as character arrays end with ‘\0’. –Using an array of characters to define a string variable. > char str1[6] = ”abcde” // The last one is ‘\0’ > char str2[] = ”This is a string.”

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Arithmetic operations of two integers are still an integer > > 3/2 1 > 2/3 0 > 2.0/

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Floating-Point Types Floating-point numbers have three representations: float, double, and long double. The float data type uses 32 bits (4 bytes) for its storage. The minimum and maximum values of float data type are defined as macros FLT_MIN and FLT_MAX, respectively, in header file float.h. The double data type uses 64 bits(8 bytes) as its storage. The minimum and maximum values of double data type are defined as macros DBL_MIN and DBL_MAX, respectively, in header file float.h The long double should have at least as many bits as double.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Below is a list of metanumbers for floating-point numbers and their mathematical equivalent. Metanumbers Mathematical Representation Inf -- +Inf ++ NaNNot-a-Number (Invalid value)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists > 0.0/0.0 nan > 1.0/0.0 inf > -1.0/0.0 -inf > sqrt(4) > sqrt(-4) nan Examples for NaN and Inf

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Sample Problem: The system in Figure1 (a) consists of a single body with mass m moving on a horizontal surface. An external force p acts on the body. The coefficient of kinetic friction between body and horizontal surface is . The free body diagram for the system is shown in Figure1 (b). Figure1: The system diagram and FBD of a sample problem

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists The nomenclature related to the modeling of the system.is listed below. m -- mass of the body x -- position of the body v -- velocity of the body a -- acceleration of the body g -- gravitational acceleration  -- friction coefficient f -- friction force N -- normal force Equation of motion: The equation of the motion of the system can be derived based on the Newton's second law. N = mg (1) f =  N (2) p-f = ma (3) From equation (1), (2) and (3), the formula for calculating the acceleration of the rigid body can be derived as follows. a = (p-  mg)/m (4)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Problem Statement: For the system shown in Figure1(a), given m = 5 kg, g = 9.81 m/s 2,  = 0.2. The external force p is expressed as a function of time t, p(t) = 20 when t >= 0 calculate the acceleration a. Solutions. 1.Declare four variables of double type to represent the mass of the body (m), the friction coefficient (mu), the external force (p), and the acceleration(a), respectively. 2.Define macro M_G with the value of 9.81.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Program 1: Declare four variables to calculate the acceleration. Acceleration a = (m/s^2) Output: /* File: accelvar.c */ #include int main() { /* declare variables */ double a, /* acceleration */ mu, /* friction coefficient */ m, /* mass */ p; /* external force */ /* Initialize variables */ mu = 0.2; m = 5.0; p = 20.0; /* Calculate the acceleration */ a = (p-mu*m*9.81)/m; /* display output */ printf("Acceleration a = %f (m/s^2)\n", a); return 0; }

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Program 2: Define macro M_G. /* File: acceldef.c */ #include /* gravitational acceleration */ #define M_G 9.81 int main() { /* declare variables */ double a; /* acceleration */ double mu; /* friction coefficient */ double m; /* mass */ double p; /* external force */ /* Initialize variables */ mu = 0.2; m = 5.0; p = 20.0; /* Calculate the acceleration */ a = (p-mu*m*M_G)/m; /* display output */ printf("Acceleration a = %f (m/s^2)\n", a); return 0; }

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists int i, *p; i = 10; p = &i;// p contains the address of i Pointer Data Type –A pointer is defined as a variable which contains the address of another variable or dynamically allocated memory. –With an asterisk ‘*’ in front of the variable names, the variables of pointer type can be declared similar to variables of other data types. The unary operator ‘&’ gives the “address of a variable”. Example:

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists p = &i;// p now stores the address of i If the address of i is 0x00E81E20, the value of p is 0x00E81E20 as shown below.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Pointer to Char as String char *s = ” This is a string”;

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Initialization –The declaration of a variable may be accompanied by an initializer that specifies the value of the variable should have at the beginning of its lifetime. –The initializer for a scalar shall be a single expression, such as > int i = 6/3 > double d = > char c = ’a’ –An array of character type may be initialized by a character string literal. > char str1[20] = ”this is a string.” > str1 this is a string.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Introduction to Formatted Input and Output Function printf() Precisely formatted output is accomplished using the output function printf. The printf function has following form printf( format-control-string, arguments ); –Format-control-string: Using specifications to describe output format. Each specification begins with a percent sign (%), ends with conversion specifier and is enclosed in quotation marks. –arguments: correspond to each conversion specification in format- control-string.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Table below lists the format-control-string of different argument types for function printf(). Argument TypeFormat-Control-String binary number“%b” in Ch only char“%c” signed char, short, int“%d” unsigned char, short, int“%u” long “%lld” unsigned long long“%ulld” octal number“%o” hexadecimal number“%x” float“%f” double“%f” or “%lf” string“%s” pointer“%p”

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Example: > printf(“%d”, 4261)// decimal integer 4261 > printf(“%lld”, 4261);// decimal long long integer 4261 > printf(“%b”, 4261);// binary number in Ch > printf(“%o”, 4261);// octal number > printf(“%x”, 4261);// hexadecimal number 10a5 > printf(“%f”, 15.0F);// print out a float > printf(“%f”, 15.0);// print out a double float > printf(“%lf”, 15.0); > printf(“%c”, ‘a’); a > printf(“%s”, “This is a string.”); This is a string.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Printing Multiple Numerical Values in a Single Printing Statement > printf(”integer is %d, floating-point number is %f”, 10, 12.34) integer is 10, floating-point number is Use multiple format specifiers. Each format specifier corresponds to an argument.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Precision of Floating-Point Numbers The precision of a floating-point number specifies the number of digits after the decimal point character. The precision typically takes the form of a period (.) followed by an decimal integer. For example, the format “%.2f” specifies the precision with 2 digits after the decimal point. > printf(”%.2f”, ) > printf(”%.2f”, ) > printf(”%.20f”, 0.2) The fractional part after the specified precision number is rounded up. A floating-point number may not be represented exactly.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Function scanf() Precise formatting input is accomplished using the input function scanf. The scanf function has following form scanf( format-control-string, arguments ); –Format-control-string: Using specifications to describe input format. Each specification begins with a percent sign(%), ends with conversion specifier and is enclosed in quotation marks. The format-control-string is similar to format-control-string discussed in printf function. –arguments: pointers to variables in which the input value will be stored.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Table below lists the format-control-string of different argument types for function scanf(). Argument TypeFormat-Control-String binary number“%b” in Ch only char“%c” short“%hd” unsigned short“%uhd” int“%d” unsigned int“%u” long “%lld” unsigned long long“%ulld” float“%f” double“%lf” string“%s” pointer“%p”

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Example: > int i > float f > double d > char c > scanf(“%d”, &i); 10 > i 10 > scanf(“%f”, &f); 10.2 > f > scanf(“%lf”, &d); 15 > d > scanf(“%c”, &c); a > c a

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Example: > int i > scanf(“%d”, &i);// input number in decimal 4261 > Long long l > scanf(“%lld”, &l);// input into long long number 4261 > l 4261 > scanf(“%b”, &i);// input number in binary in Ch // or 0b > i 4261 > scanf(“%o”, &i);// input number in octal 10245// or ‘010245’ > i 4261 > scanf(“%x”, &i);// input number in hexadecimal 10A5// or ‘0x10A5’ or ‘0X10A5’ > i 4261

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists /* File: scanfc.c for input and output example */ #include int main() { int num; double d; printf("Please input an integer and one floating-point number\n); scanf("%d%lf",&num, &d); printf("Your input values are %d and %f\n“, num, d); return 0; } > scanfc.c Please input one integer and one floating-point number Your input number is 10 and > Program scanfc.c Interactive execution of program scanf.c Example:

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Problem Statement: For the system shown in Figure1(a), the external force p is expressed as a function of time t, p(t) = 4(t-3)+20 when t >= 0 write a program to calculate the acceleration a according to the input values for m, , and t.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists /* File: accelio.c */ #include #define M_G 9.81 int main() { double a, mu, m, p, t; printf("***** Acceleration Calculator *****\n\n"); printf("Please enter value for mass in kilogram\n"); scanf("%lf", &m); printf("mass is %lf (kg)====\n\n", m); printf("Please enter value for friction coefficient\n"); scanf("%lf", &mu); printf("friction coefficient is %lf\n\n", mu); printf("Please enter value for time in second\n"); scanf("%lf", &t); printf("time is %lf (s)\n\n", t); p = 4*(t-3)+20; a = (p-mu*m*M_G)/m; printf("Acceleration a = %f (m/s^2)\n", a); return 0; } Program: Using formatted input function scanf.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Interactive execution: > accelio.c ***** Acceleration Calculator ***** Please enter value for mass in kilogram 5 mass is (kg) Please enter value for friction coefficient 0.2 friction coefficient is Please enter value for time in second 2 time is (s) Acceleration a = (m/s^2)

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Redirecting Input from and Output into Files 1) Redirecting Output into Files You can redirect standard output of a program into a file in a command line by the output redirection symbol ‘>’. 2) Redirecting and Appending Output into Files You can redirect and append standard output of a program into a file in a command line by the append redirection symbol ‘>>’.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Program 1: Declare four variables to calculate the acceleration. Acceleration a = (m/s^2) Output: /* File: accelvar.c */ #include int main() { /* declare variables */ double a, /* acceleration */ mu, /* friction coefficient */ m, /* mass */ p; /* external force */ /* Initialize variables */ mu = 0.2; m = 5.0; p = 20.0; /* Calculate the acceleration */ a = (p-mu*m*9.81)/m; /* display output */ printf("Acceleration a = %f (m/s^2)\n", a); return 0; }

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists The command below redirects the output from the program accelvar.c into file accelvar.out The command below redirects and appends the output from the program accelvar.c into file accelvar.out > accelvar.c > accelvar.out > > accelvar.c >> accelvar.out >

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists /* File: scanfc.c for input and output example */ #include int main() { int num; double d; printf("Please input an integer and one floating-point number\n); scanf("%d%lf",&num, &d); printf("Your input values are %d and %f\n“, num, d); return 0; } > scanfc.c Please input one integer and one floating-point number Your input number is 10 and > Program scanfc.c Interactive execution of program scanf.c Example:

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists 3) Redirecting Input from Files You can redirect standard input to a program from a file in a command line by the input redirection symbol ‘<’. For example, if the file scanfc.dat contains the data the command below redirects the standard input to the program scanfc.c from the file scanfc.dat. > scanfc.c < scanfc.data Please input one integer and one floating-point number Your input number is 10 and >

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists Running a C program with input in ChIDE

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists editing pane debug command pane debug pane selection bar breakpoint debug pane output pane debug bar Debug a program in ChIDE When a program is executed in debug mode, the input and output are redirected in a separate debug console window.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists ‡ Slides for optional topics in C

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists –Another way to declare a string. char *str = ”This is a string.”; Here str is a pointer to first character ‘T’. The value of str is the address of the first character.

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists ‡ Slides for optional topics in Ch

Created by Harry H. Cheng,  2009 McGraw-Hill, Inc. All rights reserved. C for Engineers and Scientists String Type in Ch A string in Ch can be declared by type specifier string_t. string_t str = ”This is a string.”;