1
MT258
Computer Programming and
Problem Solving
Unit 5
2
UNIT FiveAbstract data and hidden code
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.
4
Records for typedef
Example :• typedef
• struct
• {
• int month;
• int day;
• int year;
• }
• date_t;
• date_t datestart;
• date_t dateend;
5
Records for typedef
Example :• typedef struct Rational_type {
• int numerator, denominator;} RATIONAL;
• RATIONAL temp;
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; }
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(); }
8
Abstract data type (ADT)
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
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.
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
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
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
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.
15
Two-dimensional array of characters
Example
char catNames[5][10]=
{“ severe”, “very high”, ” high”,” medium”, ”low”};
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.
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.
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
19
Strings.h
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.
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. “;
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.
23
Data hierarchy
bit 0 byte 01000001 (ASCII character of ‘A’) 28 = 256 (possible values) field record file database
24
Data Streams
Standard input stream• int getchar(void);
Standard out stream• int putchar(int c);
Standard error stream
25
Buffering
Keyboard Buffer Programstandard
input
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.
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.
28
File pointer variable
Declare file pointer variables.• FILE* infile;• FILE* outfile;
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
30
Establishing a data file
File* output; if ( (outfile = fopen(“a:\sample.dat”. “w”) = = NULL) { printf(“Output File cannot be opened.\n”); return 1; }
31
Common I/O functions concerning characters
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);
33
Closing a file
fclose(infile); fclose(output);
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; }
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);• }
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.
37
Common escape sequences
38
Conversion characters for formatted output
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(); }
40
Conversion characters for formatted input