13.07.2015 Views

M182-lect1 pdf

M182-lect1 pdf

M182-lect1 pdf

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Professor Name : Joel M. Addawe Office : Department of Mathematics and ComputerScience (KA building),Email : joel.addawe@gmail.com phone : 0917-5062094 Consultation hours:8-12 pm WF2


Resources Class webpage : http://www.upb.edu.ph/koj Use to read important announcements read about course outline look up your grades download homework handouts download class notes Links to helpful tutorials3


Resources Discussion Forum Use to discuss class material ask questions on the material or the assignments (butNEVER post solutions) share solutions to posted practice problems get hints and tips for the assignments.4


What is a computer? A device that can accept data (input), manipulate it (process) according to specific instructions generate results (output) as a result of the processing. (optional) store the results5


What is programming? Program = a sequence of human-readableinstructions telling a computer how to do a particulartask or solve a given problem. Programming = Designing, writing and testing acomputer program.6


The programming process1. Analyze : Find the core problemDecide the inputs and outputsDecide how to go from the inputs to the outputs (only theprocess, not detailed mechanics)Break it down into sub-problems.This part is completed on paper.The end result is usually a flow-chart or pseudocode.7


The programming process2. Implement :a) Write instructionsTackle each sub-problem separately by writing a set ofinstructions (a function) for it.The computer can only understand instructions writtenin machine language (sequences of 1s and 0s).In order to make the programming process easier forhumans, researchers developed new, easier (forhumans) to understand languages as well as specialtools that could convert programs written in humanreadablelanguages into programs written in machinelanguage.C, C++ are examples of such a language.8


The programming process2. Implement :a) Write instructions (continued)Some operations that we may need our program toperform are so common (e.g. reading input from thekeyboard) that it would be expedient to have a readymodule for it.A collection of such modules is called a library. Forexample, the Input/Output library contains modules(functions) that can be invoked to read input from thekeyboard, or write output to the screen, etc.A library function may be invoked from within aprogram.9


The programming process2. Implement :b) Compile your programThe compiler is the tool that translates a programwritten in a high-level language such as C into aprogram written in machine language.The first step in the compilation process is calledpreprocessing. The preprocessor scans the inputprogram for special instructions called preprocessordirectives.These directives tell the preprocessor to do things suchas include an already existing library into the program.10


The programming process2. Implement :b) Compile your program (continued)The second step in the compilation process is the actualtranslation.The compiler tries to figure out whether the programsatisfies the rules of the language. A good compiler willcatch several types of mistakes and give informativedescriptions and suggestions to the programmer.One type of mistake is a syntax error. For example, amissing parenthesis in an arithmetic expression. Suchmistakes are generally easy for the compiler to identify.11


The programming process2. Implement :c) Link your programOnce a program has been compiled successfully, a toolcalled a linker is used to combine all its componentstogether and generate an executable program.d) Execute (run) your programIn order to run your program, you use an operatingsystem command to load it into your computer'smemory and execute its (machine language)instructions one at a time.(linux system) ./a.out or ./exer0(windows system) exer012


The programming process3. Test and debug :A program that compiles and executes successfully doesnot necessarily work as expected.It is very important to test the program with several kindsof inputs to make sure that it always gives the expectedoutcome.Programs often contain a type of error called a bug (or,more formally, a logic or design error). Such errors are hardto find and sometimes are not found until long after aprogram has been released.A tool called the debugger is very helpful in finding sucherrors.13


The programming process3. Test and debug :The recommended way to test a program is one module ata time.Once all modules have been tested successfully, startcombining them a few at a time and test again.This way, it is easier to identify where potential errors are.14


The programming environmentThe vi, gcc, gdb environmentThis application encompasses almost all of the tools thatyou will need for the programming process:a text editor to write the programa compilera linkera loader to load the program into memory so that it canbe executeda debugger15


How to program: example Write a program that computes the squarefootage of a house, given the dimensions ofeach room. Step 1 : Input The number of rooms (an integer) The dimensions of each room in feet (real numbers) Output The square footage of the house in square feet (realnumber) Subproblems compute the area of each room add up the areas of all rooms16


How to program: example Write a program that computes the squarefootage of a house, given the dimensions ofeach room. Step 2 : Translate your instructions into C language. We will learn how by exploringvariables, types, statements, expressions, assignments,conditionals, loop constructs, functions, etc. Compile your code The compiler is a program that converts the humanreadableinstructions that you wrote into machineexecutableinstructions.17


How to program: example Write a program that computes the squarefootage of a house, given the dimensions ofeach room. Step 3 : Test & Debug your program There are two types of mistakes:syntax mistakes (easy to fix; compiler helps)design mistakes, a.k.a. bugs (often hard to find; debuggerhelps). Test your program to make sure it works correctly andcan handle situations such as erroneous input (what ifsomeone types in negative dimensions?)18


A simple C program/* helloworld.cThis program prints "Hello world!" on the screen.*/#include int main () {}printf("Hello world!\n");return 0;19


A simple C program/* helloworld.cThis program prints "Hello world!" on the screen.*/#include A comment is any text between /*and */int main () {Use comments liberally to explainprintf("Hello world!\n"); your program and all its parts.return 0;}The compiler ignores all comments.20


A simple C program: Comments Comments in C may span several lines./* thisisonecomment *//* this is*/another comment21


A simple C program: Comments Comments in C may not be nested/* this /* small */ comment is wrong! */begincommentthis is ignored,as part of thecommentendcommentThe compilerthinks that thisis now actualcode, rather thana comment.22


A simple C program: Comments Suggestion: Line up comment delimiters verticallyand use symbols such as asterisks to make yourprogram more readable. Examples:/* This function reads a sequence of temperatures and* computes the average.*//*************************************** This program simulates a simple calculator. ** It reads two numbers and an operation ** (add, subtract, multiply or divide) and then ** computes and prints the result. ****************************************/23


A simple C program#include/* helloworld.c stdio.h is the library thatmeans "read inThis program prints "Hello provides world!" standard on input/output the screen.this file, too"*/functions (such as printf)#include int main () {}printf("Hello world!\n");return 0; This is a preprocessordirective. All preprocessordirectives start with a #Files ending in .h are calledheader files.24


A simple C program/* helloworld.cThis program prints "Hello world!" on the screen.*/#include Program execution always beginsin the main function.int main () {All C programs must have a mainfunction.printf("Hello world!\n");return 0;main() usually holds calls to}other functions25


A simple C program/* helloworld.cAllThisfunctionsprogramuse openingprintsand"Hello world!" on the screen.closing braces to mark the*/beginning and the end of thefunction.#include int main () {}printf("Hello world!\n");return 0;The block of statementsbetween these curlybraces is called the bodyof the function.26


A simple C programFunction /* helloworld.c = a block of statementswith This a given program name. prints "Hello world!" on the screen.*/This is the definition of a functioncalled main, which contains two#includestatements.int main () {}printf("Hello world!\n");return 0;main() is invoked(called) automaticallywhen a program beginsexecution. Otherfunctions can be calledfrom inside main()27


A simple C program: Statements A statement is the basic building block of a program.It usually translates to one or more machineinstructions. All statements end in semi-colons. The main() function shown in the example has twostatements:printf("Hello world!\n");andreturn 0;28


A simple C program: Functions A function is a block of statements with a givenname, which perform a well-defined operation. A function has zero or more input arguments andzero or one output values.29


A simple C program/* helloworld.cThis program prints "Hello world!" on the screen.This statement calls the printf() library function to*/print formatted text that we specify. The inputargument is enclosed in parentheses. It specifies the#include text we want to print as well as the formatting thatarranges the printed text.int main () {}printf("Hello world!\n");return 0;ALL statements end with a semicolon!30


A simple C program: printf() printf("Hello world!\n");The text that will be printedon the screen isHello world!\n means move on to thenext line. It is called aformat specifier. We willlearn more about that later.This statement will print Hello world! and move thecursor to the next line.31


A simple C program/* helloworld.cThis program prints "Hello world!" on the screen.*/return 0; means#include "we are done and everything completed successfully".More about return statements later.int main () {}printf("Hello world!\n");return 0 ;ALL statements end with a semicolon!32


A simple C program: the output/* helloworld.cThis program prints "Hello world!" on the screen.*/#include int main () {printf("Hello world!\n");return 0;}> Hello world!>33


A simple C program C is case sensitive. printf() is NOT the same as Printf(). All C commands are lowercase. To make your program more readable: Always write comments. Some compilers accept C++ style comments, too. Indent your code34


A simple C program: indentationint main () {}printf("Hello world!\n");return 0; As you can see, the two statements in the body ofmain() do not line up with the rest of the code. This is called indentation. Orderly indentation is very important; it makes yourcode readable. The C compiler ignores white space The vim editor will help you (look up "smart indenting"35


A simple C program: indentation There are two widely used indentation techniques:K&R styleint main() {int i; for(i=0; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!