Intro to Computer Programming
Intro to Computer Programming CSCI 105
Popular in Course
Popular in ComputerScienence
This 10 page Class Notes was uploaded by Trey Daniel on Tuesday October 13, 2015. The Class Notes belongs to CSCI 105 at Lake Superior State University taught by Mark Terwilliger in Fall. Since its upload, it has received 23 views. For similar materials see /class/222331/csci-105-lake-superior-state-university in ComputerScienence at Lake Superior State University.
Reviews for Intro to Computer Programming
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/13/15
1 2 Introduction to Computer Programming Using C What Is Computer Programming A computer in its simplest form is nothing more than a collection of silicon plastic metal glass and wire When you turn it on it does precisely what it39s been instructed to do nothing more and nothing less That s where programming comes in A pmglam is a set of instructions that tell the computer what it39s supposed to do pmglamming is the process of preparing these instructions Because computers interpret their programs very literally programmers need to be quite explicit in the directions that they prepare The Origins of Programming Since the first computers were developed in the 1940 s the discipline of computer programming has undergone a continuous evolution In those days computers were often programmed by means of large patch panels using wires to represent individual instructions Early on though it was recognized that exibility would be increased if computer programs could instead be encoded as numeric data and stored in the computer39s memory While an improvement over patch panels these machine language programs were still difficult to work with Even then most computers used binary numbers and the machine language programs were nothing more than strings of zeros and ones To streamline the programmer s job special assembly languages were developed Rather than having to remember for example that the binary pattern 00101010 is the instruction that tells the computer to add two values while the pattern 00101011 stands for subtract the assembly language programmer uses special mnemonic names such as ADD or SUB In addition assembly languages introduced the concept of using labels to stand for addresses within the computer39s memory Thus the instruction ADD AB might be used to tell the computer to add the values in memory locations 123 and 147 rather than the binary form 00101010 01111011 10010011 Of course the computer didn39t and still doesn t understand assembly language directly Instead special programs called assembleIs were and are used to translate assembly language to its binary equivalent Although assembly language programming is still an option with computer systems it s used only sparingly primarily for performing very lowlevel tasks where direct communication with the computer s hardware is required Most programming is instead done using more sophisticated languages This is because assembly language is still quite difficult to work with requiring even the simplest tasks to be broken down into sequences of several or even several hundred instructions Also virtually every computer system has its own unique assembly language To Chapter 1 Foundations 1 3 run an existing assembly language program on a new computer system requires translation of the program into the new system s assembly language often a formidable task The Development of HighLevel Languages III39gII Ievel machine independent programming languages were first introduced in the 1950 s Whereas each instruction in an assembly language represents a single machine language instruction a single highlevel language instruction will usually translate into several machine language instructions This implies of course that highlevel languages are far more expressive than assembly languages It also implies that the translation process required to convert programs written in these languages into a form that the computer can process is far more complex Actually there are two strategies for translating highlevel languages The first called compiling translates programs fully into machine language Once translated the compiled program can be run at any time without any additional translation required In contrast other languages are intelple ve When a program written in an interpretive language is run an interpreter program reads one instruction at a time and determines how to carry out the required action To better understand the difference between compiling and interpreting imagine that you have an article written in a foreign language You could hire someone to translate the article to English and give you a written copy of this translation This is what a compilerdoes Alternatively you could hire someone to read the article aloud translating it to English as they read This is what an intelpleterdoes Notice the important difference between these two approaches When the article is quotcompiledquot for you you can refer back to the translated version at any time the quotinterpretedquot version however is not retained and you d need to seek out your interpreter again if you wanted to review the article s contents In recent years it s become increasingly common for programming language implementations to adopt a hybrid translation model Rather than compile a program completely to machine language these hybridmodel compilers translate into a generic machine language which is then interpreted on the host computer Early on this strategy was adopted to simplify the translation process on small computers with very limited resources since full translation can be quite complex and placed a heavy burden on these machines As even the smallest computers acquired larger memories and faster processors this practice became less attractive Recently though the widespread use of the Internet has led to a newfound interest in the use of this model By translating web applications into a generic intermediate form it s possible to run a single application on a variety of different hardware environments without having to recompile the application for each target environment instead each hardware environment has its own interpreter that can be used to run the program on that platform Java was probably the earliest widely used language that adopted this model to support downloadable software applications This same model is used in C as well 1 4 Introduction to Computer Programming Using C Similarities and Differences in HighLevel Languages While the earliest highlevel languages were primitive by today s standards many of the most common concepts originated in these early languages For example to nd the average of three numbers in FORTRAN which was developed in 1954 you might use the instruction AVG X Y Z 3 In Pascal introduced in 1971 the equivalent instruction is Avg XYZ3 while in C introduced in 1980 you might write avgxyz3 Although these three forms are nearly identical there are some important differences When FORTRAN was developed most computers worked with capital letters only Also FORTRAN statements were originally entered into the computer by way of punched cards using a rigid layout On each card the rst ve positions were only used to hold numeric labels the actual instructions were entered in card columns 7 through 72 If an instruction was too long to t on a single line it could extend to an additional card provided a character was punched in column 6 of the continuation card Pascal and C programs in contrast allow both upper and lower case letters and are usually entered directly into the computer With no rigid punched card layout to constrain the programmer it was necessary to add some mechanism to mark the end of a statement That s the purpose of the semicolon In Pascal a semicolon is a statement separator and is placed between two consecutive instructions In C however the semicolon is used as a statement terminator and is placed at the end of each instruction The difference is very subtle and usually inconsequential but there are a few places where a semicolon must be used in C but must be omitted in Pascal Needless to say this can be quite confusing Almost all modern programming languages use the basic form of the assignment instruction that was introduced in FORTRAN In general the item on the left indicates where a value is to be placed while the expression on the right tells what value is to be stored Thus all three of the instructions above tell the computer to add three numbers divide the sum by 3 and store the result in the location whose name appears on the left Perhaps you wonder why Fortran and C use the symbol in the assignment while Pascal instead uses In all three languages distinct symbols are used to distinguish between assignment and comparison In Fortran is used for assignment while EQ is used to compare for equality In Pascal means assign while is used for equality comparison In C again means assign while means compare Just to add to the confusion BASIC uses the symbol for both assignment and comparison The computer needs to gure out from the context of the usage which interpretation is desired Chapter 1 Foundations 1 5 One area where there39s been a great deal of variation between programming languages is in the mechanisms for transferring data between the computer and the outside world In FORTRAN the value of AVG could be displayed with 1 digit after the decimal place using the instructions WRITE 61AVG 1 FORMAT F51 In the WRITE instruction the number 6 is a reference to unit 6 which is presumably associated with some output device The value 1 tells the computer to use the FORMAT statement with the label 1 to specify the appearance of the result In this instance the computer is told to display the value with 5 total character positions including the decimal point and 1 digit after the decimal point In Pascal the same instruction would be Writeln Avg51 while in C it would be cout ltlt setw5 ltlt setprecision1 ltlt avg ltlt endl HighLevel Language Evolution One topic that often confuses beginning programmers is the wide variety of programming languages that are available While we ve looked brie y at some of the similarities and differences between different languages we haven t really addressed the reasons for the existence of so many languages When computers were first introduced they were primarily used to solve complex mathematical problems Consequently the earliest focus re ected in FORTRAN the first widely used programming language was the efficient expression of these problems Soon however business clients began to use computers more for their ability to organize and manage data and languages such as COBOL which features strong data organizational capabilities were introduced Although a number of other languages were also developed these two languages along with a variety of assembly languages dialects dominated the programming landscape through the 1960 s and early 197039s During the late 196039s and early 197039s computer scientists began to seriously debate the relative strengths and weaknesses of existing programming languages Since the structures of most programming languages are strictly controlled by standardization bodies it was easier for researchers to develop new languages to try out alternative approaches to remedying the perceived weaknesses As a rule the innovations in these languages focused on two major areas of language design conaol sanctums and data shuctules 1 6 Introduction to Computer Programming Using C A control structure is a programming construct that controls the execution of subsequent programming instructions Typically control structures are classi ed as either selection structures which allow the computer to perform one of several alternative actions or repetition structures which allow the computer to perform some action repeatedly FORTRAN s control structures were quite weak perhaps because as was mentioned before the primary emphasis in FORTRAN was on solving mathematical problems In fact FORTRAN s control structures weren39t much different from those available in assembly language While COBOL s control structures were somewhat better the business orientation of the language kept it from having much in uence on scientific areas of programming A data structure on the other hand is a collection of related data items along with an appropriate set of operators for manipulating those items Again FORTRAN has very little facility for managing data structures It recognizes basic numeric data items both with and without fractional parts and in some cases also provides support for complex numbers The only level of organization available beyond isolated instances of these items is the array or table COBOL is stronger in this area due to the greater need to organize related data items to support business applications Still there is no facility for defining generalized data structures nor is there any way to bind a set of operations to an associated structure By the end of the 1970 s most educators had come to the conclusion that a better language for teaching new programmers was needed and the most popular choice was Pascal Pascal was designed specifically for teaching and provides a strong set of control structures a reasonable level of data structure support for the time and perhaps most importantly a small and relatively simple instruction set Because of its teaching orientation Pascal lacks some of the facilities needed for acceptance by professional programmers Consequently there was a fairly steady migration in the 1980 s towards another language C Although somewhat similar in structure to Pascal C has a number of the facilities that were perceived as necessary for widespread commercial use Like Pascal though C lacks the facility for connecting a data structure with its associated operators As the 198039s progressed another minirevolution struck the programming community This was the trend towards objectoriented programming Stripped of the associated hype object oriented programming is really little more than the incorporation of associated operators into a data structure Perhaps the most widely used languages today that fit this objectoriented model are C and Java C which borrows heavily from both Java and C is also an objectoriented programming language In both Pascal and C it39s possible for a programmer to define a new data type such as a matrix In C it s not only possible to define a matrix it s also possible to extend the basic arithmetic operators like and to work with a matrix Thus it s possible to extend the language in a natural way customizing it to support the needs of a particular organization or application Chapter 1 Foundations 1 7 The Impact of the Desktop Computer As was previously mentioned early computers used punched cards as their primary input medium Not only were computer programs keyed onto punched cards the data upon which those programs operated were also supplied to the computer by way of punched cards This in turn greatly in uenced the way in which computer programs were designed Most programs for processing punched cards followed the same logical structure as outlined below Initialize any required data items While there are punched cards remaining repeat these steps Read the next punched card Process the new input data Generate output information for this card s data Perform any required quotend of runquot processing Of course there were an endless number of variations on this model but most programs followed this basic ow of control As alternate forms of data entry such as online terminals became available most programmers adopted this same style of program logic to the new medium With the advent of the personal computer though users began to demand more control over the operation of the computer Simple command languages and menu systems initially developed for use with online terminals migrated to these desktop units When Apple introduced the Macintosh computer with its graphical user interface the face of programming changed dramatically At first programmers adopted the command and menudriven paradigms as simple variations on the old punchedcard processing logic Initialize any required data items While there are more commands to process repeat these steps Get the next command from the user Figure out what needs to be done to fulfill the request Carry out the user s request Perform any required quotend of runquot processing The mousedriven interface doesn39t naturally fit this programming style however Instead a new event Iliven model had to be developed Within this model the programmer lays out a screen interface with a variety of controls scattered about the screen When the mouse is positioned over one of these controls events such as mouse movement mouse clicks and keystroke entries are automatically associated with the control Underlying systemsupport software is responsible for sending notifications of these events to the various modules known as event 112111111915 Programming in large part focuses on the design and implementation of these event handlers 62 Introduction to Computer Programming Using C A Note on Good Programming Practices While the analogy is far from perfect the development of a computer program can be likened to a construction project In terms of planning and style our projects so far haven t been all that different from a child s tree fort We ve settled for guring out how to get the job done without worrying too much about some of the consequences In contrast developing a larger programming project is more like building a house Detailed blueprints need to be created and examined by inspectors to ensure that the structure will be safe and built to accepted standards Only then can the contractor proceed to the groundbreaking Once construction begins care must be taken to coordinate the various phases to ensure that everything comes together correctly Even then problems can arise In fact it s almost a sure bet that some tasks will con ict It s common to hear about plumbers boring holes through wiring or electricians drilling through plumbing as they try to complete their jobs As the projects get larger the need for careful planning and coordination becomes more critical Following his graduation my brother went to work for an engineering company in Minneapolis Minnesota One of his assignments was to develop plans for the installation of heating ventilation and air conditioning ducts in the Mall of America One day he con dedto me that one of the smaller stores in the mall wasn t going to have any heating ducts after all because the only way to reach the store would be to bore through one of the major support beams and that simply wasn t going to be done When developing a large application programmers must spend a great deal of time planning The actual development shouldn t begin in earnest until a clear picture of the solution has been produced Even then programmers should be prepared to deal with unanticipated problems Probably the best way to do so is to follow good programming practices This includes simple strategies like using wellchosen variable names It also includes following accepted design and implementation strategies that are far beyond the scope of this course In this chapter we ll look at a common component of applications that are developed for graphical environments the dialog box and see how to design dialog boxes that t cleanly into the nished program Subprograms In chapter 3 the use of named constants was brie y discussed As you will recall when you use a named constant such as PI you can use that name in place of the corresponding constant value 314159265 Named constants provide two major bene ts they make the programmer s job easier and also make the resulting program easier to understand In a similar way subprograms provide a mechanism for giving a name to a set of program instructions This allows the programmer to refer to the set of instructions bythat single name rather than having to replicate the corresponding instructions To use a humanoriented analogy this is like letting the programmer say quotOpen the doorquot instead of having to explicitly list all of the steps required to open the door put your hand on the door knob turn the knob until it releases the latch Chapter 6 Subprograms and Dialog Boxes 63 and then pull or push the door Further by using customizing data in the form of parameters you can have a generic set of instructions for opening a door that can be customized at will to open rst the living room door then the closet door and then the bedroom door The function is used in C to provide subprogram support We already saw how several arithmetic operations are included in the math library For example the square root of a number can be computed by the standard builtin function MathSqrt Similarly the various event handlers you39ve been using in C programs are in fact function subprograms as are many other operations such as Close F0cus C0nvertT01nt32 C0nve1tTOD0uble and StringF0rmat If you think about the usage of these various functions you may realize that they can be separated into two basic types functions that compute a result like the square root function and functions that perform some task like the close and clear functions In C the distinction between these two types is conveyed syntactically through a return type a taskoriented functions is often given a return type of void while a computationally oriented function has a speci c data type assigned to it A typical header for a C function looks like this type fname parameter list In this header type refers to the return type of the function As noted before void is generally used for ataskoriented function while a function that computes a result say of type double would use the return type of double fname is the name of the function As we ve seen in the examples so far the convention among C programmers is to use an uppercase letter to start the function name The parameter list is a mechanism to provide information to the function that it will need to carry out its task For example if you re going to compute a square root you need to provide the value whose square root is desired the parameter list is used to convey that information We ll see more about this later Within a function the return operation can be used to tell the computer that the function s work is done and that control should be returned to the point from which the function was initiated If the function is computing a result the value of that result is appended to the return statement return answer If however the function has a return type of void then the return statement is simply written as return Finally if a C function is de ned within the body of a class for example within the de nition of a form then you need to decide if that function is to be private or usable only from within other functions that are a part of the class or public or usable from outside of the class de nition The 64 Introduction to Computer Programming Using C appropriate designation public or private is then written in front of the function s header public void DoSomething or pri va te doubl e Compu teSome thing Specifying the Parameters for a Function As noted above parameters are used to communicate information to a function that will be needed to complete the function s task Actually C has three different kinds of parameters value parameters which are used to provide a value to a function reference parameters which are used to provide information to a function that may be changed by the function and output parameters which can be used by a function that needs to communicate multiple results back The parameter list for a function is simply a list of individual variable declarations separated by commas To distinguish between the various parameter types a pre x of ref or out is placed ahead of the variable declaration in the parameter list a parameter speci ed without the pre x is by default a value parameter To illustrate here s the start of a hypothetical function with a fairly complex parameter list int Demo string st ref int counter out double resultl out double result2 In this example the function itself computes and returns a result of type int The parameter list then de nes 4 parameter variables 0 st a value parameter of type string 0 counter a reference parameter of type int 0 resultl and result2 output parameters of type double When you need to tell the computer to carry out the action speci ed by a function you place the name of the function followed by the list of constants and or variables that are to be used in place of the parameters to the function Constant values may only be used in place of value parameters while variables can be used for any of the parameter types However when a variable is used in a position where a reference or output parameter is required the keyword ref or out must again precede that variable name in the functional invocation Result Demo quotThis is a test ref count out x1 out x2