MT258 Computer Programming and Problem Solving

40
1 MT258 Computer Programming and Problem Solving Unit 5

description

MT258 Computer Programming and Problem Solving. Unit 5. UNIT Five Abstract data and hidden code. Abstract data type (ADT). A data type is defined by its behavior more so than its representation. An abstract data type (ADT) is a set of data items and its operations. Records for typedef. - PowerPoint PPT Presentation

Transcript of MT258 Computer Programming and Problem Solving

Page 1: MT258 Computer Programming  and Problem Solving

1

MT258

Computer Programming and

Problem Solving

Unit 5

Page 2: MT258 Computer Programming  and Problem Solving

2

UNIT FiveAbstract data and hidden code

Page 3: MT258 Computer Programming  and Problem Solving

3

Abstract data type (ADT)

A data type is defined by its behavior more so than its representation.

An abstract data type (ADT) is a set of data items and its operations.

Page 4: MT258 Computer Programming  and Problem Solving

4

Records for typedef

Example :• typedef

• struct

• {

• int month;

• int day;

• int year;

• }

• date_t;

• date_t datestart;

• date_t dateend;

Page 5: MT258 Computer Programming  and Problem Solving

5

Records for typedef

Example :• typedef struct Rational_type {

• int numerator, denominator;} RATIONAL;

• RATIONAL temp;

Page 6: MT258 Computer Programming  and Problem Solving

6

Abstract data type (ADT)#include <stdio.h>

typedef struct Rational_type { int numerator, denominator;} RATIONAL;

RATIONAL get_rat(void) { RATIONAL temp; printf("Please enter the numerator of a rational number: "); scanf("%d", &temp.numerator); printf("Please enter the denominator of a rational number: "); scanf("%d", &temp.denominator); return temp; }

RATIONAL Add_rational (RATIONAL r1, RATIONAL r2) { RATIONAL temp; temp.numerator = r1.numerator * r2.denominator + r2.numerator * r1.denominator; temp.denominator = r1.denominator * r2.denominator; return temp; }

Page 7: MT258 Computer Programming  and Problem Solving

7

Abstract data type (ADT)void print_rat(RATIONAL rat) {

printf("%d / %d",rat.numerator,rat.denominator);

}

void main() {

RATIONAL rat1, rat2, rat_result;

rat1=get_rat();

rat2=get_rat();

rat_result = Add_rational(rat1, rat2);

printf("The sum of ");

print_rat(rat1);

printf(" and ");

print_rat(rat2);

printf(" is ");

print_rat(rat_result);

printf("\n\n");

printf("Press Enter to bye\n");

fflush(stdin);

getchar(); }

Page 8: MT258 Computer Programming  and Problem Solving

8

Abstract data type (ADT)

Page 9: MT258 Computer Programming  and Problem Solving

9

String A string in C is a group of characters enclosed by double quotes.

Character arrays• String “first” is really a static array of characters• Character arrays can be initialized using string literals

char string1[] = "first";• Null character '\0' terminates strings• string1 actually has 6 elements

– It is equivalent to char string1[] = { 'f','i','r','s','t','\0' };• Can access individual characters

string1[ 3 ] is character ‘s’• Array name is address of array, so & not needed for scanf

scanf( "%s", string2 );• Reads characters until whitespace encountered• Can write beyond end of array, be careful

Page 10: MT258 Computer Programming  and Problem Solving

10

Strings

char x[];• e.g. char x[100]; • Use [ ] to access individual character• indexing begins with 0

The null character or \0 has the ASCII value zero, which signals the end of a string.

String1[0]=‘\0’; String 1 will be treated as an empty string.

Page 11: MT258 Computer Programming  and Problem Solving

11

Strings Example :

#include <stdio.h>

int main(int argc, char **argv){ char x[10]="computer"; printf ("%c,%c\n",x[1],x[2]); getchar(); return 0;}

Output : o,m

Page 12: MT258 Computer Programming  and Problem Solving

12

Strings Example :

#include <stdio.h>

void main() {

char string1[25]=”Hello. I am a C program.”;

printf(“first time: %s\n\n”,string1);

string1[5] = ‘\0’;

printf(“second time: %s\n\n”,string1);

printf(“You may press Enter to bye\n”);

fflush(stdin);

getchar();

}

Output

first time: Hello. I am a C program.second time: HelloYou may press Enter to bye

Page 13: MT258 Computer Programming  and Problem Solving

13

Strings Example :

#include <stdio.h>

void main() {

char string[9]=”Hi there”;

printf(“as is | %s|\n”,string);

printf(“format 1| %2s|\n”,string);

printf(“format 2| %20s|\n”,string);

printf(“format 3| %-20s|\n”,string);

printf(“You may press Enter to bye\n”);

fflush(stdin);

getchar(); } Output

as is | Hi there|format 1| Hi there|format 2| Hi there|format 3| Hi there |You may press Enter to bye

Page 14: MT258 Computer Programming  and Problem Solving

14

Strings

The following are all equivalent.• char hello[] = “Hi there”;• char hello[] = {‘H’,’i’, ‘ ‘,’t’,’h’,’e’,’r’,’e’,’\0’};• char *hello=“Hi there”;

const char *hello=“Hi there”;• When the keyword const is used, the content cannot be

modified.

Page 15: MT258 Computer Programming  and Problem Solving

15

Two-dimensional array of characters

Example

char catNames[5][10]=

{“ severe”, “very high”, ” high”,” medium”, ”low”};

Page 16: MT258 Computer Programming  and Problem Solving

16

Strings

Functions• puts

• syntax #include <stdio.h>

• int puts(const char *s);– char string[6]=“celia”;

– puts(string);

• The function puts only accepts a string as its parameter and displays all characters in the string until \0 is encountered.

Page 17: MT258 Computer Programming  and Problem Solving

17

Strings

Functions• gets

• syntax #include<stdio.h>• char *gets(char *s)

– char string[10];

– gets(string);

• The function gets reads one character at a time from the input stream until a carriage return is encountered.

• It does not include \n character, but puts in a null \0 to signal the end of the string.

Page 18: MT258 Computer Programming  and Problem Solving

18

Strings

Example :

#include <stdio.h>

void main() {

char s1[20],s2[20];

scanf(“%s %s”,s1,s2);

printf(“|%s|\n”,s1);

printf(“|%s|\n”,s2);

fflush(stdin);

gets (s1);

printf(“|%s|\n”,s1);

fflush(stdin);

gets (s2);

printf(“|%s|\n”,s2);

printf(“You may press Enter to bye\n”);

fflush(stdin);

getchar();

}

Output1234 67890|1234||67890|

1234 67890|1234 67890|

67890| 67890|You may press Enter to bye

Page 19: MT258 Computer Programming  and Problem Solving

19

Strings.h

Page 20: MT258 Computer Programming  and Problem Solving

20

Character Array (activity)

For each value, declare a variable in C and initialize the variables :

i) ABC (character array only and not string)

ii) 30 Good Shepherd St.

Page 21: MT258 Computer Programming  and Problem Solving

21

Array (activity) For each value, declare a variable in C an

d initialize the variables :

i) ABC (character array only and not string)

• char aString[] ={‘A’, ‘B’, ‘C’};

ii) 30 Good Shepherd St.• char aString[] = “30 Good Shepherd St. “;

Page 22: MT258 Computer Programming  and Problem Solving

22

The basics of I/O

Input to a C program• A sequence of data bytes coming in.

Output to a C program• A sequence of data bytes going out.

Page 23: MT258 Computer Programming  and Problem Solving

23

Data hierarchy

bit 0 byte 01000001 (ASCII character of ‘A’) 28 = 256 (possible values) field record file database

Page 24: MT258 Computer Programming  and Problem Solving

24

Data Streams

Standard input stream• int getchar(void);

Standard out stream• int putchar(int c);

Standard error stream

Page 25: MT258 Computer Programming  and Problem Solving

25

Buffering

Keyboard Buffer Programstandard

input

Page 26: MT258 Computer Programming  and Problem Solving

26

File manipulation

A record is represented in C by structure. A file that is a group of logically related rec

ords is called a data file.

Page 27: MT258 Computer Programming  and Problem Solving

27

Text files

A text file is a collection of characters saved in the secondary storage and has no fixed size.

The computer places a special <eof> end-of-file character to mark the end of file.

Each separate line ends with a <newline> character.

You can create and edit a text file using an editor program.

Page 28: MT258 Computer Programming  and Problem Solving

28

File pointer variable

Declare file pointer variables.• FILE* infile;• FILE* outfile;

Page 29: MT258 Computer Programming  and Problem Solving

29

Open a file

File Acess modes• r open for read only• w open for write only

(if the file exists, it will be overwritten) • a open for append, i.e. adding to the EOF,

if the file exists

Page 30: MT258 Computer Programming  and Problem Solving

30

Establishing a data file

File* output; if ( (outfile = fopen(“a:\sample.dat”. “w”) = = NULL) { printf(“Output File cannot be opened.\n”); return 1; }

Page 31: MT258 Computer Programming  and Problem Solving

31

Common I/O functions concerning characters

Page 32: MT258 Computer Programming  and Problem Solving

32

Functions that access user-defined files ch = getc(infile); putc(ch, outfile); fgets(buffer, BUFFERLEN, infile); fputs(buffer, outfile); fscanf(infile, “%d”, &no); fprintf(outfile, “OUHK”); rewind(infile);

Page 33: MT258 Computer Programming  and Problem Solving

33

Closing a file

fclose(infile); fclose(output);

Page 34: MT258 Computer Programming  and Problem Solving

34

Examples #include <stdio.h> int main() { int data; FILE* fpInput; FILE* fpOutput; fpInput = fopen(“InputOutput2.c”, “r”); fpOutput = fopen(“InputOutput2.bak”, “w”); if (fpInput == NULL || fpOutput == NULL) { printf(“Output File cannot be opened.\n”); return 1; } while ((data = getc(fpInput)) != EOF) { putc(data, fpOutput); } fclose(fpInput); fclose(fpOutput); getchar(); /* to hold the screen */ return 0; }

Page 35: MT258 Computer Programming  and Problem Solving

35

Activity State the syntax and logical errors for the following progra

m for reading a line of lower-case text from the standard input and then store its upper-case equivalent.• #include <stdio.h>• void main()• {• file *fpt;• char c;•

• fpt = fopen("sample.dat", "r");• do• putc(toupper(c = getchar()), *fpt);• while (c != '\n');

• fclose (fpt);• }

Page 36: MT258 Computer Programming  and Problem Solving

36

Activity FILE *fpt;

FILE must be upper case.

fpt = fopen("sample.dat", "w");

use "w" mode for output purpose.

putc(toupper(c = getchar()), fpt);

fpt is a FILE pointer already, no asterisk is required.

Page 37: MT258 Computer Programming  and Problem Solving

37

Common escape sequences

Page 38: MT258 Computer Programming  and Problem Solving

38

Conversion characters for formatted output

Page 39: MT258 Computer Programming  and Problem Solving

39

Examples

#include <stdio.h> #include <math.h> int main(){ double x = sin(15); printf(“|%f|\n”, x); |0.650288| printf(“|%10f|\n”, x); | 0.650288| printf(“|%.10f|\n”, x); |0.6502878402| printf(“|%-10f|\n”, x); |0.650288 | printf(“|%.20f|\n”, x); |0.65028784015711682540| printf(“|%-20f|\n”, x); |0.650288 | printf(“|%20.10f|\n”, x); | 0.6502878402| printf(“|%-20.10f|\n”, x); |0.6502878402 |

Press ‘Enter’ to continue.

printf(“Press ‘Enter’ to continue.\n”); Press ‘Enter’ to continue.

getchar(); }

Page 40: MT258 Computer Programming  and Problem Solving

40

Conversion characters for formatted input