How Data Are Stored in The Computer: Decimal System

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 70

The C Programming Language

Basic knowledge

How data are stored in the


computer
Decimal system
356.57=3102 +5 101 +6 100 +5 10-1 +7 10-2

Von Neumann proposed using binary to simplify


hardware implementation
At present, all information in computers is stored
in binary form …
0011010111100011110111010110…
The C Programming Language
Basic knowledge

How data are stored in the


computer
2-byte binary integer representation
1 000 0001 1000 0001 ( Negative )
0 000 0001 1000 0001 ( Positive )
Binary Addition and Multiplication Rules :
0+0=0 0+1=1 1+0=1 1+1=
10
0×0 = 0 0×1 = 0 1×0 = 0 1×1 = 1
The C Programming Language
Basic knowledge

Octal and hexadecimal systems


Octal
Using only 0, 1, 2, 3, 4, 5, 6, and 7 as a system of
numbers, and when coming to eight to carry one.

Hexadecimal
Using 0, 1, ……,9, A, B, C, D, E, and F as a system
of numbers, and when coming to sixteen to carry
one.
The C Programming Language
Basic knowledge

D:decimal B:binary O:octal X:hexadecimal


D B O X D B O X
0 0000 0 0 8 1000 10 8
1 0001 1 1 9 1001 11 9
2 0010 2 2 10 1010 12 A
3 0011 3 3 11 1011 13 B
4 0100 4 4 12 1100 14 C
5 0101 5 5 13 1101 15 D
6 0110 6 6 14 1110 16 E
7 0111 7 7 15 1111 17 F
The C Programming Language
Basic knowledge

transition among binary, octal, and


hexadecimal data

binary  decimal
(1011)2=23+ 21+ 20=8+2+1=11
(1011.11)2=11+2-1+2-2 =11+0.5+0.25=11.75
decimal  binary
269.6875  (?????)2

2 269 1 0.6875
2 134 0  2
2 67 1 1.3750
2 33 1  2
2 16 0 (100001101)2 0.750 (1011)2
2 8 0  2
2 4 0 1.50
2 2 0  2
2 1 1 1

0 269.6875  (100001101.1011)2
The C Programming Language
Basic knowledge

octal  binary
7 3 6 . 2 5 1100 . 0101
001 100 . 010 100
111 011 110 . 010 101
1 4 . 2 4

hexadecimal  binary

A 3 F . 2 B

1010 0011 1111 . 0010 1011


The C Programming Language
Basic knowledge

The presentation of characters in


the computer
There is only binary data in the computer, and
other non-numeric content needs to be coded (The
non-numeric content is numbered by numeric
value)
 ASCII ( American Standards Committee of
Information ) code : It is the most widely used
character encoding scheme in the world developed
by the American Information Exchange Standards
Committee.
The C Programming Language
Basic knowledge

ASCII Code Table


symbols decimal symbols decimal symbols decimal symbols decimal
null 0 □ 16 space 32 0 48
☺ 1 □ 17 ! 33 1 49
☻ 2 2 18 “ 34 2 50
 3 ‼ 19 # 35 3 51
 4 ¶ 20 $ 36 4 52
 5 § 21 % 37 5 53
 6 ▬ 22 & 38 6 54
beep 7 ₤ 23 ‘ 39 7 55
 8 ↑ 24 ( 40 8 56
tab 9 ↓ 25 ) 41 9 57
newlines 10 → 26 * 42 : 58
starting 11 ← 27 + 43 ; 59
position
form-feed 12 ∟ 28 ‘ 44 < 60
Enter 13 ↔ 29 - 45 = 61
♫ 14 ▲ 30 * 46 > 62
☼ 15 ▼ 31 / 47 ? 63
The C Programming Language
Basic knowledge

A total of 128 symbols , 7-bit binary


encoding can be used to represent 27=128
symbols decimal symbols decimal symbols decimal symbols decimal
@ 64 P 80 ` 96 p 112
A 65 Q 81 a 97 q 113
B 66 R 82 b 98 r 114
C 67 S 83 c 99 s 115
D 68 T 84 d 100 t 116
E 69 U 85 e 101 u 117
F 70 V 86 f 102 v 118
G 71 W 87 g 103 w 119
H 72 X 88 h 104 x 120
I 73 Y 89 i 105 y 121
J 74 Z 90 j 106 z 122
K 75 [ 91 k 107 { 123
L 76 \ 92 l 108 | 124
M 77 ] 93 m 109 } 125
N 78 ^ 94 n 110 ~ 126
O 79 _ 95 o 111  127
Identifiers
• One feature present in all computer languages is
the identifier. Identifiers allow us to name data
and other objects in the program. Each identified
object in the computer is stored at a unique
address.
Examples of Valid and Invalid
Names
Keywords In C
reserved words (32)
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
Don’t use keywords as
identifier!
Types
• A type defines a set of values and a set of
operations that can be applied on those
values.
• Topics discussed in this section:
Void Type
Integral Type
Floating-Point Types
FIGURE 1-4 Data Types
Type Summary
Variables
• Variables are named memory locations that
have a type, such as integer or character, which
is inherited from their type. The type determines
the values that a variable may contain and the
operations that may be used with its values.
• Topics discussed in this section:
Variable Declaration
Variable Initialization
FIGURE 1-8 Variables
Examples of Variable
Declarations and Definitions
Chapter 1. A Tutorial Introduction
1.2 Variables and Arithmetic Expressions

1.2 Variables and Arithmetic Expressions


All variables must be declared before they are used.
type variables;
 Examples
int fahr, celsius;
int lower, upper, step;
float total;
An expression is composed with:
Constants, variables, functions, operators
 Examples
fahr=fahr+step;
Chapter 1. A Tutorial Introduction
1.2 Variables and Arithmetic Expressions

 Exercise: Write a program to print the


following pattern: #include <stdio.h>
****
int main( )
#include <stdio.h> ***
{
int main( ) **
int num, i, j;
{ *
scanf("%d", &num);
for(i=num; i>=1; i--){
printf("* * * *\n");
printf(" * * *\n"); for(j=0; j<num-i; j++)
printf(" * *\n"); printf(" ");
printf(" *\n"); for(j=1; j<=i; j++)
return 0; printf("* ");
} printf("\n");
}
return 0;
}
Chapter 1. A Tutorial Introduction
1.2 Variables and Arithmetic Expressions

scanf function: scanf(format, &var1, var2, …)


Example: Find the bigger number between the two integer
numbers read in from the keyboard.
#include <stdio.h>
main()
{
int x, y, z;
scanf(“%d%d”, &x,&y);
if (x > y)
z = x;
else
z = y;
printf(“The bigger is %d\n”, z);
}
Chapter 1. A Tutorial Introduction
1.2 Variables and Arithmetic Expressions

The scanf useful format


Format Function
%d read as decimal integer
%f read as floating point
%o read as octal integer
%x read as hexadecimal integer
%c read as a character
%s read as character string
Chapter 1. A Tutorial Introduction
1.3 The FOR statement

1.3 The FOR statement


 Rewritten program of temperature
converter using FOR:
#include <stdio.h>
/* print Fahrenheit-Celsius table */
main()
{ Assignment: initialization Assignment: increment
int fahr;
for (fahr=0; fahr<=300; fahr=fahr+20)
printf (“%3d %6.1f\n”, fahr, (5.0/9.0)*(fahr-32));
}
Relational exprsssion
For statement
• Not only can it be used in cases where the number of
cycles has been determined
• It can also be used in cases where the number of
cycles is uncertain, but the cycle conditions are given.

For General statement


for(Expression1 ; Expression 2 ; Expression3)
{
Circulatory body
}

06/11/22 29
for

• (1) Solve the value of


e1
expression 1.
• (2) Solve the value of
F
expression 2, if its value is zero, e2
then end the loop and turn to
step (4); if its value is non-zero, End
then execute the loop body. S
• (3) Solve the expression 3 and
turn to step (2). e3
• (4) Execute the statement after
the for statement

06/11/22 30
A B C D

for(Expression1 ; Exp2 ; Exp3) ; statement

ABDCBDCBDCBDC……

06/11/22 31
for
• (1) Expression 1 in the general form of for statement mainly assigns initial
value to loop variable, and it can also be other expressions independent of
loop variable.
• "Expression 1" can be omitted, but the semicolon behind it cannot be omitted.
for( ; i < 5 ; i = i + 1 )
{
sum = sum + i ;
}
When the loop statement is executed, it skips the step of
"Solving Expressions 1" and the rest remains unchanged.

06/11/22 32
for
• (2The value of expression 2 determines whether to
continue the loop.
• "Expression 2" can also be omitted, but the semicolon
after expression 2 cannot be omitted.
for ( i = 1; ; i = i + 1 )
{/*The omission of expression 2 causes the loop to be
dead*/
sum = sum + i;
}

06/11/22 33
for
• (3) "Expression 3" is generally used to change the value
of cyclic variables
• "Expression 3" can also be omitted. Expression 3 can
sometimes be placed after or elsewhere in the built-in
statement as part of the for loop. For example,
for( i = 1 ; i < 5 ; )
{
sum = sum + i ;
i=i+1;
}

06/11/22 34
for
(4) It is possible to omit any two or even all three of
expressions 1, 2 and 3, but neither semicolon can be
omitted. For example,
i = 1;
for ( ; ; )
{ sum = sum + i; i = i + 1; }

• (5) If the loop body statement group contains only


one statement, the "{}" at both ends can be omitted.
• Beginners are advised to retain "{}"
06/11/22 35
Solving the Value of the Continuous Additive Formula 1 + 3 + 5 +...
+ n (n > 10) of the Odd Number
# include <stdio.h>
int main ( )
{
int i, sum = 0;
int n;
printf ( "Input a number: " );
scanf ( "%d", &n );
for ( i = 1; i <= n; i = i + 2 )
{
sum = sum + i;
}
printf ( "1 + 3 + 5 + ... + %d = %d\n", i - 2, sum );
return 0;
}
06/11/22 36
An example of for loop application is given. The results of the
following programs are here:
main( )
10
{
int i;
for(i=0;i<10;i=i+1) ;
printf("%d",i);
}

0123456789

06/11/22 37
Constants
• Constants are data values that cannot be
changed during the execution of a program.
Like variables, constants have a type. In this
section, we discuss Boolean, character,
integer, real, complex, and string constants.
• Topics discussed in this section:
Constant Representation
Coding Constants
Symbolic Names for Control
Characters
Examples of Integer Constants
Examples of Real Constants
Some Strings
FIGURE 1-10 Null Characters and Null Strings
Symbolic constant
Question: the radius of a circle is provided,
calculate its circumference and area.

void main ( )
{ float r, c, a; something to replace
scanf (“%f”, &r); constant 3.1415926?
c = 2 * 3.1415926 * r ;
a = 3.1415926 * r * r; Symbolic Constant
printf(“c= %6.2f, a=%6.2f \n”, c,
a);
#define PAI 3.1415926
Constants and Variables
Symbolic constant
#define PAI 3.1416 /* define symbolic constant */
void main()
{
float r,c,a;
scanf("%f",&r);
c=2*PAI*r; /* When compiling,PAI be replaced by
3.1416 */
a=PAI*r*r; /* When compiling,PAI be replaced by
3.1416 */
printf("c=%6.2f,s=%6.2f\n",c,a);
} macro substitution
Symbolic constant:
Embedded
#define ONE 1
#define COM “company”
#define MAX 100
#define TWO ONE+ONE

a= b+2; a= b+ TWO;
printf (“%s”, “company”); printf(“%s”,COM);
int array[100]; int array[MAX];
Chapter 1. A Tutorial Introduction
1.4 Symbolic Constants

1.4 Symbolic Constants


It is a particular string of characters.
Format :
#define name replacement-text
Function:
Any occurrence of name will be replaced by the
#define LOWER
corresponding 0 /* lower limit of table */
replacement-text.
#define UPPER 300 /*UPPER limit of table */
#define STEP 20 /*step limit of table */
/* print Fahrenheit-Celsius table */
main()
{
 There is no semicolon
int fahr; at the end of a #define line.
for (fahr=LOWER; fahr<=UPPER; fahr=fahr+STEP)
printf (“%3d %6.1f\n”, fahr, (5.0/9.0)*(fahr-32));
}
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

1.5 Character Input and Output


Important View:
In C, the model of Input & Output are supported by
the standard library, and NOT the statements of C.
Tow simplest I/O functions:
 getchar()
read in a character at a time from text stream
c=getchar();
 putchar()
write one character at a time from text stream
putchar(c);
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

 File Copying Algorithm


An assignment can appear as
part of a larger expression.
#include <stdio.h>
/* copy input to output; 1st #include <stdio.h>
version*/ /* copy input to output; 2nd
read in a character version*/
main()
{ While ( character ismain()
not end-of-file indicator)
{
int c; output the character
int
just
c;
read
c=getchar();
read in a{ characterwhile((c=getchar())!=EOF)
while(c!=EOF)
putchar(c); putchar(c);
c=getchar(); }
 What happens if
}
parentheses are omitted?
}
c=getchar()!=EOF
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

/* example: list update (list is put on:\\c++class\\


list.txt )*/
#include <stdio.h>
main()
{
int c;
printf(“%s”, “ 王老师 ");
while((c=getchar())!=EOF){
putchar(c);
if(c==‘\n’) printf(“%s”, “ 王老师 ");
}
}
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

Character Counting
/*Version 2*/
/*Version 1*/ #include <stdio.h>
#include <stdio.h> main()
main() {
{ double nc;
long nc; for(nc=0;getchar()!=EOF;++nc)
nc=0; ; null statement
while(getchar()! printf(“%.0f\n”,nc);
=EOF) }
++nc;
printf(“%ld\n”,nc);
} ++ means increment by one.
++nc  nc=nc+1
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

 a character between
 Line Counting single quotes, called character
constant, represents an integer
value equal to the numerical
#include <stdio.h> value of the character. For
/* count lines in input */ example, ‘A’‘s value is 65, ‘\n’,
main() a escape sequence , is also a
{ legal character constant.
int c, nl;
nl=0;
while(( c=getchar())!=EOF)
if(c==‘\n’)
++nl;  What value does the
printf(“%d\n”,nl); ‘\n’ has?
}
Chapter 1. A Tutorial Introduction
1.5 Character Input and Output

#include <stdio.h>
#define IN 1 /*inside a word */
 Word Counting: #define OUT 0 /*outside a word */
/*count words in input */
main()
{
int c, nw, state;
state=OUT;
 What is the nw=0;
function of the while((c=getchar())!=EOF) {
if(c==' '|| c=='\n'|| c=='\t')
variable state? state=OUT;
else if (state==OUT) {
state=IN;
++nw;
}
}
printf("%d\n", nw);
}
Chapter 1. A Tutorial Introduction
1.6 Arrays

1.6 Arrays
Array Example:
#include <stdio.h>
main()
To count
{ digits, white spaces, others.
int c, i, nwhite, nother;
int ndigit[10];
nwhite=nother=0;
for(i=0;i<10;++i)
ndigit[i]=0;
while((c=getchar())!=EOF)
if(c>=‘0’ && c <=‘9’) ++ndigit[c-’0’];
else if(c==‘ ’ || c ==‘\n’|| c==‘\t’) ++nwhite;
else ++nother;
printf(“digits= ”);
for(i=0,i<10;i++)
printf (“%d”, ndigit[i]);
printf(“, white space=%d, other=%d\n”, nwhite,
nother);
}
Chapter 1. A Tutorial Introduction
1.6 Arrays

 The declaration
int ndigit[10];
ndigit is an array of 10 integers. Its subscripts
start at zero, ndigit[0]…ndigit[9].
 char variables and constants are identical to ints
in arithmetic expressions. c – ‘0’ is an integer
expression with a value between 0 and 9.
e.g. :
#define N 5
main()
{
int i=10;
int b[N];
 which statement is
int c[i]; not correct?
correct
}
Chapter 1. A Tutorial Introduction
1.7 Functions

1.7 Functions
 Function definition form:
1 2 3
return-type function-name (parameter
declarations)
{
declarations
statements
}
Chapter 1. A Tutorial Introduction
1.7 Functions

Example: call n-th power.


#include<stdio.h>
int power(int m,int n);
main()
{
int i;
for(i=0;i<10;i++)
printf(“%d %d %d\n”, i, power(2,i), power(-3,i) );
return 0;
}
/* power: raise base to n-th power: n>= 0 */
int power (int base, int n)
{
int i, p;
p=1;
for(i=1; i<=n; ++i) p=p* base;
return p;
}
Chapter 1. A Tutorial Introduction
1.8 Arguments——call by Value

1.8 Arguments——call by Value


 All function arguments are passed “by value”

/* power: raise base to n-th power; n>=0; version 2*/


int power (int base, int n)
{
int p;

for(p=1;n>0;--n)
p=p* base;
return p;
}
Chapter 1. A Tutorial Introduction
1.9 Character Arrays

1.9 Character Arrays


Example: reads a set of text lines and prints the longest

Algorithm:

while (there’s another line)


if(it’s longer than the previous longest)
save it
save its length
print longest line
Chapter 1. A Tutorial Introduction
1.9 Character Arrays

#include <stdio.h>
#define MAXLINE 1000 /*maxinum input line size */
int getline (char line[ ], int maxline);
void copy(char to[ ], char from[ ]):
main()
{
int len, max;
char line [MAXLINE], longest [MAXLINE];
max = 0;
while(( len = getline (line, MAXLINE)) > 0)
if(len > max)
{max = len; copy (longest, line) ;}
if(max>0) /* there was a line */
printf(“%s”, longest);
return 0;
}
Chapter 1. A Tutorial Introduction
1.9 Character Arrays

/* getline: read a line into s, return length */


int getline(char s[ ],int lim)
{
int c, i;
for(i=0; i<lim-1&&(c=getchar())!=EOF && c!=‘\n’;++i)
s[i]=c;
s[i]=‘\0’;
return i;
}
/* copy: copy ‘from ’ into ‘to’; assume to be big enough */
void copy(char to[ ], char from[ ])
{
int i=0;
while ((to[i]=from[i]) != ‘\0’)
++i;
}

Any String is Terminated with ‘\0’


Chapter 1. A Tutorial Introduction
1.10 External Variables and scope

1.10 External Variables and scope


The variables defined in a function are private or local to
the function, usually known as automatic variables,
which come into existence only when the function is called
and disappear when the function is exited.

The variables defined outside of any function are external


variables, which can be accessed by name by any function
(globally accessible) and remain in existence permanently.
The declaration may be an explicit extern statement or
may be implicit from context.
Chapter 1. A Tutorial Introduction
1.10 External Variables and scope

#include<stdio.h>
#define MAXLINE 1000 main()
{
int max; int len;
char line[MAXLINE]; extern int max;
char longest[MAXLINE]; extern 全局数组可以没长度 char
int getline(void); longest[];
void copy(void); max=0;
while((len=getline())>0)
if(len>max){
max=len;
 In this example, copy();
the extern declarations }
can be omitted. if(max>0)
printf("%s", longest);
return 0;
Chapter 1. A Tutorial Introduction
1.10 External Variables and scope

int getline(void)
{
int c, i;
extern char line[];
for(i=0; i<MAXLINE-1 && (c=getchar()) != EOF && c != '\n'; i++)
line[i]=c;
if(c=='\n'){
line[i]=c;
void copy(void)
i++;
{
}
int i;
line[i]='\0';
extern char line[], longest[];
return i;
} i=0;
while((longest[i]=line[i])!='\0')
++i;
}
Chapter 1. A Tutorial Introduction
1.10 External Variables and scope

If the program is in several source file, and a variable


is defined in file1 andused in file2
 What willand file3,when
happen then the
extern declarations are needed
extern in file2 and file3 to
is omitted?
connect the accurences
file1.c Andofwhen
the variable.
rewrite statement as:
#include <stdio.h> extern float rate=0;
float rate; what will happen?
main()
{ file2.c
int number; float total (int num)
float total(int n); {
extern float rate;
number =10;
rate = 0.98; return rate *num;
printf (“total =%f, number = %d\n”,
}
total (number), number);
}
#include "stdio.h"
#include<stdlib.h>
int main(void)
{ FILE *fp1, *fp2;
char num[16]; char stname[20];
if((fp1=fopen("c:\\c++class\\ 名册 .txt","r")) == NULL){
printf("File open error! \n"); exit(0);
}
if((fp2=fopen("c:\\c++class\\ 名册 2.txt","w")) == NULL){
printf("File open error! \n"); exit(0);
}
while(! feof(fp1)) {
fscanf(fp1, "%s%s", num, stname);
fprintf(fp2,“%6s %10s %8s\n”, “ 王老师 ", num, stname);
}
if(fclose(fp1) && fclose(fp2)){
printf("Can not close the file!\n");
exit(0);
}
return 0;
}
Summary
 Programming is the art of communication algorithms to computer.
 The C system provides a standard library of functions that can be
used by the programmer.
 The C compiler has a proprocessor built into it.
 Statements are ordinarily executed sequentially.
 A program consists of one or more functions written in one or
more files.
 The use of many small functions as a programming style aids
modularity and documentation of programs.
 Arrays, strings, and pointers are intimately related.
Exercises

• P.8 1-1
• P.21 1-12

You might also like