1 / 214

Understanding Algorithms: The Foundation of Programming

Learn about algorithms, their characteristics, and design tools. Discover how to convert algorithms into programs and understand the importance of clear and effective step-by-step solutions.

mangino
Download Presentation

Understanding Algorithms: The Foundation of Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 1 Greena Dattani

  2. What is algorithm Algorithm is the effective method to obtain step by step solution of problems. Knowledge of algorithm forms the foundation of study programming languages. Before starting with programming let us understand algorithm. i.e how to write algorithm, characteristic of algorithm, algorithm designing tool and conversion of algorithm to programs. Definition: An algorithm is defined as the finite steps followed in order to solve the given problem. Greena Dattani

  3. For example: To find the average score of a student for the three test marks. Step1 :Start Step2: Accept the three test marks s1,s2,s3 Step3: sum=s1+s2+s3 Step4:Average =sum/3 Step5: Display average Step6: Stop Greena Dattani

  4. Characteristic of algorithm: • Input: An algorithm must provide with any number of input/data values. • Output: An algorithm must produce at least one output. • Definiteness: Each step of the algorithm must be clear and distinct which ensures that the statement must be unambiguous. For example: To divide two numbers Algorithm Step1: Accept the numbers a,b. Step2: c=a/b Step3:Display c. Step 4: Stop. Greena Dattani

  5. Step 2 of this algorithm is not clear, as there will be no output . If b=0. Since the system doesn’t such an answer, care must be taken while writing an algorithm. The above algorithm can be rectified as follows Step1: Read the two numbers a, b. Step2:If (b=0); • Print “denominator value is 0; • And go to step 5 Step3:c=a/b Step4: print c Stop Greena Dattani

  6. Finiteness: The algorithm must be terminated after a finite number of steps. Let us illustrate this point with the help of an example: Algorithm: Step1: Start Step2: Let a=9 Step3: x=y*z Step4: Print x and go to step 2 Step5: Stop Here we noticed that in an algorithm, nowhere the value of a is changed, which control the flow of algorithm nerve terminates. Such statements must be avoided. The finiteness property assures the unambiguity in the flow. Greena Dattani

  7. Effectiveness: It must be possible in practice, to carry out each step manually. The statements must be feasible. Thus the algorithm even through is definite, should also be practical. If one take care of the above mentioned characteristics while writing the algorithm, then we can be sure of the results, for any kind of inputs. Greena Dattani

  8. Algorithm Designing tools: Algorithm must be designed in such a way that it is followed by the pure top-down approach. This will ensure the straight line execution of the algorithm. An algorithm can be expressed or designed in many ways. One can make a use of any language to specify the steps involved in solving a particular problem but simple and precise language could be adopted. Two famous ways of writing the algorithm are making use of flowcharts and pseudo codes. Greena Dattani

  9. Flowchart: Flowchart is the diagrammatic way of representing, the steps to be followed for solving the given problem. Flowcharts proves the visualization of the steps involved, since it is in the form of a diagram one can understand the flow very easily. Here are some diagrammatic symbols to design a flow chart. Greena Dattani

  10. Greena Dattani

  11. Pseudocode: Pseudocode is an artificial and informal language that helps the programmers to develop algorithm in the text format. It allows the programmer to focus on the logic of the algorithm without being distracted by details of the language syntax. It narrates steps of the algorithm more precisely. • Following are the keywords used to indicate input, output and other operations. • Input – READ, GET • Output – PRINT, DISPLAY • Compute – CALCULATE, DETERMINE • Initialize SET, INT • Add one – INCREMENTER • Sub one- DECREMENTER • Conditions and loops • IF-THEN ELSE • Repetitive execution • WHILE • CASE • REPEAT UNTIL • FOR Greena Dattani

  12. Pseudocode to obtain sum of two numbers. BEGIN INPUT X,Y DETERMINE SUM = X+Y PRINT SUM END Pseudocode to obtain average of three numbers. BEGIN DISPLAY “INPUT 3 NOS” INPUT X,Y,Z DETERMINE SUM = X+Y+Z DETERMINE AVG=SUM/3 PRINT AVG END Greena Dattani

  13. Designing a program A program is a set of instructions that are grouped together to accomplish a task or tasks. The instructions consist of task like reading and writing memory, arithmetic operations, and comparisons. Aim of a particular Program is to obtain solution to a given problem. We can design a program by going through the following first four major steps: Analyze the program. Design a solution/Program Code/Enter the program Test the program Evaluate the solution. Greena Dattani

  14. Analyze the program: When we analyze a problem, we think about the requirements of the program and how the program can be solved. Design a solution/Program: This is the stage where we decide how our program will work to meet the decision made during analysis. Program design does not require the use of a computer. We can design program using pencil and paper. This is the stage where algorithm are designed. Code/Enter the Program: Here we enter the program into the machine by making use of suitable programming language. Test the Program: This part deals with testing of programs for various inputs and making necessary changes if required. Testing cannot show that a program produces the correct output for all possible inputs, because there are typically an infinite number of possible inputs. But testing can reveal syntax errors, run-time problems and logical mistakes. Greena Dattani

  15. Evaluate The solution: Thus, finally program can be implementing to obtain desired results. Here are some more points to be considered while designing a program. • Use of procedures. • Choice of variable names. • Documentation of program • Debugging program • Testing. Use of procedures: Procedures is a part of code used to carry out independent task. Separate procedures could be written to carry out different task and then can be combined and linked with the main procedure. This will help in making the algorithm and eventually programs readable and modular. Greena Dattani

  16. Choice of variable: We can make programs more meaningful and easier to understand by choosing appropriate variable and constant names. For example: if wish to store age of two different people we can define variable age1,age2 to store their ages. The main advantage of choosing correct variable is that the program becomes self explanatory. Documentation of Program: Brief and accurate comments can be included at the beginning of each procedure/function.Program should be documented so that it can be used easily by the other people unfamiliar with the working and input requirements of the program.Thus documentation will specify what response it requires from the user during execution. Greena Dattani

  17. Debugging the Program: It is expected that one should carry out number of tests during implementation of algorithm, to ensure that the program is behaving correctly according to its specifications. The program may have some logical errors, which may not be detected during compilation. To detect such type of errors we may print computed values at various steps involved in algorithm. We should always manually execute the program by hand before ever attempting to execution it on machine. Greena Dattani

  18. Program Testing:The program should be tested against many possible inputs.Some of the things we might check are whether the program solves the smallest possible problem, whether it may not be possible or necessary to write programs that handle all input conditions, all the time. Whenever possible, programs should be accomplished by input and output section. • Here are some desirable characteristics of program • Integrity:R3fer to the accuracy of the program. • Clarity: Refer to the overall readability of the program, with emphasis on its underlying logic. • Simplicity: The clarity and accuracy of the program are usually enhanced by keeping the things as simple as possible, consistent with the overall program objectives. • Efficiency: It is concerned with the execution speed and efficient memory utilization. • Modularity:Many program can be decomposed into a independent procedures or modules. • Generality: Program must be as general as possible. Greena Dattani

  19. CHAPTER 2 Greena Dattani

  20. Programming is the process of writing instructions in any computer programming language, to get the task done by a computer. C++ is a very common programming language, and a good language to start learning basic concepts with, but you need to figure out what you find most useful. To do that you will have to try different programming languages over the time see which ones fits best to you,which language structure makes sense, which one seem to be able to accomplish the goals you want etc.Writing the program is the process of breaking out your instructions step by step and instructing the compiler or interpreter to those things in the proper programming languages. Your first step is to figure out exactly what you want your program to do, step by step. It is helpful to write this out on paper(Algorithm). Once you gain more experience you will start to see the value in doing this. Once you have your steps figured out,you will want to write a program in the language you have choosen. Whatever [programming language you choose, it will have specific word and styles to do different things. Much like we use words and punctuation every day, so do programs. Greena Dattani

  21. The origin of c++ : C++ is an object oriented language and was developed by BjarneStroustrup starting in 1979 at AT and T Bell laboratories as an enhancement to the C programming languages and originally named C with classes. It was renamed C++ in 1983 where ++ is an incrementer operator in C and C++.The Programming language was developed at AT and T for the purpose of writing the UNIX operating system. C was developed with the primary goal of Operating efficiency. BjarneStroustrup developed C++ in order to add objects oriented constructs to the C language. C++ is also considered t\as the combination of C along with Object Oriented features of Simula7. C++ is also a traditional procedural language with some additional constructs. A well written C++ program with some additional constructs. A well written C++ program will reflect elements of both object oriented programming style and classic procedural programming. C++ is actually an extensible language since we can define new styles in such a way that they act just like the predefined types which are the part of standard language.C++ is designed for large scale software development. C++ is regarded as a “ Middle-level”language, as it comprises combination of both high-level and low-level language features. Greena Dattani

  22. Programming language can be classified into following types: • Machine Language- Machine language are the only language understood by computers. While easily understood by computers, machine languages are almost impossible for humans to use because they consist entirely of numbers. • Assembly language: Assembly languages have the same structures and set of commands as machine languages but they enable a programmer to use names instead of numbers. • High Level languages: A programming languages such as C, FORTRAN or PASCAL that enables a programmer to write programs that are more or less independent of a particular type of computer. Such languages are considered high-level because they are closer to human languages. Machine languages and Assembly languages both are low-level languages since they are closer to the hardware. Greena Dattani

  23. Structure of simple c++ programs //simple program in c++ #include<iostream.h> int main() { cout <<“Welcome to NIRMALA COLLEGE”; return 0; } Output : Welcome to NIRMALA COLLEGE Greena Dattani

  24. //simple program in C++ This is a comment line. Lines beginning with two slash signs(//) are used to comment on the program or a part of the program. In the above program the line is a brief description of our program. #include<iostream.h> Lines beginning with a hash sign (#) are directives for the prepocessor. In this case the directives #include<iostream.h> tells the processor to include the header file iostream which is a standard file. This specificfile (iostream) includes the declarations of the basic standard input-output library in C++, and is included because functions (cout) from this file is used in the program Greena Dattani

  25. Int main(): This lines corresponeds to the beginning of the definition of the main function. The main() function is the point where programs execution begins. Evert C++ program must have a main() cout << “Welcome to NIRMALA COLLEGE”; cout represents the standard output stream in C++ and the meaning of the entire staement is to print(Welcome to NIRMALA COLLEGE) into the standard output stream(which usually is the screen). return 0; The return statement causes the main function to finish. This is the most usual way to end a C++ console program. Every function in C++ must return a value, thus return 0;return 0 to the integer function main(). Greena Dattani

  26. Compiling and running C++ programs: Let us understand compiling and debugging with the help of Turbo C++ and Borland C++. Turbo C++ and Borland C++ provides an integrated development environment(IDE) under MS DOS. The IDE provides us with an editor and several menus on the main menu bar. • File menu helps in creating and saving source file. • Source file can be compiled by using compile option. • Program once compiled can be executed with the run option. Greena Dattani

  27. Pitfall and Tips to Programming: Here are some pitfalls and basic things to be taken care of in any programming language. Some of the tips are specifically with respect to concepts covered in remaining chapters and could be understood well after going through those concepts. • Plan and be organized: When planning a program it is always better to plan ahead rather than jump straight into it. It is good idea to write down the functions of the program in the order you need to code them, it little ‘blocks’. Even “draw” it if it helps. When actually coding it, use comments. Doing these little things could save your valuable programming time and helps make the code look a little more explanatory and professional. • Write it out on paper: Think before you code and write the entire idea or the logic of solving a particular problem on paper; doing so would prevent lots of logical errors. This technique also works when you are not able to figure out why the logic is not working . Greena Dattani

  28. Indent your program: Always indent your program for readability. It is a good practice and useful to debug your program. Good indentation makes it easy to see that your closing braces are correctly aligned and help you scan through your code quickly by giving visual clues about where the program flow changes. • Always use comments: Make comments in your code often. Not only does to it help people who are trying to help you understand it more,when you come back later,you’ll be able to pick upwher you left off and edit much faster. For Example: int age1;/*holds age of first employee*/ Use either // or /* depending on your compiler and language Greena Dattani

  29. Always write if statements with braces: By putting braces around every block of code you write you ensure that future edits won’t introduce bizarre bugs. If you have a one-line if statement: If (<condition>) execute(); You should still surround execute(); with braces: If (<condition>) { execute(); } Now, if you go back and add a second instruction If(<condition>) { execute(); execute2(); } You don’t have to worry about putting in the braces, and you know that you won’t forget to put them in. Greena Dattani

  30. Restrict goto: Some very simple programming languages allow you to control the flow program with the goto keyword. You simply place a label somewhere in your program, and then can jump to that point in your code anythime by following goto with that keyword. Like so: GotomyLabel … myLabel; /* code*/ In these simple and limited programming languages, goto maybe used commonly, and this feature is included in C/C++ too. It is however considered as extremely bad programming practice. The reason for this is simply that there are better alternatives. C and C++ provides more advanced control structures like various types of function and loops, which not only make it easy to code a certain behaviour, but safer, goto is still sometimes used for customized control,like breaking out of heavily nested loops. If your program does indeed require the use of goto, you should probably be redesigning the whole program to fix it properly instead of using a quick fix like goto. If in doubt, don’t use goto. Greena Dattani

  31. Use Appropriate Variable: While programming, we have to take care about the variables. We need to give appropriate name for the variables to avoid confusion. • Take advantage of array indicates: When operating on two arrays with the same index and operation, the switch statement can usually be avoided. Consider the general switch statement that assigns and tallies all the occurrences of array[i] to count[i]: switch(array[i]){ case1: count[1]++; break; case2: count[2]++; break; case3: count[3]++; break; } This can be shortened to the single statement. Count [array[i]]++ Greena Dattani

  32. Beware of loop invariants: Be aware of loop invariant and how they can affect code efficiency. An example:If you have code within a loop that uses non-varying variable: for (i=0;i<100;i++) { total = I + x + y; cout <<total; } As you see , xand y are not variables within the loop and so it is much more efficient to code the loop as follows: total = x+y; for(i=0;i<100;i++) { total+=I; } This is because the loop does one less addition on each loop cycle. Greena Dattani

  33. Clean up after cin: It is a good idea to follow cin with cin.get() or cin.ignore() because cin can leave a terminating character in the stream, which could cause small problems with your code. For Example: For example: #include<iostream.h> int main() { int age; cout<<“ENTER YOUR AGE”; cin>>age; cout<<“you entered <<age<<endl”; return 0; } That code exits right after printing the age. The program’skips’ right over where it should pause for the use to press Enter. This is bad because the user never gets to see what is being written to the screen after enter the age. The code, however, works as intended: Greena Dattani

  34. Code Optimization tips: If you have got lots of if-else statements, try to put the most likely to be met first. Use a++ and a– instead of a+=1 and a-=1. While doing calculations: Remember while doing calculations in C++ that multiplication and division takes priority above addition and subtraction. Adding brackets according to these rules makes it to understand, and it is the neater way to code. Remember that when you use cout statement do not use Quotes around an arithmetic expression, it will simply display the whole line. Reuse the code Avoid using of temporary variable Avoid memory wastage Greena Dattani

  35. CHAPTER 3 Greena Dattani

  36. VARIABLES AND ASSIGNMENT Identifiers • A valid identifier is a sequence of one or more letters, digits or underscores characters (_). • Neither spaces nor punctuation marks or symbols can be part of an identifier. • Only letters, digits and single underscore characters are valid. • In addition, variable identifiers always have to begin with a letter. They can also begin with an underscore (_ ), but in some cases these may be reserved for compiler specific keywords . • In no case they can begin with a digit. Greena Dattani

  37. Some of the valid identifiers are: Fname, Age1, marks_phy, it1 Some examples of invalid identifiers are as follows: 1marks – Variable name should always start with a letter and not a digit. Curr$ - Use of special characters is not allowed. Room temp – Space is not allowed while naming a variable. Note: C++ is a "case sensitive" programming language. That means the identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the AGE variable is not the same as the age variable or the Age variable. These are three different variable identifiers. Greena Dattani

  38. Keywords: The keywords are also identifiers but cannot be user defined as they are reserved for a specific task. All the keywords should be in lower case letters. Some of the keywords are: auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete,do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template,this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void. Greena Dattani

  39. Constants Constants are expressions with a fixed value. There are three types of constants in C++ string constants, numeric constants & character constants. • String constants: • Numeric constant: • Character and string constant: Greena Dattani

  40. String constants is a sequence of alphanumeric (letters and numbers) characters enclosed in double quotation marks whose maximum length is 255 characters. Following are the examples of valid string constants. • “Nirmala” • “Rs 2500.00” • “University of Mumbai” Following are the examples of invalid string constants. • Nirmala – Characters are not enclosed in double quotation marks. • “information technology – Closing double quotation mark is missing • ‘Hello’ – Characters are not enclosed in double quotation marks. Greena Dattani

  41. Numeric constant are positive or negative numbers. • There are four types of numeric constants: • integer constant. • floating point constant. • hex constant. • octal constant. octal constant : short octal Long octal hex constant: short hexadecimal long hexadecimal Greena Dattani

  42. Integer constants They are numerical constants that identify integer decimal values. Integer constant do not contain decimal points. integer constant : integer short integer Long integer Here are some valid integer constants 1776 707 -273 Greena Dattani

  43. Floating Point Numbers These are numbers with decimals and/or exponents. They can include either a decimal point or an e characteror both a decimal point and an e character. integer constant : single precision (float) double precision (double) Long double Here are some valid floating point constants, 3.14159 6.02e23 (this is same as 6.02 x 1023 ) 1.6e-19 (this is same as 1.6x 10-19) The default type for floating point constants is double. If you explicitly want to express a float or long double numerical constant, we can use the f or l suffixes respectively: 3.14159L // long double 6.02e23f // float Greena Dattani

  44. Character and string constant: There also exist non-numerical constants, like: • 'z' • 'p' • "Hello world" • "How do you do?" The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes ("). Greena Dattani

  45. When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions: • x • 'x' x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'. Greena Dattani

  46. Escape sequence Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes: \n newline \r carriage return \t tab \v vertical tab \b backspace \f form feed (page feed) \a alert (beep) \' single quote (') \" double quote (") \? question mark (?) \\ backslash (\) Greena Dattani

  47. For example: '\n' '\t' "Left \t Right" "one\ntwo\nthree“ Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A). String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line. "string expressed in \ two lines“ Greena Dattani

  48. You can also concatenate several string constants separating them by one or several blank spaces, tabulators,newline or any other valid blank character: "this forms" "a single" "string" "of characters“. Finally, if we want the string literal to be explicitly made of wide characters (wchar_t), instead of narrow characters (char), we can precede the constant with the L prefix: L"This is a wide character string" Wide characters are used mainly to represent non-English or exotic character sets. Boolean literals There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type boolby using the Boolean literals true and false. Greena Dattani

  49. Symbolic constant Defined constants (#define)) You can define your own names for constants that you use very often without having to resort to memory consuming variables, simply by using the #define preprocessor directive. Its format is: #define identifier value For example: #define PI 3.14159 #define NEWLINE '\n' This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant. Greena Dattani

  50. For example: // defined constants: calculate circumference #include <iostream> #define PI 3.14159 #define NEWLINE '\n' int main () { double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; } Output: 31.4159 Greena Dattani

More Related