Chapter 1: A Tutorial Introduction Chapter 1: A Tutorial Introduction
Chapter 1: A Tutorial Introduction Chapter 1: A Tutorial Introduction
E
Executable
t bl fil
file
Editor
So rce code: hello.c
Source helloc
#include <stdio.h>
Assembler
main()
{
Object file: hello.obj
printf(“Hello world₩n”);
Compiler
}
main ()
C F 32
{
int fahr, celsius; 5
int lower, upper, step;
9
lower=0;
upper=300;
step=20;
fahr=lower;
while(fahr
( <=upper)) {
celsius = 5*(fahr-32)/9;
printf("%d₩t%d₩n", fahr,celsius);
f h f h t
fahr=fahr+step;
}
}
Basic data type
Integer: “int”
16-bit ints ( from -32768 to +32767), 32-bits ints
Floating point: “float”
-38 38
Fractional part (32-bit ): 10 ~10
Character –a single byte: “char”
Short integer: “short”
Long integer: “long”
Double-precision floating point:”double”
Overflow
G
Guess what
h values
l are printed
dbby ffollowing
ll program
#include <stdio.h>
main ()
{
int i;
I = 32767;
printf("%d
printf( %d %d %d ₩n
₩n", i,i+1,i+2);
i i+1 i+2);
}
#include <stdio
<stdio.h>
h>
lower=0;
upper=300;
step=20;
p
fahr=lower;
while(fahr <=upper) {
celsius = (5./9.)*(fahr-32.0);
printf("%3.0f %6.1f₩n", fahr,celsius);
fahr=fahr+step;
}
}
Format specifier in “printf”
printf
#include <stdio.h>
main()
{
printf( /%d/₩n , 336);
printf("/%d/₩n",
printf("/%2d/₩n",336);
printf("/%10d/₩n",336);
p
printf("/%-10d/₩n",336);
,
}
Example2
#include <stdio.h>
main()
{
printf("/%f/
i tf("/%f/ ₩n",1234.56);
₩ " 1234 56)
printf("/%e/ ₩n",1234.56);
printf("/%4.2f/ ₩n",1234.56);
printf("/%3
printf( /%3.1f/
1f/ ₩n
₩n",1234.56);
1234 56);
printf("/%10.3f/ ₩n",1234.56);
printf("/%10.3e/ ₩n",1234.56);
}
The For statement
#include <stdio.h>
c=getchar() ;
p
putchar(c);
( );
Exercise
Write a code for
Read a character
While (character is not end-of-file indicator)
output the character just read
read character
First verson
#include <stdio.h>
//*copy
copy input to output: 1st version *//
main()
{
int c;
c=getchar();
while (c != EOF) {
putchar(c);
c=getchar();
}
}
Second version
#include <stdio.h>
//*copy
copy input to output: 1st version *//
main()
{
int c;
putchar(c); // c = getchar() !=
! EOF
c=getchar();
}
}
Character counting program
#include <stdio.h>
main()
{
long nc;
nc=0;
while ( getchar()
() !=EOF))
++nc;
// line counting
printf(" %ld₩n", nc);
} // if(c==
if(c ‘/n’)
// ++nc
Word counting
#include <stdio.h>
main()
{
int c,nl,nw,nc,state;
state=OUT;
nl=nw=nc=0;
while ( (c=getchar()) != EOF) {
++nc;
if ( c
c=='₩n')
₩n )
++nl;
if( c==' ' || c== '₩n' || c=='₩t')
state =OUT;
else if (state
( == OUT)) {
state =IN;
++nw;
}
}
printf("%d %d %d₩n", nl,nw,nc);
}
Home work
E
Exercise
i 1 1-1
1 to
t 1-12
1 12