Computer Programming - Lecture 2

1,655 views
1,516 views

Published on

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,655
On SlideShare
0
From Embeds
0
Number of Embeds
403
Actions
Shares
0
Downloads
128
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Computer Programming - Lecture 2

  1. 1. Lecture 2 Algorithms and Problem SolvingComputer Programming I 1
  2. 2. Overview Algorithm Program design Pseudocode Structure diagram Flowcharts Introduction to C++ Testing and debugging Program errors Computer Programming I 2
  3. 3. Algorithm Algorithm  A sequence of precise instructions which leads to a solution Program  An algorithm expressed in a language the computer can understand Computer Programming I 3
  4. 4. Program Design Programming is a creative process  No complete set of rules for creating a program Program Design Process  Problem Solving Phase • Result is an algorithm that solves the problem  Implementation Phase • Result is the algorithm translated into a programming language Computer Programming I 4
  5. 5. Problem Solving Phase Be certain the task is completely specified  What is the input?  What information is in the output?  How is the output organized? Develop the algorithm before implementation  Experience shows this saves time in getting your program to run.  Test the algorithm for correctness Computer Programming I 5
  6. 6. Implementation Phase Translate the algorithm into a programming language  Easier as you gain experience with the language Compile the source code  Locates errors in using the programming language Run the program on sample data  Verify correctness of results Results may require modification of the algorithm and program Computer Programming I 6
  7. 7. Object Oriented Programming Abbreviated OOP Used for many modern programs Program is viewed as interacting objects  Each object contains algorithms to describe its behavior  Program design phase involves designing objects and their algorithms Computer Programming I 7
  8. 8. Sample problemsWrite a program calculating the sum of two numbers Input Processing Output 5, 10 15 1) Declare variables 3) Process 2) Assign values input_1 sum = input_1 + input_2 input_1 = 5 input_2 input_2 = 10 sum The computer (and so C++) Names for our cells provides basic arithmetic 8 operations. If the operation you want to use is not provided, you have to compose it. Computer Programming I 8
  9. 9. Write a program calculating the sum of two numbers There are many models supporting the development of the code. We will see now the same algorithm expressed as: 1)Pseudocode 2)Structure diagram 3)Flowcharts and finally in C++. Computer Programming I 9
  10. 10. Pseudocode Mixture of C++ and ordinary English Allows us to make our algorithm precise without worrying about the details of C++ syntax Computer Programming I 10
  11. 11. PseudocodeWrite a program calculating the sum of two numbers Version 1: Version 2: PROGRAM Add Two Numbers PROGRAM Add Two Numbers READ two numbers READ First ADD the numbers READ Second WRITE the sum Sum = First + Second END PROGRAM WRITE Sum END PROGRAM Computer Programming I 11
  12. 12. Structure Diagram  Helpful to break the algorithm into more manageable piecesWrite a program calculating the sum of two numbers Version 1: PROGRAM Add Two Numbers READ ADD WRITE Two Numbers Two Numbers The Sum Computer Programming I 12
  13. 13. Structure DiagramWrite a program calculating the sum of two numbers Version 2: PROGRAM Add Two Numbers READ ADD WRITE Two Numbers Two Numbers The Sum READ READ Sum = Input_1 Input_2 Input_1 + Input_2 Computer Programming I 13
  14. 14. Rules for Structure Diagram A module which resides above others is referred to as a Calling module A module which resides below another is referred to as a Called module A module can be both a calling and called module A called module can only be called by one calling module Computer Programming I 14
  15. 15. Flowchart Diagram that shows the logical flow of a program Stress on structured programming Useful for planning each operation a program performs, and in order in which the operations are to occur By visualizing the process, a flowchart can quickly help identify bottlenecks or inefficiencies where the process can be streamlined or improved The final visualization can then be easily translated into a program Computer Programming I 15
  16. 16. Flowcharting symbols Input/Output (used for all I/O operations) Processing (used for all arithmetic and data transfer operations). Decision (used to test for a condition). Terminal (used to indicate the beginning and end of a program or module). Connector (used to indicate the point at which a transfer of control operation occurs). Predefined (used to indicate the name process of a module to be executed). Connecting all the symbols and showing the flowComputer Programming I 16
  17. 17. Write a program calculating the sum of two numbers START READ First READ Second Sum = First + Second WRITE Sum END Computer Programming I 17
  18. 18. Flowchart Conventions1) Each symbol denotes a type of operation.2) A note is written inside each symbol to indicate the specific function to be performed.3) The symbols are connected by flow-lines.4) Flowcharts are drawn and read from top to bottom unless a specific condition is met that alters the path.5) A sequence of operations is performed until a terminal symbol designates the sequences end or the end of the program.6) Sometimes several steps or statements are combined in a single processing symbol for ease of reading. Computer Programming I 18
  19. 19. Computer Programming I 19
  20. 20. startA flowchart to accept two numbers as input and prints out the maximum Input A Input B False True A>B print B print A end Computer Programming I 20
  21. 21. Structured Programming Structured Programming is a technique using logical control constructs that make programs easier to read, debug, and modify if changes are required. true false true Sequence Selection Repetition Computer Programming I 21
  22. 22. Different selection structuresIf a > 10 then do S1 If a > 10 then do nothing else do S2 false truetrue false A>10 A>10S1 S2 If a > 10 then do S1 else do S2 If a <= 10 then do S1 True False true false A>10 A<=10 S1 S2 S1 Computer Programming I 22
  23. 23. Loop structures False S1 A<=10 true S2 S1 true A<=10 S2 FalseRepeat While A is less than or equal toS1 10 repeatS2 S1As long as A is Less than or S2equal to 10 otherwise exit the End looploop Computer Programmingthe What is I difference ? 23
  24. 24. Loop example (do..While)Draw a flowchart to allow the input of 5 numbers Startand displays out the sum of these numbers 1 C=1 Assume the numbers given to A are 3,2,4,5,6 in order 2 Sum=0 C=1 C=1 C=2 C=1 Sum = 0 Sum = 3 Sum = 3 Sum = 0 A=3 A=3 A=3 3 Input A 1,2 3 4 5 4 Sum = Sum + A C=2 C=2 C=2 C=3 Sum = 3 Sum = 3 Sum = 5 Sum = 5 5 C=C+1 A=3 A=2 A=2 A=2 C <=5 true true 6 3 4 5 6 c<=5 False C=3 C=3 C=3 C=4 Output Sum = 5 Sum = 5 Sum = 9 Sum = 9 7 Sum A=3 A=4 A=4 A=4 C <=5 true Computer Programming 4 6 3 I 5 24 End
  25. 25. Loop example (while…) Draw a flowchart to allow the input of Start 5 numbers and displays out the sum of these numbers 1 C=11 C=1 Assume the numbers given to 2 Sum=0 A are 3,2,4,5,6 in order2 C=1 False Sum = 0 3 c<=5 4 5 6 true3 C=1 C=1 C=1 C=2 4 Sum = 0 Sum = 3 Sum = 3 Sum = 3 Input A C <=5 true A=3 A=3 A=3 5 Sum = Sum + A C=2 C=2 C=2 C=3 6 C=C+1 Sum = 3 Sum = 3 Sum = 5 Sum = 5 C <=5 true A=2 A=2 A=3 Output 3 4 5 6 7 Sum Computer Programming I 25 End
  26. 26. Prime number example flowchart Start 1Pseudocode algorithm to solve this problem: Input M 21. Start 3 I=22. Input a number M3. Set an Index (I) to start from 24. Divide the number M by the Index (I) R=M%I 4 value and store the remainder in R True False5. If R is equal to zero then output “Not R=0? 5 Prime” and goto to Step 106. Increment Index (I) by 1 I=I+1 67. If the Index (I) value is less than the True number M go to Step 4 I<M? 78. Output “Prime” False9. End Output Output 8 Prime Not Prime End 9 Computer Programming I 26
  27. 27. Example of structured flowchartComputer Programming I 27
  28. 28. Find the Maximum 28
  29. 29. Find the Maximum - Structured 29
  30. 30. Find the Maximum - Structured 30
  31. 31. Unstructured Flowchart break…Computer Programming I 31
  32. 32. Introduction to C++ Where did C++ come from?  Derived from the C language  C was derived from the B language  B was derived from the BCPL(Basic Combined Programming Language) language Why the ‘++’? ++ is an operator in C++ Computer Programming I 32
  33. 33. C++ History C developed by Dennis Ritchie at AT&T(American Telephone & Telegraph Company) Bell Labs in the 1970s.  Used to maintain UNIX systems  Many commercial applications written in C C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s.  Overcame several shortcomings of C  Incorporated object oriented programming  C remains a subset of C++ Computer Programming I 33
  34. 34. A Sample C++ Program A simple C++ program begins this way #include <iostream> using namespace std; int main() { And ends this way return 0; } Computer Programming I 34
  35. 35. CommentsComments are pieces of source code discarded from the code by thecompiler. They do nothing. Their purpose is only to allow the programmerto insert notes or descriptions embedded within the source code.C++ supports two ways to insert comments:// line comment/* block comment *//* my second program in C++ with more comments */#include <iostream.h>int main (){ cout << "Hello World! "; // says Hello World! return 0;} Computer Programming I 35
  36. 36. My first program in C++ Hello World! a comment line a pound sign (#) is a directive for the preprocessor. It is not // my first program in C++ executable code but indications for the compiler. #include <iostream.h> tells the compilers preprocessor to int main () include the iostream standard header file. { cout << "Hello World!"; Corresponds to the beginning of the main function declaration. The main return 0; function is the point where all C++ programs begin their execution. } to terminate a program cout is the standard output stream in C++ Computer Programming I 36
  37. 37. Layout of a Simple C++ Program #include <iostream> using namespace std; int main() { variable_declarations statement_1 statement_2 … statement_last return 0; }Computer Programming I 37
  38. 38. Program Layout (1/2) Programmers format programs so they are easy to read  Place opening brace ‘{‘ and closing brace ‘}’ on a line by themselves  Indent statements  Use only one statement per line Computer Programming I 38
  39. 39. Program Layout (2/2) Variables are declared before they are used  Typically variables are declared at the beginning of the program  Statements (not always lines) end with a semi-colon Include Directives #include <iostream>  Tells compiler where to find information about items used in the program  iostream is a library containing definitions of cin and cout Computer Programming I 39
  40. 40. Program Layoutusing namespace std;  Tells the compiler to use names in iostream in a “standard” way  To begin the main function of the programint main(){  To end the main functionreturn 0;}  Main function ends with a return statement Computer Programming I 40
  41. 41. Running a C++ Program C++ source code is written with a text editor The compiler on your system converts source code to object code. The linker combines all the object code into an executable program. Computer Programming I 41
  42. 42. ConceptsCompiler: is a program that translates a high-levellanguage program, such as a C++ program, into amachine-language program that the computer candirectly understand and execute.Linking: The object code for your C++ programmust be combined with the object code forroutines (such as input and output routines) thatyour program uses. This process of combiningobject code is called linking and is done by aprogram called a linker. For simple programs,linking may be done for you automatically. Computer Programming I 42
  43. 43. Run a Program Obtain code Compile the code Fix any errors the compiler indicates and re-compile the code Run the program Now you know how to run a program on your system Computer Programming I 43
  44. 44. Testing and Debugging Bug  A mistake in a program Debugging  Eliminating mistakes in programs  Term used when a moth caused a failed relay on the Harvard Mark 1 computer. Grace Hopper and other programmers taped the moth in logbook stating: “First actual case of a bug being found.” Computer Programming I 44
  45. 45. Program Errors Syntax errors  Violation of the grammar rules of the language  Discovered by the compiler • Error messages may not always show correct location of errors Run-time errors  Error conditions detected by the computer at run-time Logic errors (warning)  Errors in the program’s algorithm  Most difficult to diagnose  Computer does not recognize an error Computer Programming I 45
  46. 46. End of Lecture 2Computer Programming I 46

×