1 Data Structures and Algorithms Programs. Different problems. Operations. Size of data. Resources available.

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

I/O means Input and Output. One way: use standard input and standard output. To read in data, use scanf() (or a few other functions) To write out data,
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
1 CSE1303 Part A Data Structures and Algorithms Semester 2, 2006 Lecture A1 – Welcome & Revision.
1 Introduction to Computing: Lecture 16 Character Strings Dr. Bekir KARLIK Yasar University Department of Computer Engineering
1 Introduction to Computing Lecture 11 Character Strings Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
1 Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A1 – Welcome & Revision.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
1 CSE1301 Computer Programming: Lecture 21 File I/O.
1 CSE1301 Computer Programming: Lecture 9 Input/Output.
1 CSE1301 Computer Programming: Lecture 19 Character Strings.
CSE1301 Computer Programming: Lecture 19 File I/O
Files Programs and data are stored on disk in structures called files Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
1 CSE1301 Computer Programming: Lecture 19 File I/O.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Adv. UNIX:io/91 Advanced UNIX v Objectives of these slides: –look in some detail at standard input and output in C Special Topics in Comp.
Chapter 18 I/O in C.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
File IO and command line input CSE 2451 Rong Shi.
CSE1301 Computer Programming: Lecture 14 I/O and Files.
ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Kymberly Fergusson WELCOME CSE1303 Part A Data Structures and Algorithms Summer 2002.
Lecturer: Omid Jafarinezhad Sharif University of Technology Department of Computer Engineering 1 Fundamental of Programming (C) Lecture 6 Array and String.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
CECS 130 EXAM 1.  int main() { printf (“%c %c \n", 'a', 65); printf ("%d %ld\n", 1977, L); printf (" %10d \n", 1977); printf ("%010d \n", 1977);
Lecture 11: Files & Arrays B Burlingame 18 November 2015.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Arrays and Strings Lecture 30. Summary of Previous Lecture In the previous lecture we have covered  Functions Prototypes Variable Scope  Pointers Introduction.
CSE1301 Computer Programming: Lecture 6 Input/Output.
CS 261 – Recitation 7 Spring 2015 Oregon State University School of Electrical Engineering and Computer Science.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
Characters and Strings
CS 1704 Introduction to Data Structures and Software Engineering.
Files A collection of related data treated as a unit. Two types Text
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr.
Computer Science 210 Computer Organization
Chapter 7 Text Input/Output Objectives
Chapter 18 I/O in C.
File Input/Output.
Computer Programming Lecture 15 Text File I/O
Programming in C Input / Output.
Input and Output Lecture 4.
Computer Science 210 Computer Organization
Programming in C Input / Output.
CSI 121 Structured Programming Language Lecture 7: Input/Output
Lecture 8b: Strings BJ Furman 15OCT2012.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
CSI 121 Structured Programming Language Lecture 21 Character Strings
File Input and Output.
Programming in C Input / Output.
Files Chapter 8.
Chapter 18 I/O in C.
Presentation transcript:

1 Data Structures and Algorithms Programs. Different problems. Operations. Size of data. Resources available.

2 Overview Basic data structures. How to manipulate them. How to implement them. Other algorithms and how to implement them.

3 Revision - This lecture Basic C data types Boolean 1D and multidimensional arrays Strings Input/Output File I/O Structures and typedef

4 Review - Basic Data types in C int char float double

5 Review - int vs float Integer division in C rounds down: 4/5 = 0 float is a "communicable" type: 4.0/ = = 1.8

6 Review - char Characters are stored as a small integer Each character has a unique integer specified in an ASCII table. –( ASCII values range from –0 is the value for the special character '\0' –127 is the value for –Other special characters: \n \t \ \\ etc There are other extended character sets (extending from )

7 Review - Type Modifiers long –Allows for large numbers to be stored. long int num; - double is a long float short –Stores smaller numbers, taking less space short int x; const –Makes a variable constant (not able to be changed). const int p; –Must be initialised at declaration

8 Review - Boolean Has two values, true and false. In C we use integers as Booleans. Zero represents false. Any non-zero integer represents true. In Borland programs, use #define to define the constants true and false

#include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } Review - Boolean 9

#define true 1 #define false 0 #define bool int bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } For Borland use #define or const int Review - Boolean 10

11 Review - Variables Is a logical name or identifier for a piece of memory for storing values. Has a type associated with it. Must be declared before being used: int x float sum; May be initialised at declaration: char choice = 'a'; Identifiers may contain letters, digits and underscores, but may not start with a digit.

12 Review - Variables Variables can be local or global Global variable declarations are made at the start of the file after any #define and #include –Global variables are available to be used anywhere throughout the program. Local variable declarations are made at the start of a function. –Local variables are only able to be used inside the function where they are declared.

Global variable Local variable Review - Variables 13 #include #define MAXSTRING 100 char name[MAXSTRING]; int main() { bool flag = true; while (flag != false) { if (scanf("%s", name) == 1) printf("Hello %s", name); else flag = false; }

#include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } File inclusion header Review - Functions 14

#include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } Function definition Review - Functions 15

Function name #include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } Review - Functions 16

Must be compatible with the function’s return type Function return type #include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return true; } Review - Functions 17

#include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } Parameter type Function parameter Review - Functions 18

int main() { int year, month, day; printf(“Enter year, month and day: ”); scanf(“%d %d %d”, &year, &month, &day); day = dayOfYear(year, month, day); printf(“\nDay of Year = %d\n”, day); } Function call Review - Functions 19

20 Review - Arrays (1D) All the elements are always of the same type. An element: array1D[index] In C, the first element has index 0 (zero). array1D: 01N - 1

21 Review - Multidimensional Arrays Arrays of arrays. All the elements are always of the same type. An element: array2D[row][column] array2D:

2-dimensional array of int int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; int dayOfYear(int year, int month, int day) { int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; } Review - Multidimensional Arrays 22

Index goes from 0 to 12 int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; int dayOfYear(int year, int month, int day) { int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; } Review - Multidimensional Arrays 23

24 Input/Output is done via streams Uses the library stdio.h Streams that are available in the library are stdin (keyboard), stdout and stderr (screen). These can be redirected. Data is written to stdout using the printf() function. printf("%s\n%f\n%c\n%d\n", name, age, gender, idNumber); Data is read in from stdin using the scanf() function. scanf("%s %f %c %d", name, &age, &gender, &idNumber); Format control string Review – Input/Output Conversion specifiers Pointers to variables where input will be stored Variables containing data to be printed 24

25 scanf() returns the number of values successfully read and converted or returns a special value EOF when input ends. Note for when reading a single character ( %c ): if there is a \n character left in the buffer from reading another value ( %d ) then that \n will be read into your character variable. Conversion specifiers: i or d : display a signed decimal integer f : display a floating point value e or E : display a floating point value in exponential notation g or G : display a floating point value in either f form or e form l : placed before any float conversion specifier to indicate that a long double is displayed Review – Input/Output

#include int main() { int day; int month; int year; char name[30]; printf(“Enter your name:\n”> scanf(“%s”, name); /* skipping spaces */ printf(“Hi %s. Enter birthdate as: dd mm yyyy\n”, name); scanf("%d %d %d", &day, &month, &year); /* alternative */ printf(“Hi %s. Enter birthdate as: dd-mm-yyyy\n”, name); scanf("%d-%d-%d", &day, &month, &year); return 0; } Note: no ampersand for strings Conversion specifier Literal characters 26

27 Strings : array of characters + ‘ \0 ’ Example: char name[30]; Unlike other arrays, strings must have an end-of-string character : ‘\0’ String functions you will use from the string.h library include: Length - strlen(string1) Assignment - strcpy(dest, source) Concatenation - strcat(dest, string2) Comparison - strcmp(string1, string2) Max length including ‘\0’ Copies string2 onto the end of the destination string Returns: positive if string1 sorts after string2, 0 if they are the same string negative if string1 sorts before string2 Review - Strings

28 An array of characters compared to a string: The length of the string as returned by strlen(), is 1 element shorter than the array – it does not count the ‘ \0 ’ (end of string character) Review - Strings CATS CAT\0

#include #define MAXLENGTH 100 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, “Hello World!”); strcpy(string2, string1); length = strlen(string1); printf(“length of string1 = %d\n”, length); strcpy(string1, “Apple”); strcpy(string2, “Orange”); string2 needs to be the same length as string 1 string1 needs to fit the number of characters of the second string, +1 for the ‘\0’ character 29

if (strcmp(string1, string2) < 0) { printf(“%s %s\n”, string1, string2); } else if (strcmp(string1, string2) == 0) { printf(“The strings are the same.\n”); } else { printf(“%s %s\n”, string2, string1); } strcat(string1, “ juice”); printf(“%s\n”, string1); return 0; } Prints the order which the two strings sort, alphabetically. Note: To scan within a string use: sscanf(string1, “%d”, int1); 30

31 Review -File Handling in C File Input/Output is also done via streams Files need to be opened before use. –Associate a "file handler" to each file –Modes: read, write, or append File input/output functions use the file handler (not the filename). Some examples of file handlers you know: stdin, stdout, stderr

32 Review -File Handling in C Need to check the file opened sucessfully. Need to close the file after use. Basic file handling functions: fopen(), fclose() File I/O functions: fscanf(), fprintf(), fgets().

#include #define MAXLEN 100 int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; char name[MAXLEN]; int count; float mark; inputfile = fopen(“Names.txt”, “r”); outputfile = fopen(“marks.dat”, “w”); if (inputfile == NULL) { printf(“Unable to open input file.\n”); return 1; } if (outputfile == NULL) { printf(“Unable to open output file.\n”); return 1; } Mode r : read w : write a : append Associate a file handler for every file to be used. fopen() returns NULL if an error occurs 33

count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; printf("Enter mark for %s: \n", name); scanf("%f", &mark); if ( fprintf(outputfile, "%s %f\n", name, mark) <= 0 ) { printf("Error writing to output file.\n"); return 1; } printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outputfile); return 0; } fprintf() returns the number of successfully written or negative if an error occurs 34 fscanf() returns the number of values read and converted

#include #define MAXLEN 100 int main() { FILE *inputfile = NULL; char line[MAXLEN]; int count = 0; inputfile = fopen(“Names.txt”, “r”); if (inputfile == NULL) { printf(“Unable to open input file.\n”); return 1; } while(fgets(line, MAXLEN, inputfile) != NULL) { count++; } printf(“Number of lines: %d”, count); fclose(inputfile); return 0; } To read in a line, use fgets(). fgets() returns NULL if end of file is reached. fgets(string, length, filehandle) What would happen if you tried to count the number of lines again, once the end of the file has been reached? 35

36 Review - struct Members may have different types. structname.membername structs are also known as “records,” and members as “fields” structname:

37 Review - typedef Gives a new name to a type that has already been defined. E.g. typedef struct StudentRec Student; Saves typing struct StudentRec everywhere. Or you can use it: typedef struct { int ID; float mark; } Student;

Recall: Macro substitution #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; 38

#include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; Recall: Structure declaration 39

Structure name / tag Members Don’t forget this! Recall: #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; 40

Recall: Data type New type name #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; 41

Recall: An instance of the struct A member of a struct instance“Package” Type Student readStudent(void) { Student next; scanf(“%s %d”, next.name, &next.mark); return next; } void printStudent(Student student) { printf(“%s %d\n”, student.name, student.mark); } 42

Recall: Array of instances of structs Assignment Member of an array element #define MAXCLASS 100 main() { Student class[MAXCLASS]; int n, i, best = 0; printf(“Enter number of students: ”); scanf(“%d”, &n); for (i = 0; i < n; i++) { class[i] = readStudent(); if (class[best].mark < class[i].mark) { best = i; } printf(“Best student is: ”); printStudent(class[best]); } 43

44Preparation Next lecture: Pointers