The Lecture for Turbo C

82
The Lecture for Turbo C David Van Schumacher BUPT-QM 07B05 Friday, December 28, 2007

description

This is a set of slides I used for communicating with my classmates about Course Programming Fundermental

Transcript of The Lecture for Turbo C

Page 1: The Lecture for Turbo C

The Lecture forTurbo C

David Van SchumacherBUPT-QM 07B05

Friday, December 28, 2007

Page 2: The Lecture for Turbo C

STRINGS FUNCTIONSSection A

Page 3: The Lecture for Turbo C

Fundamental functions

• Input–scanf–getchar–gets

• Output–printf–putchar–puts

Page 4: The Lecture for Turbo C

Grammar

• scanf(“input format”,&variety name);• gets(variety name);• variety name = getchar();

Page 5: The Lecture for Turbo C

What’s string in turbo C

• It’s NOT a string anymore.• It is seemed as a series of characters, which is

a character array.• The number of the character array is just the

same as the number of letters of the word or sentence plus one.

• The one more element is “\0” which is printed as “\n” by gets and printed as “”(NULL) by other words.

Page 6: The Lecture for Turbo C

Library Functions<string.h>

• strcat(string1,string2)– Appends string2 to the end of string1– Usage: Create the name of data file.

• strlen(string)– Returns the length of string. Doesn’t include the “\

0”!!!!!!!!!– Usage: Determine whether a input data is valid for

your program.

Page 7: The Lecture for Turbo C

Library Functions<string.h>

• strcpy(string1,string2)– Copies string2 to string1, including the “\0”

• strncpy(string1,string2,n)– Copies at most n characters of string2 to string1. If

string2 has fewer than n characters, it pads string1 with “\0”s.

– Usage: Used for Create a short file name if a string is too long.

Page 8: The Lecture for Turbo C

Library Functions<string.h>

• strcmp(string1,string2)– Compares string1 to string2. Returns a negative

integer if string1<string2. 0 if string1==string2. positive integer if string1>string2.

• strncmp(string1,string2,n)– Compares the first n letters of string1 and string2

return the value as function “strcmp”.• Usage: We can use it for comparing if your

program work properly when you call some data file.

Page 9: The Lecture for Turbo C

Library Functions<ctype.h>

• isalpha (determine whether is it a letter)• isupper (determine whether is it uppercase)• islower (determine whether is it lowercase)• isdigit (determine whether is it a number)• ispunct (determine whether is it a punctuation)• toupper (change lowercase to uppercase)• tolower (change uppercase to lowercase)

• Format: Function name(character variety name)• True ----- !0 False ----- 0

Page 10: The Lecture for Turbo C

Usage

• To make your name of data file more clearly. • And we can use it for determine whether a

input in valid.

Page 11: The Lecture for Turbo C

Library Functions<stdlib.h>

• atoi – Converts an ASCII string to an integer. Conversion

stops at the first noninteger character.• atof

– Converts an ASCII string to a double-precision number. Conversion stops at the first character that cannot be interpreted as a double.

• itoa– Converts an integer to an ASCII string.– Format: itoa(number,string,n)

Page 12: The Lecture for Turbo C

DEALING WITH STRINGSSection B

Page 13: The Lecture for Turbo C

Example

• Write a program that prompts the user to type in four character strings, places these in an array of strings, and then prints out: (e.g. I am Peter Pan)

1. The four strings in reverse order. (e.g. Pan Peter am I)

2. The four strings in the original order, but with each string backwards. (e.g. I ma reteP naP)

3. The four strings in reverse order with each string backwards. (e.g. naP reteP ma I)

Page 14: The Lecture for Turbo C

way Ⅰ

• sscanf• Please see page 372 of the book1.Declare a character array2.Grammar: sscanf(character array name,

“format”, varieties to store the integer of the character)

Page 15: The Lecture for Turbo C

Solution Ⅰ char x[40],a[4][10]; int i,j,b[4]; printf("\n\nPlease input four

words:"); gets(x); sscanf(x,"%s %s %s %s",

a[0],a[1],a[2],a[3]); for(i=3;i>-1;i--) printf("%s ",a[i]); printf(“\n");

Page 16: The Lecture for Turbo C

Solution Ⅰ for(i=0;i<4;i++) b[i]=strlen(a[i])-1; for(i=0;i<4;i++) { for(j=b[i];j>=0;j--) printf("%c",a[i][j]);printf(" "); } printf("\n"); for(i=3;i>=0;i--) { for(j=b[i];j>=0;j--) printf("%c",a[i][j]);printf(" "); }

Page 17: The Lecture for Turbo C

WAY Ⅱ

• Save as a string.1.Use Gets to receive the input and check

whether is it valid for your program.2.If that is valid, do the next step.

Page 18: The Lecture for Turbo C

Solution Ⅱint i,j; char str[4][11]; printf("Please insert four strings :\n");for(i=0;i<4;i++) scanf("%s",&str[i]);printf("The four strings you have just input are:\

n");for(i=0;i<4;i++) printf(" %s",str[i]); printf("\n");

Page 19: The Lecture for Turbo C

Solution Ⅱfor(i=3;i>=0;i--)printf(" %s",str[i]);printf("\n");

for(i=0;i<4;i++){ for(j=6;j>=0;j--) { printf("%c",str[i][j]); }} printf("\n");

for(i=3;i>=0;i--){ for(j=6;j>=0;j--) { printf("%c",str[i][j]); }}printf("\n");return 0;

Page 20: The Lecture for Turbo C

Way Ⅲ

• Use the sentence• while((c = getchar()) && “conditions”)

Page 21: The Lecture for Turbo C

Solution Ⅲ

• We omit it here. Because it isn’t good at dealing with strings

Page 22: The Lecture for Turbo C

Summarize

• Use the method of coordinate can deal with the strings character by character.

Page 23: The Lecture for Turbo C

INPUT VALIDATIONSection C

Page 24: The Lecture for Turbo C

Exercise

• Write a C program that reads several positive numbers and uses the function round_to_nearest to round each of these numbers to the nearest integer. The program should print both the original number and the rounded number.

Page 25: The Lecture for Turbo C

Answer

int main(){ float a; void round_to_nearest(float); printf("Please input a real number:"); scanf("%f",&a); round_to_nearest(a); return 0;}

Page 26: The Lecture for Turbo C

Answer

void round_to_nearest(float a){ int z; float x; z=a;x=a-z; if(x>=0.5) z++; printf("\nthe original number is:%f",a); printf("\nthe rounded number is:%d",z);}

Page 27: The Lecture for Turbo C

Question

• What will happen if I enter “AB.CD”???

How could that happen??????

Page 28: The Lecture for Turbo C

Input Validation

• Because the input is invalid to the program.• A invalid value can cause so damaging errors

to your program.• So we should found the invalid input out.

Page 29: The Lecture for Turbo C

Solution with Way Ⅰ

char apple[8];float number; printf(“please enter a number:”);gets(apple);sscanf(apple,“%f”,&number);

Page 30: The Lecture for Turbo C

Solution with Way Ⅱint isfloat(char *c,int number){ int pdp=1,i,dec; if (*c != '-' && *c != '+' && (*c < '0' || *c >'9')) return 0; for (i=1;i<number;i++) if (*(c+i) == '.') {*(c+i)='0';dec = i;break;} for (i=1;i<number;i++) { pdp = pdp * isdigit(*(c+i)); if (pdp>1000) pdp=1; } *(c+dec) = '.'; if (pdp==0) dec=0; else dec=1; return dec;}

Page 31: The Lecture for Turbo C

The String in functions

• We can’t pass a string into a function, because it is an array.

• We can only tell the function where the address of the first letter.

• We pass the address to the letter, and from that, we get all addresses.

• Then, we can change their value.

Page 32: The Lecture for Turbo C

float getscore(void){ char c,i=0,n=0,number[9]; float score;while((c=getchar())!='\n') { if (c!=‘.’&&(c<‘0’||c>’9’)) {printf ("Warning: please enter a number!!!\n"); return -1.0;} if (c==‘.’) i=1; if (i==1&&c==‘.’) {printf("Warning:too much decimal point!\n");return -1.0;} if (n>=7) {printf("Warning:we only accept 6 digits!\n");return -1.0;} number[n++]=c; }score = atof(number); return score;}

Solution with Way ⅢCan be replaced by the function isdigit

What is it used for?

Page 33: The Lecture for Turbo C

Summarize: sscanf

Advantage• Can save numbers and

strings at the same time.• Can easy turn every digits to

a value.

Disadvantage• Can not find invalid value

and give the user a warning.

Page 34: The Lecture for Turbo C

Examplechar x[40],a[4][10]; int i,j,b[4]; printf("\n\nPlease input four words:"); gets(x); sscanf(x,"%s %s %s %s",

a[0],a[1],a[2],a[3]); for(i=3;i>-1;i--) printf("%s ",a[i]); printf("\n");

Page 35: The Lecture for Turbo C

Summarize: Saving as strings

Advantages• Can check invalid inputs and

give the user a warning.• Can correct some invalid

inputs in some cases.

Disadvantages• if the length of the input is

not fixed, it will be very hard to control.

• It can be very hard to turn the strings to number.

Page 36: The Lecture for Turbo C

Exampleint main(){ char K[100]; int i,k=1; while (k!=0) { k=0; printf("please type in your time(m:ss.kkk):"); gets(K); i=strlen(K); if (K[1]!=':'||K[4]!=‘.’) {k=1; } else {k[1]=0;k[4]=0;} if (i!=8) k=1; for (i=0;i<8;i++) if (K[i]<‘0’&&K[i]>‘9’) k=1; if (k==1) printf (“error! Please enter time as m:ss.kkk”); }

After we make sure the input is valid. We can use sscanf deal with the strings!

Page 37: The Lecture for Turbo C

Summarize:Use while((c = getchar()) && “conditions”)

Advantages• Can check all kinds of wrong

input. And give responsible warnings!

Disadvantages• Can be too complex and

waste too much time!• Strongly recommend that

not to use this method while examination.

• Strongly recommend that use it when you design a program.

Page 38: The Lecture for Turbo C

Example GetScore1: printf ("The score for \"easy to read\":"); scoreEasy = getscore(); if (scoreEasy>1.0 ||scoreEasy<0.0) {

printf("Note:the score should be in [0,1]!\n");goto GetScore1;

} printf ("the score is %3.1f\n",scoreEasy); i++;

Page 39: The Lecture for Turbo C

goto

• The command ‘goto’ can be used everywhere in your program.

• Grammar: goto Linename;• You should name one line in your program in

your program as “getscore1:”

Page 40: The Lecture for Turbo C

Note

• Most programmer don’t like ‘goto’ because it can cause confusions.

• We use some dead repetition instead.• Such as “while(1)”

Page 41: The Lecture for Turbo C

float getscore(void){ char c,i=0,n=0,number[9]; float score;while((c=getchar())!='\n') { if (c!=‘.’&&(c<‘0’||c>’9’)) {printf ("Warning: please enter a number!!!\n"); return -1.0;} if (c==‘.’) i=1; if (i==1&&c==‘.’) {printf("Warning:too much decimal point!\n");return -1.0;} if (n>=7) {printf("Warning:we only accept 6 digits!\n");return -1.0;} number[n++]=c; } getchar(); score = atof(number); return score;}

Page 42: The Lecture for Turbo C

How to set limit?

• Sometimes, we want to set a limit of length for our users. If the user input something too long, we have to ignore the last letters.

Page 43: The Lecture for Turbo C

Methodwhile((c=getchar())&&(i++)<max) {……}if (n>=max) { while (1) { c=getchar(); if (c==‘\n’) break; } }

Page 44: The Lecture for Turbo C

Another problem

• If one want to find the rounded number for several times, what should he do?

• Obviously, he can only run the program for lots of times. What would he think?

• How foolish the programmer are!

Page 45: The Lecture for Turbo C

We change the program

int Num, ok=1;float num;do{ num = getscore(); if (num<1) { printf(“no negative please! \n”); continue; }Num = round_to_nearest(num);ok = Continue();}while(ok==0);

Page 46: The Lecture for Turbo C

int Continue();do { char c; int ok=3; printf(“do you want to continue?(Y/N):”); c = getchar(); if (c!=‘\n’) getchar(); if (c==‘\n’ || c==‘y’ || c==‘Y’) ok = 0; if (c==‘n’||c==‘N’) ok =1; } while (ok==3);return ok;

Page 47: The Lecture for Turbo C

continue

• Stop the reputation and re-start it from the beginning but all varieties will keep the current value.

Page 48: The Lecture for Turbo C

By the way

• When we use the method III we always need the ASCII code for some characters. What should we do with that?

• In fact we can use Turbo C and ask the computer to show you the ASCII numbers.

Page 49: The Lecture for Turbo C

Program

for (i=0;i<=255;i++;) printf(“%d---%c”, i,(char) i);

• Note the range of ASCII code is from -127 to 128

Page 50: The Lecture for Turbo C

Input Validation

• This kind of processes are used for avoiding mis-input which caused by ‘enter’ hasn’t been got by your program.

• Moreover, you can design that if an user try too many times he can choose to exit. (Hint: use the exit() in <stdlib.h>)

Page 51: The Lecture for Turbo C

New Year Gifts

• I have made several input validation sub-program in the library <DSINPUT.h>.

• I hope you can enjoy it!• There are six functions in my library.

Page 52: The Lecture for Turbo C

<DSINPUT.H>

• in_p_int (int max) <max<=30000>– Ask the user enter a positive number smaller than

max value.• in_n_int (int min) <min>=-30000>

– Ask the user enter a negative number that larger than min value.

• in_int (int min, int max)– Ask the user enter a number that larger than min

value and smaller than min value.

Page 53: The Lecture for Turbo C

• void goon()– Ask the user if he’d like to use the program again.

• in_float (int min, int max)– Ask the user enter a real number that larger than min

value and smaller than min value.• int isfloat(char *c,int number)

– *c is the head address of a string. Number is the length of the string

– Determine whether a string can be turned to real number.

• int isstring(char *str)– Determine whether is a string a sentence. If so return

1, otherwise return 0.

<DSINPUT.H>

Page 54: The Lecture for Turbo C

FIND HELPSection D

Page 55: The Lecture for Turbo C

Need help?

• Don’t go to the teacher or Zhangfan or me.• Try to think about it by yourself.• If you need more help please try to use the

help in turbo C. ,

Page 56: The Lecture for Turbo C

Let me show some examples

• Study time functions.

Page 57: The Lecture for Turbo C

Let me show some examples

• Study time functions.

For the function “delay”

The function “delay” ask the program have a pause before next command (ms)

A constant

Page 58: The Lecture for Turbo C

Time functions

• In fact, the faction clock() doesn’t give the program a real time. What the function give to the program can be seemed as a “time number”.

• The constant CLK_TCK can turn the difference of “time number” to real time. The CLK_TCK equals to 18.200

Page 59: The Lecture for Turbo C

Constant

Page 60: The Lecture for Turbo C

• Study random functions

Let me show some examples

Page 61: The Lecture for Turbo C

• Study random functions

Let me show some examples

Can be placed by time(NULL)If you do so, this sentence can be omitted

Page 62: The Lecture for Turbo C

Let me show some examples

• Study random functions

Page 63: The Lecture for Turbo C
Page 64: The Lecture for Turbo C

rand

• The random function rand can only offer some fixed random number.

• If you run the same program for several times, the random numbers offered by rand() will always be the same numbers.

Page 65: The Lecture for Turbo C

Example#include<stdio.h>#include<stdlib.h>int main(){ int i; for(i=1;i<=10;i++) printf ("number %d:%d\n",i,rand()); printf ("\n"); return 0;}

Page 66: The Lecture for Turbo C

Output

Just the same

Page 67: The Lecture for Turbo C

Let me show some examples

• Study random functions

Page 68: The Lecture for Turbo C

random

• The random function rand can only offer some fixed random number.

• If you run the same program for several times, the random numbers offered by rand() will always be the same numbers.

Page 69: The Lecture for Turbo C

Example#include<stdio.h>#include<stdlib.h>int main(){ int i; for(i=1;i<=10;i++) printf ("number %d:%d\n",i,random(10000)); printf ("\n"); return 0;}

Page 70: The Lecture for Turbo C

Output

Just the same

Page 71: The Lecture for Turbo C

Problem

• How can rand() and random() return a real random number?

• We can use randomize()

Page 72: The Lecture for Turbo C

Let me show some examples

• Study random functions

Page 73: The Lecture for Turbo C

Example Ⅰ#include<stdio.h>#include<stdlib.h>int main(){ int i; randomize(); for(i=1;i<=10;i++) printf ("number %d:%d\n",i,rand()); printf ("\n"); return 0;}

Page 74: The Lecture for Turbo C

Output

Page 75: The Lecture for Turbo C

Example Ⅱ#include<stdio.h>#include<stdlib.h>int main(){ int i; randomize(); for(i=1;i<=10;i++) printf ("number %d:%d\n",i,random(10000)); printf ("\n"); return 0;}

Page 76: The Lecture for Turbo C

Output

Page 77: The Lecture for Turbo C

More examples

• Game• TT

• Source code• Game• TT

• These programs use both time functions and random functions.

Page 78: The Lecture for Turbo C

DEBUG YOUR PROGRAMSection E

Page 79: The Lecture for Turbo C

method

• Find the value of your variety that might cause bugs.

• If all the value is right, check the following:– use ‘=’ properly or not– check the variety of left side and right side of ‘=’ is

in the right order.

Page 80: The Lecture for Turbo C

WHITE PROGRAMSection F

Page 81: The Lecture for Turbo C

Note

• check {} ()• use space properly• made the structure of your program more

clearly.• How to name your variety

Page 82: The Lecture for Turbo C

The End

Thank you very muchConnect with me at

[email protected]