Introduction to Programming with C
Introduction to Programming with C COP 3223
University of Central Florida
Popular in Course
Popular in Computer Programming
This 19 page Class Notes was uploaded by Luisa Beer on Thursday October 22, 2015. The Class Notes belongs to COP 3223 at University of Central Florida taught by Arup Guha in Fall. Since its upload, it has received 27 views. For similar materials see /class/227460/cop-3223-university-of-central-florida in Computer Programming at University of Central Florida.
Reviews for Introduction to Programming with C
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/22/15
Strings in C Basically strings are character arrays in C However that isn39t the complete picture It would be nice if strings didn39t always have to be the same length as character arrays are In order to deal with this issue strings in C by default are null terminated This means that the last character storing a string is the null character 39039 For example the following is a valid way to initialize a string to store quothelloquot char word20 wordO 39h39 wordl 39e39 word2 39l39 word3 39l39 word4 39o39 word5 39039 In this example the character array word is storing a string of length 5 Notice that we actually store six characters here This means that a character array of size 20 can actually store a string with a maximum length of 19 NOT 20 since the last character in the array must be reserved for the null character Another way to read in a string is from the keyboard directly into a character array scanfquotsquot word This reads in all the characters typed in until whitespace is read in and automatically adds the null character to the end of what is read in One consequence of this idea is that the literals 39a39 and quotaquot are different The first is a single character the second is stored in a character array of at least size two where the last character is the null character Example of Processing a String The three following examples turn a string into its uppercase version return the length of a string and reverse the contents of a string void toupperchar word int index 0 while wordindex 39039 wordindex toupperwordindex index int lengthchar word int index0 while wordindex 39039 index return index void reversechar word int index len char temp len lengthword for index0 indexltlen2 index temp wordindex wordindex wordlen l index wordlen l index temp Standard Libary stringh functions There are four C string functions that are used quite commonly and covered in the text This function concatenates the string s2 to the string s1 and stores the result in SI The const in front of s2 indicates that the function will not change the contents of the string s2 char strcatchar sl const char 52 This function compares the two strings s1 and s2 If s1 comes first alphabetically an integer less than 0 is returned If the two strings are equal 0 is returned If s2 comes before s1 instead an integer greater than 0 is returned int strcmpconst char sl const char 52 This contents of s2 are copied into s1 This works DIFFERENTLY than s1 s2 which would just copy a pointer int strcpychar sl const char 52 Returns the number of characters in s before a 39039 is encountered int strlenconst char 5 These functions come in handy with dealing with strings It39s important to follow the speci cation for each function when calling them As mentioned above the const guarantees that the contents of that string won39t be changed by the function Finding the First String alphabetically We know that the student with the first last name alphabetically always gets to go first Here39s a program to determine that student int main char curname30 firstname30 int numstuds i Get number of names printfquotHow many students are therenquot scanfquotdquot ampnumstuds printfquotEnter their last namesnquot for i0 iltnumstuds i scanfquotsquot curname Update the first name seen if iO strcpyfirstname curname Update if we find a new first name else if strcmpcurname firstname lt 0 strcpyfirstname curname printfquotThe first person in line is quot printfquotsnquot firstname return 0 More on String Functions The key to using these String functions and any prewritten functions is to understand exactly what the given functions do so that you can call them with the appropriate parameters in the appropriate manner In the program above we wanted to quotstorequot the name of the earliest name alphabetically we had seen However the statement firstname curname would have been inadequate because it just changes a pointer That39s essentially what a string is Instead the function strcpy does the trick In using it we must make sure we pass in the proper parameters strcpyfirstname curname This copies the value of the string curname into the string firstname which is exactly what we want Furthermore strcmp works in an even less obvious way than strcpy did It returns an integer from comparing two strings Basically it39s similar to checking for lt and gt all at once If the first is the correct relationship between the two strings a negative integer is returned if they are equal 0 is returned and otherwise a positive integer is returned Since we are checking to see if curname comes before firstname the appropriate boolean condition is strcmpcurname firstname lt 0 Palindrome Example The following function returns true if and only if the input parameter is a palindrome This determination is a case sensitive one int palindromechar word int len index index 0 len strlenword while wordindex wordlen l index ampamp index lt len2 index if index len2 return 1 return 0 Arrays of Strings If a string is a onedimensional array an array of strings is really a twodimensional array Here is an example definition char words10020 This allocates 100 arrays of size 20 NOT 20 arrays of size 100 Thus we can store up to 100 strings each of which can be no longer than 19 characters To access a particular string only use one array index strcpywords0quothelloquot Here is an example that should illustrate the different expressions we can use when dealing with an array of strings char words10020 int freq26 i wordcnt let Assume that the array gets filled here for i0 ilt26 i freqi 0 for wordcnt0 wordcntlt100 wordcnt for let0letltstrlenwordswordcntlet if isalphawordswordcntlet freqtolowerwordswordcntlet 39a39 Basically we keep a frequency count of all alphabetic characters in the 100 strings in the array Arrays of Strings as Parameters Consider turning the segment of code above into a function We would want to pass in the two dimensional array as a parameter Also to make this a little easier we would want to pass in the zeroed frequency array in as a parameter as well One piece of information we DO have to specify in the function definition and prototype is the size of the second dimension void calcfreqchar words20 int freq int len int wordcnt let for wordcnt0 wordcntlt100 wordcnt for let0letltstrlenwordswordcntlet if isalphawordswordcntlet freqtolowerwordswordcntlet 39a39 And here is how the function would be called calcfreqwords freq 100 Fall 2005 Student Evaluations COP 3223 Great Class very challenging took me from absolutely no knowledge of programming to a very acceptable level didn t like using puttyexe tests were too difficult this is supposed to be an intro class also sometimes he would tell us to studyreview certain things for the test but they weren39t on the test presented the information well liked working in groups couldn39t putty from home a few homework assignments were ambiguously worded and made more difficult than necessary no real problems with this course maybe it was a bit easy liked trying to write small programs in class like professors analogies and way of making complicated topics easy to understand some programs were really complicated goes out of the way to answer questions in lecture class time was well used examples online were help ll I struggled in this class mostly because I fell behind and wasn39t able to catch up it seemed like the class moved too fast for me I believe programs should be due before exams on the same material I think the professor teaches the class as if everyone has done programming before didn t like putty written tests were difficult because I couldn39t change my code liked class notes online some assignments and tests were difficult the tests were made to seem easier than they were you should present some of the practice problems and solutions in class programming assignments should hold more weight on the overall grade tests seemed oriented to someone who had programmed before don t give tracing questions on tests that are linked together the book could have been better the programming assignments were done very well I missed a pop quiz day and it changed my grade but the syllabus said there were no quizzes tests are very tricky the teacher is very down to earth lacking descriptiveness in program comments maintained a cheery atmosphere the text reading becomes difficult when there s some discrepancy between class activity and the syllabus schedule size of the class was ridiculously large i like the programming assignments but the standard deviation thing struck me as ridiculous assignments took forever to be graded tests were a bit difficult to finish in the allotted time would have been nice to know what I was marked off for slower pace less tangents during lecture class moves too slowly better explanations for deductions on programs mc questions are really hard sometimes sometimes the programming assignments are too complex and introduce several concepts at once standards favored students with experience liked actually running programs in class to demonstrate hard first test textbook was difficult more but smaller programs don t test on arrays before the assignment is due more instructor feedback can t see how C is an important language to learn I would like more simple examples of the harder concepts tests were too long didn t like test questions with pass by val vs pass by ref tough tests not enough easier assignments to balance the difficult ones didn t like E option on MC tests second test was too long compared to first assignments more complex than what was taught class would be better taught in a lab didn t like test Ithought I understood stuff and then my bubble burst we don t use the textbook often or refer to it should give a more detailed rubric for grading assignments pace was too fast it wasn39t clear what we were supposed to use in a program programming assignments are long and tricky liked the many examples split some of the programming assignments into smaller ones didn t like how example programs in class seemed so simple and then assignments were much more complex I liked how helpful my teacher was The TA comments on assignments weren39t very helpful more quizzes would keep students on track class is too fast not enough time going over specifics of examples presented too mechanically I don t agree with the test method hard to write three or four programs in a half hour focus more on going over examples in class and less on analogies tests can be very tricky pace of the second half of the course is too fast didn t like full class programming sessions want easier tests with no curve make class slower Still some kids think that the tests and assignments are too hard tricky or too long Didn t like using putty A few homework assignments were ambiguously worded Deviated from the syllabus Slower pace Didn39t use the book much and didn39t update changes in reading schedule Assign more smaller homework assignments Make a clear grading rubric available beforehand My responses This is a challenging class Students need to understand that from the beginning but that it is designed for a beginner But for different beginners different amount of preparation times may be necessary Putty will still be provided but isn 39t required Should learn jGRASP well so I can fix it on anyone39s computer In the real world assignments are not always given in a crystal clear fashion If there are ambiguities in an assignment you should first ask for a clarification If that doesn39t help use your best judgment This sort of skill can not be cultivated if you never practice on an ambiguously worded assignment My goal is to impart a set of ideas If I feel that I am not doing a good job of doing so with the planned syllabus I need to be able to make changes to be more effective The reason I gave that reading quiz was feedback from T As who said that students were having difficulty looking up facts in the text This is a skill I feel is very very important I thought that I could encourage that skill by telling the class there would be a reading quiz the following class period that would count as part of a homework grade Maybe the class seems fastpaced but this is the standard amount of material covered in a course like this all over the nation at 4 year universities Actually in many intro courses more is covered Computer Science is not an easy major Later courses in the major require much much more work and move much more quickly Perhaps the web page should be updated but I want students to learn how to read a book Books have table of contents and indexes Some students need practice learning how to find things in a book and I want to give them that opportunity Sometimes college students want to be spoonfed like they were in high school but the goal of college is to learn how to feed yourself how to learn on your own This is one way in which a student ought to be an active learner Pay attention in lecture then use your common sense to determine the useful information in the text Then as an active learner it39s your job to synthesize that information with what was taught in class I very intentionally teach differently than what39s in the book I want to give students the opportunity to be active learners who synthesize information on their own If I just presented the material in the book as it is in the book students would never make their own connections and would just have a view of the material consistent with the text The practice programs are smaller programs that students can work on if they need more practice In real life programs are long and require the synthesis of multiple ideas I can 39t give a large application as a program but I try to find reasonable tasks that require the type of thinking that a computer programmer uses in their daily jobs COP 3530 Arup is an excellent instructor I prefer working without a partner tests were hard ego damage I learned too many lab assignments Arup is an awesome teacher he knows what he39s talking about and gets his ideas across clearly tests required too much curving unprepared for the rst test It39ll be interesting to see how to adapt this course to CS2 I would like to continue the labs but it39s just not practical to do so without the paltnering idea with respect to grading I am concerned about getting across the relevance of the math as well as students dealing with the dif culty COT 4810 I liked the freedom to reconstruct book topics didn t like that it was harder than section 1 the student evaluations did not include all the graded criteria more frequent updates on how to improve in between presentations liked learning about different topics and doing the paper at the end didn t like talking in front of people I need to nd ways to for students to be more enthusiastic about this course and to show up I also need to stay awake and give students frequent updates and feedback File InputOutput Up to this point you have been testing your programs by entering input from the keyboard Although this works fine for small sets of input this would be very time consuming for processing large amounts of data Furthermore large amounts of data often already exist in text files It would certainly be wasteful to type these data in by hand while running a program when they are already available in a file As you might imagine C provides the ability to read from files AND write to les In fact when we read information from the keyboard and wrote information to the screen we primarily used the functions printf scanf Similarly for reading from files and writing to les we39ll use the functions fprintf fscanf The rst f in each of these function calls stands for quot lequot Here is the specification for each function fprintffilgdptr ctrlstr othearguments fscanffilgdptr ctrlstr otherarguments You39ll notice that these are identical to printf and scanf EXCEPT for the first parameter How to Create a File Pointer In order to read from a le or write to a file you MUST use a pointer to that le Here is a declaration of a file pointer FILE ifp In order to properly quotinitializequot an file pointer it must be set to point to a file In order to do this we must specify the following 1 Name of the file 2 Mode quotrquot for read or quotwquot for write There is a function call that uses this information to open the appropriate le and return a pointer to it It39s name is fopen Here is an example of its use ifp fopenquotinputtxtquot quotrquot You39ll notice that the first parameter to the fopen function is a string storing the name of the file to be opened The second parameter is also a string For our purposes this string will either be quotrquot or quotwquot There are other possibilities for this second parameter but we won39t deal with them in this class When we open a file in quotrquot reading mode the file should already exist and the fopen function returns a pointer to the beginning of that le If the le doesn39t exist fopen returns NULL How to Read from an Input File This works nearly the same as reading from the keyboard In fact imagine pretyping all of your responses you would type in the keyboard into a file and then running a program that read from that le instead of the keyboard In that situation the new program would work identically Every time you use the fscanf function to read in a piece of information from a file the le pointer reads in the next token returns it and advances to the following token Here is an example of how to read in an integer from the le we previously opened fscanfifp quotdquot ampnum The rst parameter tells the computer to look to where ifp is pointing instead of the keyboard The rest works the same Imagine that the file we just opened quotinputtxtquot contains several integers separated by white space with the end of the data being signi ed by a 0 Here is how we would read in and sum all the numbers from the file FILE ifp int num 1 sum 0 ifp fopenquotinputtxtquot quotrquot while num 0 fscanfifp quotdquot ampnum sum num fcloseifp Closing a le You39ll notice that the last line above uses a new function call fclose All les that are opened must also be closed In order to close a file you must simply pass the file pointer to the file you want to close into the fclose function Forgetting to close a le may corrupt the contents of that file Here is a complete program that reads in a le containing numbers and outputs their sum to the screen include stdioh int main FILE ifp int num 1 sum 0 ifp fopenquotinputtxtquot quotrquot while num 0 fscanfifp quotdquot ampnum sum num fcloseifp printfquotThe sum is dnquot sum return 0 Example Writing to a File Imagine that you wanted to write some output to a file Consider editing the program we looked at a couple lectures ago that counted up the frequencies of each alphabetic character in a file and printed out a chart to the screen so that it wrote the chart into a le Here are the changes we would make to the main function and the printchart function int main int freq26 FILE ofp initfreq readinputfreq ofp fopenquotcharfreqtxtquot quotwquot printchartfreq ofp fcloseofp return 0 void printchartint freq FILE ofp int index fprintfofpquotLettertFrequencynquot for index 0 indexlt26 index fprintfofpquotctdnquotchar39a39index freqindex1 Secret Code Message Example One of the types of codes employed to hide the meaning of a message many many years ago involved substituting the first letter in the alphabet for the last the second letter for the second to last etc Essentially the following chart shows a list of substitutions ILetterA B C ID IE IF IG H I J K L M ICode Z IY X IWIV IU T s IR IQ IP 0 IN Now imagine writing a program that took in a plain English file and outputted a file containing only the letters in the previous le in code according to the code above Here are the steps we39d have to go through 1 Open both files 2 Read from the input file character by character 3 For each character if it is alphabetic determine it39s corresponding code letter and output that to the output file To make the output file a bit neater we will place a newline after 60 characters have been written to a line In this example the functions fgetc and fputc will be used Here are the prototypes for both Gets the next character from the file pointed to by fp and returns it int fgetcFILE fp Writes 0 to the file pointed to by fp int fputcint c FILE fp include ltstdiohgt int main FILE ifp ofp int cnt 0 c codechar Open both the input and output files ifp fopenquotfruitcquotquotrquot ofp fopenquotfruitcodetxtquot quotwquot Continue reading in characters till the end of the input file while c fgetcifp EOF Only process alphabetic characters if isalphac write out the encoded character to the output file codechar 39Z39 toupperc 39A39 fputccodechar ofp Add a newline character if 60 characters have been written to a line cnt if cnt60 0 fputc39n39 Ofp fcloseifp Close both files fcloseofp Questions to Think About 1 How does the encoding work in the line that assigns codechar 2 How does the adding of the new line work 3 How can we adapt this program to include all non alphabetic characters unchanged and not change the case of all the alphabetic characters 4 If we did 3 could we decode the file exactly