Procedural Programming - Brigham Young University-Idaho

1y ago
5.45 MB
394 Pages
Last View : 14d ago
Last Download : 6m ago
Upload by : Harley Spears

Table of ContentsTable of Contents . 1Course Overview . 2Computers & Programs .41.0 First Program . 131.1 Output. 241.2 Input & Variables . 351.3 Expressions . 461.4 Functions . 581.5 Boolean Expressions . 761.6 IF Statements. 86Unit 1 Practice Test . 99Unit 1 Project : Monthly Budget . 1012.0 Modularization . 1082.1 Debugging. 1302.2 Designing Algorithms . 1452.3 Loop Syntax . 1562.4 Loop Output . 1682.5 Loop Design . 1812.6 Files . 190Unit 2 Practice Test . 207Unit 2 Project : Calendar Program . 2093.0 Array Syntax . 2143.1 Array Design . 2333.2 Strings . 2423.3 Pointers . 2553.4 Pointer Arithmetic . 2693.5 Advanced Conditionals . 284Unit 3 Practice Test . 301Unit 3 Project : MadLib . 3034.0 Multi-Dimensional Arrays . 3094.1 Allocating Memory . 3244.2 String Class . 3374.3 Command Line . 3464.4 Instrumentation . 356Unit 4 Practice Test . 361Unit 4 Project : Sudoku . 363A. Elements of Style . 369B. Order of Operations . 375C. Lab Help. 376D. Emacs & Linux Cheat-Sheet . 377E. C Syntax Reference Guide . 378F. Glossary . 381G. Index . 393

Course OverviewProcedural programming is the process of solving programming challenges by breaking large problems intosmaller ones. These sub-problems are called procedures.Unit 0GoalsThe goal of this class is that each student will be able to solve problems in C and have a solid foundationin software development methodology. By the end of the semester You will be well prepared for CS 165 and the other course in computing majors. This class is thefoundation on which all Computer Science (CS), Electrical Engineering (EE), and Electrical &Computer Engineering (ECEN) courses are based.You will have confidence in your ability to solve problems with C . This class will include tons ofopportunities for hands-on programming. By the end of the semester, you will have written morethan thirty programs.You will possess a tool-bag of different approaches to solve software problems. Not only will welearn the mechanics of the C programming language, we will also learn how to solveprogramming problems using procedural tools.You will have a firm foundation in the basic constructs of procedural C . All the components ofprocedural programming (except structures) will be learned in CS 124. Object OrientedProgramming, the second half of the C language, is the topic of next semester.These goals will be explored in the context of C using the Linux operating system.Course LayoutThe course will be broken into four sections:1. Simple Programs. How to write your first program and begin thinking like a programmer. At theend of this section, you will be able to write a program with multiple functions, IF statements, andcomplex mathematical operations.2. Loops. The goal of this section is to be able to solve problems using loops. Additionally we will learnseveral tools enabling us to solve hard programming problems and manage programs with largeamounts of complexity.3. Arrays. Next we will learn how to handle and manipulate large amounts of data in increasinglycomplex data structures. Specifically, we will learn about arrays, pointers, and file I/O.4. Advanced Topics. The final section of the course will involve learning about a collection ofspecialized topics (dynamic memory allocation, multi-dimensional arrays, jagged arrays, andinstrumentation to name a few) in the hopes they will help us understand the main topics of thesemester better. In other words, the goal is not to learn these specialized topics so much as to makesure we have nailed the fundamentals.Page 2 Course Overview Unit 0: Overview Procedural Programming in C

How to Use This TextbookThis textbook is closely aligned with CS 124. All the topics, problems, and technology used in CS 124 aredescribed in detail with these pages.Sam and SueUnit 0You may notice two characters present in various sections of this text. They embody two common archetypesrepresentative of people you will probably encounter in industry.Sue’s TipsSue is a pragmatist. She cares only about getting the job done at a high quality level and withthe minimum amount of effort. In other words, she cares little for the art of programming,focusing instead on the engineering of the craft.Sue’s Tips tend to focus on the following topics: Pitfalls: How to avoid common programming pitfalls that cause bugsEffort: How to do the same work with less time and effortRobustness: How to make code more resistant to bugsEfficiency: How to make code execute with fewer resourcesSam’s CornerSam is a technology nerd. He likes solving hard problems for their own sake, notnecessarily because they even need to be solved. Sam enjoys getting to the heart of aproblem and finding the most elegant solution. It is easy for Sam to get hung up on a problem forhours even though he found a working solution long ago.The following topics are commonly discussed in Sam’s Corner: Details: The details of how various operations work, even though this knowledge is notnecessary to get the job doneTidbits: Interesting tidbits explaining why things are the way they areNeither Sue’s Tips nor Sam’s Corner are required knowledge for this course. However, you may discoveryour inner Sam or Sue and find yourself reading one of their columns.Needing HelpOccasionally, each of us reaches a roadblock or feels like help is needed. This textbook offers two ways to bailyourself out of trouble.If you find you are not able to understand the problems we do in class, work through them at home beforeclass. This will give you time for reflection and help ask better questions in class.If you find the programming problems to be too hard, take the time to type out all the examples by hand.Once you finish them, work through the challenge associated with each example. There is something abouttyping code by hand that helps it seep into our brains. I hope this helps.Procedural Programming in C Unit 0: Overview Course Overview Page 3

Computers & ProgramsUnit 0Sam is talking with an old high school friend when he find out he is majoring in Computer Science. “Youknow,” said his friend, “I have no idea how a computer works. Could you explain it to me?” Sam is stumpedfor a minute by this. None of the most common analogies really fit. A computer is not really like a calculatoror the human brain. Finally, after much thought, Sam begins: “Computer programs are like recipes and thecomputer itself is like the cook following the instructions ”ObjectivesBy the end of this class, you will be able to: Identify the major parts of a computer (CPU, main memory, etc.).Recite the major parts of a computer program (statements, headers, etc.).Type the code for a simple program.Overview of Computers and ProgramsConsider a simple recipe for making cookies. The recipe consists of the ingredients (the materials used tomake the cookies) as well as the instructions (such as “stir in the eggs”). If the recipe was precise enough thenany two cooks would be able to produce an identical set of cookies from the provided ingredients. Mostrecipes, however, are ambiguous. This requires the cook to improvise or use his best judgment. This analogyholds well to the relationship between computers and programs with one exception: the computer is unableto improvise: Cook: The cook is the computer executing the instructions.Recipe: The recipe is the computer program to be executed.Ingredients: The ingredients are the input to the program.Cookies: The cookies correspond to the output of the program.Chef: The chef is the person who came up with the recipe. This is the role of the programmer.Your job this semester is to derive the recipe (computer program) necessary to produce the desired cookies(output) from the provided ingredients (input).Page 4 Computers & Programs Unit 0: Overview Procedural Programming in C

ComputersComputers today are all based on the basic model developed by Dr. John von Neumann. They consist of aCPU (the part that executes instructions), the Memory (the part where programs and data are stored), thebus (the wire connecting all components), and the peripherals (input and output llerCPUUnit 0MemoryBusPlease view the following movie to learn more about the parts of a computer:Parts of a ComputerPossibly the most important part of a computer is the CPU. This has several components: the memoryinterface (operating much like a controller, it puts data on the bus and takes data off the bus), instructionfetcher (determines which instruction is next to be executed), the instruction decoder (interpreting what agiven instruction does), the registers (keeping temporary data), and the ALU (Arithmetic Logic Unit,performing math and logical operations). Please view the following movie to learn more about the parts of acomputer:The CPUFinally, programs consist of simple instructions that are executed by the CPU.Instruction FetcherInstruction DecoderBusMemoryInterfaceRegistersALUProcedural Programming in C Unit 0: Overview Computers & Programs Page 5

The following is a sample instruction set (real CPUs have hundreds of instructions but do essentially the samething):Name Opcode DescriptionExampleUnit 0NOOP0Do nothingNOOPLOAD1Load a value from some memory location into the registerLOAD M:3SET2Set the register to some valueSET 1SAVE3Saves the value in a register to some memory locationSAVE M:10JUMP5Sets the Next Instruction value to some memory locationJUMP M:0JUMPZ6Same as JUMP except only sets the Next Instruction value if the JUMPZ M:0register is set to zeroADD8Adds a value to the registerADD 1SUB9Subtracts a value from what is currently in the registerSUB 1MULT10Multiplies the current value in the register by some valueMULT 2DIV11Integer division for some value in the registerDIV 2AND12Returns 1 if the value and the register are both non-zeroAND 1OR13Returns 1 if the value or the register is non-zeroOR 1NOT14Returns 1 if the value in the register is zeroNOTPlease view the following movie to learn about how these instructions can be used to make a program:ProgramsThe last item is an emulator (a program that pretends it is something else. In this case, it emulates the simplecomputer presented in the previous movies).EmulatorTo run a program:1. Type or paste the program in the large edit control below the “Load Program” label. Make sure thereis one instruction per line or it will not work correctly. You may also need to delete an extra space.2. Press thebutton. This will load the program into memory and set the “Next Instruction”pointer to zero.3. Step through the program, one instruction at a time, by pressing thebutton.A couple programs you may want to run what will they do?SET 0xffSAVE D:0SET 0x00SAVE D:0JUMP M:0Page 6 Computers & ProgramsSET 0xffSAVE D:0LOAD M:3ADD 1SAVE M:3JUMP M:0 Unit 0: Overview Procedural Programming in C

ProgramsThe “pound include” statement allowsthe program to include a library.The iostream library allows you toread/write data to the screenEvery C program begins with a functioncalled main.The using statement allows us toconveniently access the libraryfunctions. This library function iscalled std, short for standard.This tells the program where to beginexecution.#include iostream using namespace **** This program will display “Hello World!”* to the *****/int main(){cout "Hello World!" endl;return 0;}Every block of related code issurrounded by “curly braces”.All functions encapsulate theircode with curly braces.The return statement lets usexit the function. Here we areleaving the return code of 0.Code 0: No ErrorCode 0: Increasing SeverityThis line actually does the work for this program.We are “piping” the text “Hello World!” to the outputfunction called cout.IOSTREAM: This simple program has two parts to the header. The first part indicates that theiostreamlibrary will be used. The iostream library contains many useful tools that we will be using in every programthis semester, including the ability to display text on the screen. There are other libraries we will be introducedto through the course of the semester, including iomanip, cassert, and fstream.NAMESPACE: The second line of code in the header indicates we are to be using the shorthand versionof the tools rather than the longer and more verbose versions. This semester we will always have “usingnamespace std;” at the top of our programs, though in CS 165 we will learn when this may not be desirable.CURLY BRACES: All the instructions or statements in a C program exist in functions. The {}s (called“curly braces”) denote where the function begins and ends. Most programs have many functions, thoughinitially our programs will only have one. Back to our recipe analogy, a program with many functions issimilar to a recipe having sub-recipes to make special parts (such as the sauce). The functions can be namedmost anything, but there must be exactly one function called main(). When a program begins, execution startsat the head of main().COUT: The first instruction in the program indicates that the text “Hello world” will be displayed on thescreen. We will learn more about how to display text on the screen, as well as how to do more complex andpowerful tasks later in the semester (Chapter 1.1).RETURN: The last statement in this example is the return statement. The return statement serves twopurposes. The first is to indicate that the function is over. If, for example, a return statement is put at thebeginning of a function, all the statements after return will not be executed. The second purpose is to sendProcedural Programming in C Unit 0: Overview Computers & Programs Page 7Unit 0There are many computer languages, each enabling the programmer to write a computer program. In thisclass, we will be using the C language developed by Bjarne Stroustrup in the early 1980’s. A C program consists of two parts: the header and the functions. The header describes what tools will be used inthe program and the functions contain the recipes themselves. The functions consist of individual instructionscalled statements:

data from one function to another. Consider, for example, the absolute value function from mathematics. Inthis example, the output of the absolute value function would be sent to the client through the returnmechanism. We will learn more about the use of return later in the semester (Chapter 1.4).CommentsUnit 0Strictly speaking, the sole purpose of a recipe is to give the cook the necessary information to create a dish.However, sometimes other chefs also need to be able to read and understand what the recipe is trying to do.In other words, it is often useful to answer “why” questions (example: “Why did we use whole wheat flourinstead of white flour?”) as well as “how” questions (example: “How do I adjust the recipe for highelevation?”). We use comment to address “why” questions.Comments are notes placed in a program that are not read by the compiler. They are meant to make theprogram more human-readable and easier to adjust. There are two commenting styles in C : line and blockcomments.Line commentsLine comments indicate that all the text from the beginning of the line comment (two forward slashes //) tothe end of the line is part of the comment:{// line comments typically go inside functions just before a collection//of related statementscout "Display text\n";// You can also put a line comment on the end// of a line of code like this.}Some general guidelines on comments: Comments should answer “Why” and “How” questions such as “Why is this variable set to zero?”or “How does this equation work?”Comments should not state the obvious.When there are multiple related statements in a function, set them apart with a blank line and acomment. This facilitates skimming the function to quickly gain a high-level understanding of thecode.Block commentsBlock comments start with /* and continue until a */ is reached. They can span multiple lines, but often donot. We typically use block comments at the beginning of the ******************************* Program:*Assignment 10, Hello World*Brother Helfrich, CS124* Author:*Sam Student* Summary:*This program is designed to be the first C program you have ever*written. While not particularly complex, it is often the most difficult*to write because the tools are so *********************************/All programs created for CS 124 need to start with this comment block. Observe how the comment blocksstarts with the /* at the top and continues until the */ on the last line. We will start all of our programs withthe same comment block. Fortunately there is a template provided so you won’t have to type it yourself.Page 8 Computers & Programs Unit 0: Overview Procedural Programming in C

We also have a comment block at the beginning of every function. This comment block should state the nameof the function and briefly describing what it is designed to do. If there is anything unusual or exceptionalabout the function, then it should be mentioned in the comment block. The following is an example of afunction comment block:Unit *********** MAIN* This program will display a simple message on the **************/Problem 1Which part of the CPU performs math operations?Answer:Please see page 5 for a hint.Problem 2If a program is like a recipe for cookies then which of the following is most like the data of the program? IngredientsInstructionsMeasurementsChefPlease see page 4 for a hint.Procedural Programming in C Unit 0: Overview Computers & Programs Page 9

Problem 3What is missing from this program?#include iostream int main(){cout "Howdy\n";return 0;Unit 0}Answer:Please see page 7 for a hint.Problem 4Which of the following is a function?int main()#include iostream return 0;using namespace std;Please see page 7 for a hint.Problem 5What is wrong with this program?#include iostream using namespace std;int main(){cout "Howdy\n";}Answer:Please see page 7 for a hint.Page 10 Computers & Programs Unit 0: Overview Procedural Programming in C

Assignment 0.2In I-Learn, please answer the following questions:1. What does the following assembly program do?Unit 0SET 0xffSAVE D:0SET 0x00SAVE D:0JUMP M:02. What does the following assembly program do?SET 0xffSAVE D:0LOAD M:3ADD 1SAVE M:3JUMP M:03. Write the code to put “Hello world” on the screen:4. What is the purpose of comments in a program?5. Give an example of all the ways to write a comment in C :Procedural Programming in C Unit 0: Overview Computers & Programs Page 11

Unit 11.0 First Program . 131.1 Output. 241.2 Input & Variables . 351.3 Expressions . 461.4 Functions . 581.5 Boolean Expressions . 761.6 IF Statements. 86Unit 1 Practice Test . 99Unit 1 Project : Monthly Budget . 101Page 12 Computers & Programs Unit 1: Simple Program Procedural Programming in C

1.0 First ProgramSue is home for the Christmas holiday when her mother asks her to fix a “computer problem.” It turns outthat the problem is not the computer itself, but some data their bank has sent them. Instead of e-mailing alist of stock prices in US dollars ( ), the entire list is in Euros ( )! Rather than perform the conversion byhand, Sue decides to write a program to do the conversion. Without referencing any books (they are back inher apartment) or any of her previous programs (also back in her apartment), she quickly writes the code tocomplete the task.Unit 1ObjectivesBy the end of this class, you will be able to: Use the provided tools (Linux, emacs, g , styleChecker, testBed, submit) to completea homework assignment.Be familiar with the University coding standards (Appendix A. Elements of Style).PrerequisitesBefore reading this section, please make sure you are able to: Type the code for a simple program (Chapter 0.2).Overview of the processThe process of turning in a homework assignment consists of several steps. While these steps may seemunfamiliar at first, they will be well-rehearsed and second-nature in a week or two. The lab assistants (wearinggreen vests in the Linux lab) are ready and eager to help you if you get stuck on the way. The process consistsof the following steps: into the labCopy the assignment template using cpEdit your file using emacsCompile the program using g Verify your solution with testBedVerify your style with styleCheckerTurn it in with submitThis entire process will be demonstrated in “Example – Hello World” at the end of the chapter.Procedural Programming in C Unit 1: Simple Programs 1.0 First Program Page 13

0. LoginAll programming assignments are done on the Linux system. This includes the pre-class assignments, theprojects, and the in-lab tests. You can either go to the Linux Lab to use the campus computers, or connectremotely to the lab from your personal computer. Either way, you will need to log in. If you have not donethis in Assignment 0.0, please re-visit the quiz for the default password. The lab assistants will be able to helpyou reset your password if necessary. Please see Appendix C: Lab Help for a description of what the labassistants can and cannot do.It is worthwhile to set up your computer so you do not need to come to the lab to do an assignment. Themethod is different for a Microsoft Windows computer than it is for an Apple Macintosh computer.Remote access for Windows computers1. Download the tool called PuTTYUnit 1Setup - PuTTY2. Go to the lab and read the IP address (four numbers separated by periods) from any machine in thelab. They are through This will be the physical machine you areaccessing when using remote access3. Boot PuTTY and type in your IP address from step 2 and the port 215. You might want to save thissession so you don't have to keep typing the numbers in.4. Select [OPEN]. After you specify your username and password, you are now logged into thatmachine.Remote access for Macintosh or Linux computersIf you are on a Macintosh or a Linux computer, bring up a terminal window and type the following command:ssh username @ ip -p215If, for example, you want to connect to machine and your username is “sam”, then you wouldtype:sshsam@ more information, please see:Setup - TerminalPage 14 1.0 First Program Unit 1: Simple Program Procedural Programming in C

1. Copy TemplateOnce you have successfully logged into the Linux system (either remotely or in the Linux Lab), the next stepis to copy over the template for the assignment. All the assignments for this class start with a template filewhich has placeholders for the assignment name and the author (that would be you!). This file, and all otherfiles pertaining to the course, can be found on:/home/cs124The assignment (and project and test) template is located on:/home/cs124/template.cppcp source file destination file If, for example, you were to copy the template from /home/cs124/template.cpp into hw10.cpp, you would typethe following command:cp/home/cs124/template.cpphw10.cppMost Linux commands do not display anything on the screen if they were successful. You will need to do adirectory listing (ls) to see if the file copied. A list of other common Linux commands are the following:NavigationtoolsChange Directoryls . List information about file(s)cat . Display the contents of a file to the screenclear . Clear terminal screenexit . Exit the shellyppasswd . Modify a user passwordOrganizationmkdir . Create new folder(s)mv . Move or rename files or directoriestoolsrm . Remove filesProgrammingemacs . Common code editortoolsvi . More primitive but ubiquitous editorg . Compile a C programHomeworkstyleChecker . Run the style checker on a filetestBed . Run the test bed on a filetoolssubmit . Turn in a fileFor more commands or more details on the above, please see Appendix D: Linux and Emacs .Sue’s TipsBe careful how you name your files. By the end of the semester, you could easily get lost in asea of files. Spend a few moments thinking of how you will organize all your files as this willbe a useful practice for the remainder of your career.Procedural Programming in C Unit 1: Simple Programs 1.0 First Program Page 15Unit 1On the Linux system, we type commands rather than use the mouse. The command used to copy a file iscalled “cp”. The syntax for the copy command is:

2. Edit with EmacsOnce the template has been copied

programming problems using procedural tools. You will have a firm foundation in the basic constructs of procedural C . All the components of procedural programming (except structures) will be learned in CS 124. Object Oriented Programming, the second half of the C language, is the topic of next semester.

Related Documents:

the classroom are responsible for contributing to this complete educational vision. A BYU education should be spiritually strengthening, intellectually enlarging, and character building, leading to lifelong learning and service. (The Mission of Brigham Young University and The Aims of a BYU Education, Brigham Young University. Brigham Young .

31st Annual BRIGHAM YOUNG UNIVERSITY MODEL UNITED NATIONS CONFERENCE Sponsored by the David M. Kennedy Center for International Studies Saturday, November 14, 2020 Esteemed Delegates, I am pleased to welcome you to the 31st annual Brigham Young University Model United

Behind Closed Doors: A Network Tale of Spoofing, Intrusion, and False DNS Security Casey Deccio Brigham Young University Provo, UT Alden Hilton Brigham Young University Provo, UT Michael Briggs Brigham Young University Provo, UT Trevin Ave

Brigham Young University CAA File #48 2 AMERICAN SPEECH-LANGUAGE-HEARING ASSOCIATION Application for Reaccreditation Evaluation of Educational Programs in Speech-Language Pathology and Audiology Date March 1, 1998 Name of institution Brigham Young University Address 136 TLRB, Provo, UT 84602 School, College, or

Efforts to the Jewish People" (Master's thesis, Brigham Young University, 1967). 7Burl Shephard, "When We Know People, We Love Them," Instruc kQr 99 (August 1964):318-19. 8Dann Hone, "Communique," Staff Newsletter of Brigham Young University, Division of Continuin

29th Annual BRIGHAM YOUNG UNIVERSITY MODEL UNITED NATIONS CONFERENCE Sponsored by the David M. Kennedy Center for International Studies Friday, October 26, 2018 – Provo, Utah Dear Delegates, I am so pleased to welcome you to the 29th annual Brigham Young Univ

Structure programming has been the traditional way of programming. Procedural Programming If you have taken a course in C, Visual Basic, Pascal, FORTRAN, Cobol etc. the programs you wrote were Procedural. In procedural programming, the focus of the programs was to solve a problem.

IEEE TRANSACTIONS ON COMPUTER-AIDED DESIGN OF INTEGRATED CIRCUITS AND SYSTEMS, VOL. 33, NO. 9, SEPTEMBER 2014 1277 Placement for Binary-Weighted Capacitive Array in SAR ADC Using Multiple Weighting Methods Yongfu Li, Student Member, IEEE, Zhe Zhang, Student Member, IEEE, Dingjuan Chua, Student Member, IEEE, and Yong Lian, Fellow, IEEE Abstract—The overall accuracy and linearity of a matching .