chapter 1&2flowchart is a graphical or symbolic representation of an. algorithm. it is the...

62
CHAPTER 1&2

Upload: others

Post on 11-Mar-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

CHAPTER 1&2

OBJECTIVES

After completing this chapter, you will be able to: Understand the basics and Advantages of an

algorithm. Analysis various algorithms. Understand a flowchart. Steps involved in designing a program. Understand the origin of C++ Identify the applications that use C++ Understand simple C++ programs

INTRODUCTION

A computer is a useful tool for solving a great variety of problems. To make a computer do anything (i.e. solve a problem), you have to write a computer program. In a computer program you tell a computer, step by step, exactly what you want it to do. The computer then executes the program, following each step mechanically, to accomplish the end goal.

INTRODUCTION The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Flowchart is a graphical or symbolic representation of an algorithm. It is the diagrammatic representation of the step-by-step solution to a given problem.

Program Design consists of the steps a programmer should do before they start coding the program in a specific language. Proper program design helps other programmers to maintain the program in the future.

ALGORITHMS

Algorithm is a finite sequence of steps expressed for solving a problem.

An algorithm can be defined as “a process that performs some sequence of operations in order to solve a given problem”.

Algorithms are used for calculation, data processing, and many other fields.

ALGORITHMS

Let us follow an example to help us understand the concept of algorithm in a better way.

Let’s say that you have a friend arriving at the railway station, and your friend needs to get from

the railway station to your house. Here are three different ways (algorithms) that you might give your friend for getting to your home.

SOLUTION The taxi algorithm: Go to the taxi stand. Get in a taxi. Give the driver my address. The call-me algorithm: When your train arrives, call my mobile phone. Meet me outside the railway station. The bus algorithm: Outside the railway station, catch bus number 39. Transfer to bus 84 near Kurla station. Get off near Kalina University. Walk two blocks west to my house.

An Algorithm: Baking a Cake

Three reasons for using algorithms

Efficiency: Certain types of problems, like sorting, occur often in computing. Efficient algorithms must be used to solve such problems considering the time and cost factor involved in each algorithm.

Abstraction: Algorithms provide a level of abstraction in solving problems because many seemingly complicated problems can be distilled into simpler ones for which well known algorithms exist.

Reusability: Algorithms are often reusable in many different situations.

Expressing Algorithms

Algorithms can be expressed in many different notations , including natural languages, pseudocode, flowcharts and programming languages. Natural language expressions of algorithms tend to be verbose and ambiguous, and are rarely used for complex or technical algorithms. Pseudocode and flowcharts are structured ways to express algorithms that avoid many ambiguities common in natural language statements, while remaining independent of a particular implementation language. Programming languages are primarily intended for expressing algorithms in a form that can be executed by a computer, but are often used to define or document algorithms.

EXAMPLE

Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.

Solution

Algorithm using natural language statements: 1. Input a set of 4 marks 2. Calculate their average by summing and dividing by

4. 3. if average is below 50 ,then result is Fail other wise

the result is Pass.

Solution

Algorithm using pseudocode : 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

Example

Finding the largest number in an unsorted list of numbers.

Solution

Algorithm using natural language statements: 1. Assume the first item is largest. 2. Look at each of the remaining items in the list and

if it is larger than the largest item so far, make a note of it.

3. The last noted item is the largest item in the list when the process is complete.

Solution

Algorithm using pseudocode: Step 1 : largest = L0 Step 2 : for each item in the list (Length(L) ≥ 1), do Step 3 : if the item ≥ largest, then largest = the item return largest

FLOWCHARTS

FLOWCHARTS

A Flowchart is a type of diagram (graphical or symbolic) that

represents an algorithm or process. Each step in the process is represented by a different symbol and contains a short description of the process step. The flow chart symbols are linked together with arrows showing the process flow direction. A flowchart typically shows the flow of data in a process, detailing the operations/steps in a pictorial format which is easier to understand than reading it in a textual format.

Example

consider that we need to find the sum, average and product of 3 numbers given by the user.

Solution Algorithm for the given

problem is as follows: Read X, Y, Z Compute Sum (S) as X + Y + Z Compute Average (A) as

S / 3 Compute Product (P) as

X x Y x Z

Flowchart Symbols

Terminator : An oval flow chart shape indicates the start or end of the process, usually containing the word “Start” or “End”.

Process: A rectangular flow chart shape indicates a normal/generic process flow step.

Process

Flowchart Symbols

Decision: A diamond flow chart shape indicates a branch in the process flow. This symbol is used when a decision needs to be made, commonly a Yes/No question or True/False test.

Data: A parallelogram that indicates data input or output

(I/O) for a process.

Decision

Input / output

Flowchart Symbols

Connector: A small, circular flow chart shape used to indicate a jump in the process flow. Connectors are generally used in complex or multi-sheet diagrams.

Arrow: used to show the flow of control in a process.

Basic Flowchart

Example 1

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

Example 1

START

Input M1,M2,M3,M4

GRADE←(M1+M2+M3+M4)/4

IS GRADE<50

PRINT “FAIL”

STOP

Y N

PRINT “PASS”

Example 2

Finding the largest number between A and B

Solution #1

Algorithm :

Read A, B

If A is less than B Write B Else

write A endif

START

Read A ,B

A >B

Write B

STOP

Y N

Write A

Flowchart

Solution #2

Algorithm :

Read A, B Let MAX = A

If MAX is less than B MAX = B

Write (Display) MAX

Flowchart

START

Read A ,B

MAX =A

MAX < B

Write MAX

STOP

Y N

MAX =B

Solution #3

ALGORITHM Step 1: Input VALUE1, VALUE2 Step 2: if (VALUE1 > VALUE2) then MAX ← VALUE1 else MAX ← VALUE2 endif Step 3: Print “The largest value is”, MAX

Solution #3

MAX ← VALUE1

STOP

Y N

START

Input VALUE1,VALUE2

MAX ← VALUE2

is VALUE1>VALUE2

Print “The largest value

is”, MAX

Four Flowchart Structures

Sequence Decision Repetition Case

Sequence Structure

A series of actions are performed in sequence

Decision Structure

One of two possible actions is taken, depending on a condition. If the answer to the

question is yes, the flow follows one path. If the answer is no, the flow follows another path

YES NO

Decision Structure

The question “is x < y?” is asked. If the answer is no, then process A is performed. If the answer is yes, then process B is performed.

YES NO x < y ?

Process B Process A

Decision Structure

The flowchart segment below shows a decision structure with only one action to perform. It is expressed as an if statement in C++ code.

YES NO x < y ?

Calculate a as x times 2.

C++ Code

if (x < y)

a = x * 2;

Flowchart

Repetition Structure A repetition structure represents

part of the program that repeats. This type of structure is commonly known as a loop.

Notice the use of the diamond symbol . A loop tests a condition, and if the condition exists, it performs an action. Then it tests the condition again. If the condition still exists, the action is repeated. This continues until the condition no longer exists.

Repetition Structure

The flowchart segment below shows a repetition structure expressed in C++ as a while loop.

x < y? Add 1 to x

YES while (x < y)

x++;

Flowchart C++ Code

Case Structure

One of several possible actions is taken, depending on the contents of a variable.

CHAPTER 2

A SIMPLE C++ PROGRAM Before looking at how to write C++ programs consider the following simple example

program

The previous program is the typical program that programmer apprentices write for the first time, and its result is the printing on

screen of the "Hello World!" sentence. It is one of the simplest programs that can be written in C++, but it already contains the fundamental components that every C++ program has. We are going to look line by line at the code we have just written:

A SIMPLE C++ PROGRAM

// my first program in C++ This is a comment line. All lines beginning with two slash signs (//) are considered

comments and do not have any effect on the behaviour of the program. The programmer can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is.

#include <iostream> Lines beginning with a hash sign (#) are directives for the preprocessor .

In this case the directive #include<iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.

A SIMPLE C++ PROGRAM

using namespace std; All the elements of the standard C++ library are

declared within what is called a namespace. int main () This line corresponds to the beginning of the definition

of the main function. The word main is followed in the code by a pair of parentheses (()).

A SIMPLE C++ PROGRAM

Using namespace std

cout is part of the standard library, and all the elements in the standard C++ library are declared within what is a called a namespace: the namespace std .

cout << "Hello World!"; cout represents the standard output stream in C++. Notice that

the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs.

return 0; The return statement causes the main function to finish.

A SIMPLE C++ PROGRAM

We could have written:

int main () { cout << "Hello World!"; return 0; }

All in just one line and this would have had exactly the same meaning as the previous code. In C++, the separation between statements is specified with an ending semicolon (;) at the end of each one, so the separation in different code lines does not matter at all for this purpose. We can write many statements per line or write a single statement that takes many code lines. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it.

VARIABLES

A variable is a symbolic name for a memory location in which data can be stored and subsequently recalled. Variables are used for holding data values so that they can be utilized in various computations in a program. All variables have two important attributes: A type which is established when the variable is defined (e.g., integer, real, character). Once defined, the type of a C++ variable cannot be changed. A value which can be changed by assigning a new value to the variable. The kind of values a variable can assume depends on its type. For example, an integer variable can only take integer values (e.g., 2, 100, -12).

IDENTIFIERS

Identifiers are names given to variables which distinguish them from all other variables.

The rules of C++ for valid identifiers state that:

An identifier must:

start with a letter

consist only of letters, the digits 0-9, or the underscore symbol _ Not be a reserved word.

The following are valid identifiers:

Length, days_in_year, DataSet1, Profit95, _Pressure, first_one, first_1 although using _Pressure is not recommended.

The following are invalid:

days-in-year 1data int first.val throw Note : C++ is case-sensitive

Fundamental data types

They can mainly be classified into:

• Character types: They can represent a single character, such as 'A' or '$' . • Numerical integer types: They can store a whole number value, such as ۷ or ۱۰۲٤. They exist in a variety of sizes, and can either be signed or unsigned, depending on whether they support negative values or not . • Floating-point types: They can represent real values, such as ۳٫۱٤ or ۰٫۰۱, with different levels of precision, depending on which of the three floating-point types is used . • Boolean type: The boolean type, known in C++ as bool, can only represent one of two states, true or false .

Example

int a, b, c;

int a; int b; int c;

which declares integer variables i, j and count,

real variables sum and product,

a character variable ch, and a boolean variable pass_exam

=

int i, j, count;

float sum, product;

char ch;

bool passed_exam;

Initialization of variables

int a = 0;

int a (0);

int a {0};

By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs). cout << "Output sentence"; // prints Output sentence on screen

cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout. Notice that the sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names. For example, these two sentences have very different results: cout << "Hello"; // prints Hello

cout << Hello; // prints the content of Hello variable

Standard Output (cout)

Example

Multiple insertion operations (<<) may be chained in a single statement:

cout << "This " << " is a " << "single C++ statement";

This last statement would print the text This is a single C++ statement. Chaining insertions is especially useful to mix literals and variables in a single statement :

cout << "I am " << age << " years old ";

cout << "First sentence.\n"; cout << "Second sentence.\nThird sentence.";

cout << "First sentence." << endl; cout << "Second sentence." << endl;

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example: int age;

cin >> age;

Standard Input (cin)

cin >> a >> b;

= cin >> a; cin >> b;

Escape Codes:

\n newline

\t tab

\v vertical tab

\a alert (beep)

\' single quote (')

\" double quote (")

\? question mark (?)

\\ backslash (\)

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

// operating with variables #include <iostream> using namespace std; int main () { // declaring variables: int a, b; int result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result<<‘\n’; // terminate the program: return 0;

}

Example 1

Introduction to strings

string mystring = "This is a string"; string mystring ("This is a string");

// my first string #include <iostream> #include <string> using namespace std; int main () { string mystring; mystring = "This is the initial string content"; cout << mystring <<‘\a’<< endl; mystring = "This is a different string content"; cout << mystring <<‘\t’<< endl; return 0; }

Example 2

CONSTANTS constants can be declared in two different ways: using the #define preprocessor directive, and through use of the const keyword

#define identifier value

#define PI 3.14159 #define NEWLINE '\n'

This defines two new constants: PI and NEWLINE.

const double pi = 3.14159 const char newline = ‘\n’

Example 3

// defined constants: calculate circumference #include <iostream> using namespace std; #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; }

Example 9

Write a program that will find and print the Sum & Difference of 2 numbers .

Example 10

Write a complete program that will find and print a correct average of 3 numbers .