Download Fundamentals of Programming: Errors in C++ and Algorithms with Flowcharts and more Cheat Sheet Programming Languages in PDF only on Docsity! Fundamentals of Programming Lecture 4a: Errors in C++, Algorithms and Flowchart Errors in C++ * Illegal operation performed * Detected at the time of compilation Types Syntax error Run time error Linker error Logical error wk wn Semantic error Run Time Error Runtime errors occur when a program with no syntax errors asks the computer to do something that the computer is unable to reliably do. * Trying to divide by a variable that contains a value of zero * Trying to open a file that doesn't exist * There is no way for the compiler to know about these kinds of errors when the program is compiled Example Run Time Error void main() { int n = 9, div = 0; // wrong logic number is divided by 0 div = n/0; cout<<div; Linker Errors After compilation different object files are linked with main’s object, errors generated when the executable of the program cannot be generated * wrong function prototyping * incorrect header files * most common linker error is writing Main() instead of main() Semantic Error Semantic error occurs when the statements written in the program are not meaningful to the compiler Example: void main() { int a, b, c; a+b=c;//semantic error } Algorithms and Flowcharts Example 1 Write an algorithm and draw a flowchart to convert the length in feet to centimeter 12 Example 2 Flowchart: ( start ) Input M1,M2,M3,M4 GRADE<(M1+M2+M3+M4)/4 2 Is GRADE<5 0 PRINT PRINT “PASS” “FAIL” Algorithm: Step 1: Input M1,M2,M3,M4 Step 2: GRADE < (M1+M2+M3+M4)/4 Step 3: if (GRADE <50) then Print “FAIL” else Print “PASS” endif 15 Example 3 Write an algorithm and draw a flowchart that will calculate the roots of a quadratic equation (ax? + bx +c = 0) Hint: d=sqrt(b2 - 4ac) Roots: x1 = (-b + d)/2a, x2 = (-b—d)/2a 16 Pseudocode: Input the coefficients (a,b,c) of the quadratic equation Calculate d Calculate x1 Flowchart: Calculate x2 Algorithm: d sqrt(b x b-4x ax c) Step 1: Input a, b,c Step 2: d< sqrt(bxb — 4xaxc) Step 3: x1— (- b+d) / (2xa) x, (1b alexa) Step 4: x2 — (- b-d) / (2xa) Step 4: Print x1, x2 x, (-b+ d)/(2x a) Algorithm: Step 1: Step 2: Step 3: Input VALUE1, VALUE2 if WALUE1 > VALUE2) then MAX <— VALUE1 else MAX <— VALUE2 endif Print “The largest value is”, MAX Flowchart ¥ oS | 20 Example 5 Write an algorithm for a person who is ordering food at a fast food restaurant. At the food counter, the person can order the following items: a burger, fries and a drink. After placing his/ her order the person goes to the cashier 21 Pseudocode: Approach counter if want burger then order burger if want fries then order fries if want drink then order drink Pay cashier Flowchart: Approach counter Want Y rder burger? urger Y - nn YS N Pay cashier 22