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

Similar documents
2 nd Week Lecture Notes

Computer Programming : C++

Programming with C++ Language

FLOWCHARTS A flowchart is a graphical representation of the steps to be followed for solving problem. It consists of a set of symbols.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

A First Program - Greeting.cpp

Getting started with C++ (Part 2)

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CSc Introduction to Computing

Lecture 2 Tao Wang 1

Manual. Subject Code: CS593. Computer Science and Engineering

Lab # 02. Basic Elements of C++ _ Part1

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

C++ INDEX. Introduction: Instructions for use. Basics of C++: Structure of a program Variables. Data Types. Constants Operators Basic Input/Output

BITG 1233: Introduction to C++

Understanding main() function Input/Output Streams

CHAPTER 3 BASIC INSTRUCTION OF C++

4. Structure of a C++ program

Unit 1 : Principles of object oriented programming

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

IS 0020 Program Design and Software Tools

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 2: Basic Elements of C++

UEE1302 (1102) F10: Introduction to Computers and Programming

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Introduction to Programming

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

C++ Programming: From Problem Analysis to Program Design, Third Edition

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

1

Objectives. In this chapter, you will:

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

Computer Skills (2) for Science and Engineering Students

Chapter 2 C++ Fundamentals

The C++ Language. Arizona State University 1

Programming. C++ Basics

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Chapter 1 INTRODUCTION

Fundamentals of Programming CS-110. Lecture 2

CS242 COMPUTER PROGRAMMING

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Increment and the While. Class 15

Your First C++ Program. September 1, 2010

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Chapter 2 Basic Elements of C++

LECTURE 02 INTRODUCTION TO C++

Chapter 1 Introduction to Computers and C++ Programming

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.1

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Variables. Data Types.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

UNIT- 3 Introduction to C++

Creating a C++ Program

Introduction to the C++ Programming Language

CSCI 123 Introduction to Programming Concepts in C++

BASIC ELEMENTS OF A COMPUTER PROGRAM

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

CMPE110 - EXPERIMENT 1 * MICROSOFT VISUAL STUDIO AND C++ PROGRAMMING

EEE145 Computer Programming

CS102: Variables and Expressions

Introduction to Programming

A Freshman C++ Programming Course

REVIEW. The C++ Programming Language. CS 151 Review #2

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

This watermark does not appear in the registered version - Slide 1

1. In C++, reserved words are the same as predefined identifiers. a. True

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

6.096 Introduction to C++ January (IAP) 2009

Maciej Sobieraj. Lecture 1

Chapter 2: Overview of C++

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Basics of C++ // my first program in C++ Hello World! #include <iostream> using namespace std; int main () { cout << "Hello World!

download instant at Introduction to C++

Introduction to Programming using C++

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Introduction to Programming EC-105. Lecture 2

C: How to Program. Week /Mar/05

Fundamental of Programming (C)

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Transcription:

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: Step 2: Step 3: Input M1,M2,M3,M4 GRADE (M1+M2+M3+M4)/4 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. Decision Data: A parallelogram that indicates data input or output (I/O) for a process. 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 N IS GRADE<50 Y PRINT PASS PRINT FAIL STOP

Example 2 Finding the largest number between A and B

Solution #1 Algorithm : Flowchart START Read A, B Read A,B If A is less than B Write B Else write A N A >B Y endif Write B Write A STOP

Solution #2 Algorithm : Read A, B Let MAX = A Flowchart START Read A,B If MAX is less than B MAX = B MAX =A Write (Display) MAX N MAX < B Y MAX =B Write MAX STOP

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

Solution #3 START Input VALUE1,VALUE2 Y is VALUE1>VALUE2 N MAX VALUE1 MAX VALUE2 Print The largest value is, MAX STOP

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 NO YES

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. NO x < y? YES Process A Process B

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. Flowchart C++ Code NO x < y? YES if (x < y) a = x * 2; Calculate a as x times 2.

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. Flowchart C++ Code x < y? YES while (x < y) Add 1 to x x++;

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

A SIMPLE C++ 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 (()).

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.

A SIMPLE C++ PROGRAM 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.

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 i, j, count; float sum, product; char ch; bool passed_exam; which declares integer variables i, j and count, real variables sum and product, a character variable ch, and a boolean variable pass_exam int a, b, c; = int a; int b; int c;

Initialization of variables int a = 0; int a (0); int a {0};

Standard Output (cout) 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

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;

Standard Input (cin) 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; cin >> a >> b; = cin >> a; cin >> b;

Escape Codes: 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. \n newline \t tab \v vertical tab \a alert (beep) \' single quote (') \" double quote (") \? question mark (?) \\ backslash (\)

Example 1 // 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; }

Introduction to strings string mystring = "This is a string"; string mystring ("This is a string"); Example 2 // 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; }

CONSTANTS constants can be declared in two different ways: using the #define preprocessor directive, and through use of the const keyword #define identifier value This defines two new constants: PI and NEWLINE. #define PI 3.14159 #define NEWLINE '\n' 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.