Chapter 3: Number Systems, Scalar Types, I/O · There are only two possible values for each digit:...
Transcript of Chapter 3: Number Systems, Scalar Types, I/O · There are only two possible values for each digit:...
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Chapter 3: Number Systems,
Scalar Types, I/O
Positional number systems:
• Base
• Digits
• Exponents / Powers
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Decimal Numbers
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 * 1000 + 2 * 100 + 6 * 10 + 1 * 1
= 4000 + 200 + 60 + 1
= 4261 (decimal)
104 103 102 101 100
10000 1000 100 10 1
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Are there any non-positional number systems?
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Binary
The base is 2 instead of 10
There are only two possible values for each digit: 0 and 1.
For example,
binary number decimal number
0 0
1 1
10 2
11 3
100 4
101 5
110 6
1100 1010 202
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Binary
Basic skill: counting in binary (not in text)
“Poor man‟s” conversion: count in decimal and binary, side-by-side
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Binary
The digits' weight increases by powers of 2. The weighted values for each position is
determined as follows:
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
For example,
binary 10 is decimal 2.
the binary value 1100 1010 represents the decimal value 202.
1 * 128 + 1 * 64 + 0 * 32 + 0 * 16 + 1 * 8 + 0 * 4 + 1 * 2 + 0 * 1
= 128 + 64 + 0 + 0 + 8 + 0 + 2 + 0
= 202 (decimal)
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Binary practice
Convert the following binary integers to decimal:
11 =
101 =
101010 =
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
In reverse!
Converting from decimal to binary: repeated division by 2
Example: 13 =
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Practice repeated division algorithm
Convert from decimal to binary:
6 =
41 =
127 =
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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:
83 82 81 80
512 64 8 1
1. 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 1 010 000 111 101 110 100 011 equals to
octal value (12075643)8.
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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 45761023 equals to binary value
100 101 111 110 001 000 010 011.
3. 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 119.
1*64 + 6*8 + 7*1 = 119
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Hexadecimal, a.k.a. hex
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.
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
F E D C B A 9 8 7 6 5 4 3 2 1 0
Decimal
Hexadecimal
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
The weighted values for each position is as follows:
163 162 161 160
4096 256 16 1
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 522.
2*256 + 0*16 + 10*1 = 522
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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.
Binary Octal Decimal Hex Binary Octal Decimal Hex
0000 00 00 00 1001 11 09 09
0001 01 01 01 1010 12 10 A
0010 02 02 02 1011 13 11 B
0011 03 03 03 1100 14 12 C
0100 04 04 04 1101 15 13 D
0101 05 05 05 1110 16 14 E
0110 06 06 06 1111 17 15 F
0111 07 07 07 10000 20 16 10
1000 10 08 08
EoL
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
How about negative numbers?
First idea: sign-magnitude (not in text)
Good for pencil-and-paper, but not very good
for computers!
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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.
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 bit by bit
3. add 1
Example, represent –2 in binary two‟s complement on 16 bits:
• Binary value of 2: 0b 0000 0000 0000 0010
• Binary complement of 2: 0b 1111 1111 1111 1101
• Plus 1: +1
• Two‟s complement representation of -2: 0b 1111 1111 1111 1110
Some C compilers accept this syntax, but
it‟s not standard!
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Give binary two‟s complement form of a negative number, find its absolute value (a.k.a. magnitude)
1. Complement the binary number
2. Add 1
Example: find the decimal value of 0b1111 1111 1111 1110 in binary
two‟s complement form with 16 bits.
• Binary two‟s complement 0b 1111 1111 1111 1110
• Binary complement 0b 0000 0000 0000 0001
• Plus 1 +1
• Absolute value: 0b 0000 0000 0000 0010
• Absolute value in decimal: 210
• Negative value in decimal: -2
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Subtraction of a value in the computer can be implemented as addition of its negative (in two‟s complement!)
Example: 2 – 2 can be performed as 2 + (-2) as follows:
0b 0000 0000 0000 0010 binary representation of 2
0b 1111 1111 1111 1110 two‟s comp. representation of -2
0b 0000 0000 0000 0000 Result (is it correct?)
Practice: calculate
• 5 – 4 =
• 4 – 5 =
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
We‟ve covered section 3.1
In notebook for next time
(do not turn in for grading!)
• End-of-chapter questions 1 and 2 a, b, c, d
– For 2, use only 8 bits, not 32
• Read and take notes: sub-section 3.1.3
Binary Fractions
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
1-minute quiz
What is the decimal value of this two‟s
complement numbers:
• 0111 1111
• 1001 0101
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Extra-credit question
Is two‟s complement a positional number
system?
Explain, either way!
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
The following sections have
been covered in the lab:
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.2 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
0 1 2 3 4 5 6 7 8 9
– the following 31 graphic characters
! " # % & ' ( ) * + , - . / :
; < = > ? [ \ ] ^ _ { | } ~ $ `
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.3 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 Interpretive Approach
– 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;
}
3.4 Declaration
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
• Integer Data Types
Integer is a basic data type and can be represented by one of the
following data types.
char long long
signed char signed long long
unsigned char unsigned 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: An Interpretive Approach
> 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: An Interpretive Approach
• 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
–2147483648(–231) and 2147483647(231–1), respectively.
– The unsigned int ranges from 0 to UINT_MAX, which is equal to 4294967295(232–1).
INT_MAX 0b01111111 11111111 11111111 11111111
INT_MIN 0b10000000 00000000 00000000 00000000
UINT_MAX 0b11111111 11111111 11111111 11111111
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
#include <stdio.h>
#include <limits.h>
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 = 2147483647
INT_MIN = -2147483648
UINT_MAX = 4294967295
Program: limits.c
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
• 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 -32768(-215) and SHRT_MAX is equal to 32767(215-1).
– The macro USHRT_MAX, defined in the header file limits.h, specifies the maximum value of unsigned short. It is equal to 65535(216-1).
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
• 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 -9223372036854775808LL (-263) and
9223372036854775807LL (263–1), respectively.
– The long long int ranges from 0 to ULLONG_MAX, which is 264–1.
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
• 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 (in Ch only). •
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: An Interpretive Approach
Example:
C:/Ch> int i
C:/Ch> i = 036
30
C:/Ch> i = 0x1e
30
C:/Ch> i = 0b11110
30
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: An Interpretive Approach
End of sections have covered in
the lab
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.7 Boolean Type (C99 only!)
The keyword bool can be used to declare variables with boolean data type.
For example, the following statement
bool 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.
true and false are defined in header file stdbool.h, which need to be included!
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.8 Characters– 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 value Character
20000 0 1 0 0 1 0 0 0 H
20001 0 1 1 0 0 1 0 1 e
20002 0 1 1 0 1 1 0 0 l
20003 0 1 1 0 1 1 0 0 l
20004 0 1 1 0 1 1 1 1 o
20005 0 0 1 0 0 0 0 1 !
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
– 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(-27) and CHAR_MAX is equal to
127(27-1).
– The macro UCHAR_MAX, defined in the header file limits.h,
specifies the maximum value of unsigned short. It is equal to
255(28-1).
• CHAR_MAX = 127 0b0111 1111
• CHAR_MIN = -128 0b1000 0000
• UCHAR_MAX = 255 0b1111 1111
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
• 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: An Interpretive Approach
• Escape CharactersEscape Code Description
\a (alert) Produces an audible or visible alert. The active position shall
not be changed.
\b (backspace) Moves the active position to the previous position on the
current line.
\f (form feed) Moves the active position to the initial position at the start
of the next logical page.
\n (new line) Moves the active position to the initial position of the next
line.
\r (carriage return) Moves the active position to the initial position of the
current line.
\t (horizontal tab) Moves the active position to the next horizontal
tabulation position on the current line.
\v (vertical tab) Moves the active position to the initial position of the next
vertical tabulation position.
\\ (backslash) Produces a backslash character \.
\’ (single quote) Produces a single quote character „.
\” (double quote) Produces a double quote character “.
\? (question mark) Produces a question mark character ?.
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
In notebook for next time
(do not turn in for grading!)
Read and take notes: numeric escape codes,
first two paragraphs on p.57
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Strings of characters
• A string of characters is a sequence of zero or more
characters enclosed in double quotes, such as “xyz”.
– Strings can be empty!
• Strings in C are represented as arrays of char
– The last character must be ‘\0’ (ASCII zero)
• 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: An Interpretive Approach
Strings of characters
• Printing a string variable: use format specifier %s
char str1[6] = "abcde" // The last one is '\0'
...
printf("The string is %s \n", str1);
More about strings in Ch.12
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.9 Floating-Point Types
float, double, 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.
• DBL_MIN and DBL_MAX, also in float.h
The long double should have at least as many bits as double
• LDBL_MIN and LDBL_MAX, also in float.h
Let‟s quickly find out!
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Not in text
• In C99, %lf and %f are equivalent
– both can be used interchangeably for float
and double!
• For long double, %Lf should be used
– As long as long double and double are
equivalent, %lf will work too, however...
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Below is a list of metanumbers for floating-point numbers and their
mathematical equivalent.
Meta-numbers
Metanumbers Mathematical Representation
-0.0 0-
+0.0 0+
-Inf -
+Inf +
NaN Not-a-Number (Invalid value)
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
> 0.0/0.0
nan
> 1.0/0.0
inf
> -1.0/0.0
-inf
> sqrt(4)
2.000
> 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: An Interpretive Approach
Sample Problem:
The same as in Ch.2!
Two changes in the solution …
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
/* File: acceldef.c */
#include <stdio.h>
/* 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: An Interpretive Approach
3.10 Complex Types
Read over lightly for now, more in the lab
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
We‟ve covered the following sections of the text:
--end of 3.8
--3.9
--skipped 3.10
Solve in notebook for next time (do not turn
in for grading!):
• End-of-chapter question 5 (a through l)
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
int i, *p;
i = 10;
p = &i; // p contains the address of i
3.11 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:
Diagram not in text: “Two worlds”
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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: An Interpretive Approach
How to declare a String using a Pointer
char *s = ”This is a string”;
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.12 typedef
For convenience, the C programmer can define her/his own data
types, e.g.
typedef unsigned int size_t; //used by sizeof
typedef char[5] DNA_t;
The new data types can be used just like the built-in ones, e.g.
DNA_t seq1, seq2;
DNA_t seq3 = "GATA";
DNA_t seq4 = {'G', 'A', 'T', 'A', '\0',};
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.13 Determining the programming data
model of a computer
Use sizeof, to find the number of Bytes used
internally for each data type (as shown in week 2‟s lab)
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.14 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 must be a single expression, such as
int i = 6/3;
double d = 12.345;
char c = ’a’;
– An array of character type may be initialized by a character string literal (constant).
char str1[20] = ”this is a string.”;
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
3.15 Introduction to Formatted
Input and Output
• 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: An Interpretive Approach
Table 3.5 Format-control-strings for printf().
Argument Type Format-Control-String
binary number “%b” in Ch only
char “%c”
signed char, short, int “%d”
unsigned char, short, int “%u”
long 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: An Interpretive Approach
Printing multiple numerical values in a
single statement
printf(”integer is %d, floating-point number is %f”,
10, 12.34);
Output is:
integer is 10, floating-point number is 12.340000
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: An Interpretive Approach
Precision of Floating-Point Numbers
Specifies the number of digits to be printed after the decimal point .
The precision typically takes the form of a period (.) followed by
an decimal integer.
For example, the format “%.2f” specifies 2 digits after the decimal point.
printf(”%.2f”, 12.1234);
12.12
printf(”%6.2f”, 12.5678);
12.57
printf(”%.20f”, 0.2);
0.20000000000000001110
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: An Interpretive Approach
Precision of Floating-Point Numbers
If represented internally on 4 Bytes, floats have about 7“real” digits of precision .
If represented internally on 8 Bytes, doubles have about 15“real” digits of precision .
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
Field width of numbers
The field width is the size of a field in which data are printed.
An integer width is inserted between % and the conversion specifier
to indicate the field width
For example, “%6d” specifies the field width of 6 for an integer,
“8.4” specifies a field width of 8 with 4 digits after the decimal point.
printf(”%6d”, 12);
12
printf(”%8.4f”, 5.12345);
5.1234
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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: An Interpretive Approach
Table below lists the format-control-string of different argument types for
function scanf().
Argument Type Format-Control-String
binary number “%b” in Ch only
char “%c”
short “%hd”
unsigned short “%uhd”
int “%d”
unsigned int “%u”
long 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: An Interpretive Approach
/* File: scanfc.c for input and output example */
#include <stdio.h>
int main() {
int num;
double d;
printf("Please input one 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;
}
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
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: An Interpretive Approach
/* File: accelio.c */
#include <stdio.h>
#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: An Interpretive Approach
Execution:
Please enter value for mass in kilogram
5
mass is 5.000000 (kg)
Please enter value for friction coefficient
0.2
friction coefficient is 0.200000
Please enter value for time in second
2
time is 2.000000 (s)
Acceleration a = 1.238000 (m/s^2)
Created by Harry H. Cheng, 2009 McGraw-Hill, Inc. All rights reserved.
C for Engineers and Scientists: An Interpretive Approach
SKIP 3.15.3 and 3.15.4
Redirecting
SKIP 3.16
Homework for Ch.3:
Problems 12, 17, 18, 19