Fundamentals of Structured Programming

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

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

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Programming with C++ as a Second Language

Ch 1. Algorithms and Basic C++ Programming

CSCI 1061U Programming Workshop 2. C++ Basics

CS110: PROGRAMMING LANGUAGE I

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

IS 0020 Program Design and Software Tools

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

Computer Programming : C++

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

2 nd Week Lecture Notes

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

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

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

Chapter 2. C++ Basics

Chapter 2: Basic Elements of C++

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

Scientific Computing

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Computer Science II Lecture 1 Introduction and Background

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

Chapter 1 Introduction to Computers and C++ Programming

Problem Solving With C++ Ninth Edition

B. Subject-specific skills B1. Problem solving skills: Supply the student with the ability to solve different problems related to the topics

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

CE221 Programming in C++ Part 1 Introduction

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

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

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Partha Sarathi Mandal

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

Introduction to Programming using C++

COMP322 - Introduction to C++ Lecture 01 - Introduction

Object Oriented Design

Absolute C++ Walter Savitch

CSI33 Data Structures

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

Chapter 2 Basic Elements of C++

Chapter 2. Outline. Simple C++ Programs

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

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Fundamentals of Programming CS-110. Lecture 2

UNIT- 3 Introduction to C++

Objectives. In this chapter, you will:

Introduction to Programming

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

The C++ Language. Arizona State University 1

Introduction to C++ (Extensions to C)

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Programming. C++ Basics

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

A First Program - Greeting.cpp

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Full file at

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

CSCI 123 Introduction to Programming Concepts in C++

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Topic 2: C++ Programming fundamentals

EC 413 Computer Organization

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Input And Output of C++

Lecture 2 Tao Wang 1

CSCE 110 PROGRAMMING FUNDAMENTALS

Lesson 2 Variables and I/O

(0) introduction to the course. how to learn a programming language. (0) course structure

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

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

Dr. Md. Humayun Kabir CSE Department, BUET

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

Basic Computer Programming for ISNE. Santi Phithakkitnukoon ผศ.ดร.ส นต พ ท กษ ก จน ก ร

CSc Introduction to Computing

KOMAR UNIVERSITY OF SCIENCE AND TECHNOLOGY (KUST)

CS242 COMPUTER PROGRAMMING

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

From Pseudcode Algorithms directly to C++ programs

Decaf Language Reference Manual

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

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

Getting started with C++ (Part 2)

Chapter 2: Data and Expressions

A Freshman C++ Programming Course

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Crash Course into. Prof. Dr. Renato Pajarola

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

Week 1: Hello World! Muhao Chen

Fast Introduction to Object Oriented Programming and C++

Computer Programming. Dr. Fahad Computer Science Deptt.

Chapter 2: Introduction to C++

CS201 - Introduction to Programming Glossary By

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Information Science 1

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

Transcription:

Fundamentals of Structured Programming Dr. Salma Hamdy s.hamdy@cis.asu.edu.eg 1

Course Logistics Staff Teachers Prof. Mohamed Roushdy (Dean) Dr. Salma Hamdy Contact: s.hamdy@cis.asu.edu.eg Office: FCIS, 3 rd floor, glass room. Office hours: Tuesday 11:00-13:00 Course page Wednesday 11:00-13:00 http://piazza.com/faculty_of_computer_and_information_sciences/sp ring2013/csw150 Access Code: CSW150 2

Course Logistics General Class meets: Tuesday 8:00-11:00 Wednesday 8:00-11:00 Lab meets: check your schedule! :-p (3-hour lecture + 2-hour lab) a week. Assessment (125 points) Final Term Examination 90 Oral Discussion 10 Practical Examination 15 Mid Term + Assignments 10 YOUR JOB read + think + code = HW + lab tasks + exams 3

Course Logistics Textbook C++ How to Program, 8th edition, Deitel & Deitel, Prentice Hall- Pearson Education International, 2012. References Problem Solving with C++, 8th edition, Walter Savitch, Addison Wesley-Pearson Education International, 2012. Object Oriented Programming in C++, 4th edition, Robert Lafore, Pearson Education, 2002. Internet: ENDLESS list. 4

Course Logistics Ethics Lecture 1. Time management 2. Attendance 3. Manners 4. Mind + hands (if possible) 5. Your rights. 6. My rights. 7. Questions Lab 1. Time management 2. Attend ONLY in your class. 3. Manners 4. Mind + hands (BOTH!!!) 5. Your rights. 6. TA s rights. 7. Questions Cheating and copied assignments, programs, projects, or code segments, will not be tolerated. 5

Course Logistics Outline 1. Introduction 2. Basics 3. Control Structures 4. Arrays and Structures 5. Pointers and Dynamic Arrays 6. Functions 7. Parameters, Overloading, and Reference 8. Recursion 9. Strings 10.Streams and File I/O 6

Course Logistics Outcomes During and upon the completion of this course, you will: - Have a basic understanding of structured programming concepts and how computers understand your code. - Know how to design, analyze, and code simple and sophisticated programs using C++ language that execute efficiently. - Make use of simple data structures, linear algebra, and other knowledge to solve real problems. - Require substantial programming and good software engineering practice. - Develop and deploy a C++ application of your own design. - Meet deadlines and be a team player. - Be able to present your work and describe your solutions. 7

Announcement ONLY next week s lectures isa will be switched with the electronics lectures. Programming: Sunday Feb 17 th, 8:00-11:00 Group 2 Monday Feb 18 th, 8:00-11:00 Group 1 Electronics: Tuesday Feb 19 th, 8:00-11:00 Group 1 Wednesday Feb 20 th, 8:00-11:00 Group 2 8

Review 9

Contents 1. Problem Solving 2. Computer Programs 3. C++ Programming (Basics) 10

Why Programming? 1... 2... 3... 11

1. Problem Solving Steps of Solving a Problem: 1. Define the problem Understand input and output Change the problem Simplify the problem 12

1. Problem Solving (cont.) Steps of Solving a Problem: 1. Define the problem 2. Design a solution How to reach output from input Plan a solution List steps of solution Analysis Algorithm 13

1. Problem Solving (cont.) An algorithm is a procedure for solving a problem in terms of the actions to be executed and the order in which those actions are to be executed. An algorithm is merely the sequence of steps taken to solve a problem. The steps are normally "sequence," "selection, " or "iteration," statements. 14

1. Problem Solving (cont.) A pseudo code is a kind of structured English for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax. The pseudocode needs to be complete. It describes the entire logic of the algorithm so that implementation becomes a task of translating line by line into source code. 15

1. Problem Solving (cont.) Pseudo code common format NOT a language syntax 16

1. Problem Solving (cont.) Pseudo code common format NOT a language syntax 17

1. Problem Solving (cont.) Example 1: Student pass? 18

1. Problem Solving (cont.) Example 1: Student pass? 1. GET Grade 2. If Grade is greater than or equal to 60 THEN 3. Print "passed" 4. ELSE 5. Print "failed" 19

1. Problem Solving (cont.) Example 2: Average of ten grades 20

1. Problem Solving (cont.) Example 2: Average of ten grades 1. SET Total to zero 2. SET Grade Counter to one 3. WHILE Grade Counter is less than or equal to ten THEN 4. GET the Next Grade 5. ADD the Next Grade to the Total 6. SET the Class Average to the Total divided by ten 21

1. Problem Solving (cont.) A flowchart is diagram of the steps you will use to reach your goal (steps of the algorithm). Various standard shapes. 22

1. Problem Solving (cont.) Example 1: Student pass Example 2: Average of ten grades 23

1. Problem Solving (cont.) Steps of Solving a Problem: 1. Define the problem. 2. Design a solution. 3. Test on sample data trace + debug Logical Errors 24

1. Problem Solving (cont.) Steps of Solving a Problem: 1. Define the problem. 2. Design a solution. 3. Test on sample data trace + debug ---------------- 4. Implement the algorithm Programming Language 25

1. Problem Solving (cont.) Steps of Solving a Problem: 1. Define the problem. 2. Design a solution. 3. Test on sample data trace + debug ---------------- 4. Implement the algorithm 5. Test on real data run Programming Language 26

1. Problem Solving (cont.) Steps of Solving a Problem: 1. Define the problem. WHY? 2. Design a solution. 3. Test on sample data trace + debug ---------------- 4. Implement the algorithm 5. Test on real data run Programming Language 27

1. Problem Solving (cont.) Example 1 Calculate the area of a circle given its radius. Example 2 Convert degrees from Fahrenheit to Celsius according to C = 5(F 23)/9 28

1. Problem Solving (cont.) 29

1. Problem Solving (cont.) Can we hire someone to do the job? An expert maybe Or even better, can we automate the job? 30

2. Computers Programs Computers = devices (HW) that can perform computations and make logical decisions phenomenally faster than human beings can. They process data under the control of sets of instructions called computer programs (SW). 31

2. Computers Programs (cont.) Computer Organization Memory unit Input unit ALU Output unit CPU Secondary Storage 32

2.1 Programming Languages Talking to your Computer 1- Machine Language - Directly understandable by computer. - String of numbers (1s and 0s) - Machine dependant. - Too tedious for programmer. - Too many instructions. 33

2.1 Programming Languages (cont.) Talking to your Computer 1- Machine Language 1- Assembly Language - English-like abbreviations. - Requires assembler. - Still too many instructions. 34

2.1 Programming Languages (cont.) Talking to your Computer 1- Machine Language 1- Assembly Language 3- High Level Language 35

2.1 Programming Languages (cont.) Talking to your Computer 1- Machine Language 1- Assembly Language 3- High Level Language C++, C, Microsoft s.net languages (e.g., Visual Basic, Visual C++ and Visual C#) and Java 36

2. Computers Programs (cont.) Programming Techniques Unstructured Programming Procedural Programming Modular Programming Object Oriented Programming Logic Programming 37

2.2 Programming Techniques (cont.) Unstructured Programming One main program. A sequence of commands or statements, which modify data that is global throughout the whole program. Disadvantages. 38

2.2 Programming Techniques (cont.) Procedural Programming A single program, which is divided into small pieces called procedures. Combine returning sequences of statements into one single place. A procedure call is used to invoke the procedure. Use a procedure in another program? 39

2.2 Programming Techniques (cont.) Modular (Structured) Programming Procedures of a common functionality are grouped together into separate modules. Program is now divided into several smaller parts which interact through procedure calls. Each module can have its own data. This allows each module to manage an internal state. One state per module. 40

Spaghetti code Courtesy of Dr. Mohamed Samy 41

2.2 Programming Techniques (cont.) Object Oriented Programming (OOP) Treat data and the procedures that act upon the data as a single "object"--a selfcontained entity with an identity and certain characteristics of its own. Encapsulation Data Hiding Inheritance Polymorphism 42

2.2 Programming Techniques (cont.) Logical Programming Focus on telling the system what to do, rather than how to do it. Describe problems in a declarative manner (versus procedural). Clues: Facts and rules. Solve problems by asking questions. Deductive reasoning and Predicate logic. 43

2. Computers Programs (cont.) C++ Development Environment C++ programs consist of pieces called classes and functions. Even if you don t follow the OOP approach, you will still take advantage of the rich collections of classes and functions in the C++ Standard Library. 44

2. Computers Programs (cont.) C++ Development Environment 1- Creating Program - Source code - Popular IDEs: Microsoft Visual Studio 2010 Express Edition, Dev C++, NetBeans, Eclipse. 2- Preprocessing - Automatically - Preprocessor directives 45

2. Computers Programs (cont.) C++ Development Environment 3- Compiling - Object code 4- Linking - Object code to needed parts 46

2. Computers Programs (cont.) C++ Development Environment 5- Loading - With other needed libraries. 6- Executing - One instruction at a time. 47

3. C++ Programming 48

3. C++ Programming (cont.) Libraries and namespaces 49

3. C++ Programming (cont.) Libraries and namespaces functions 50

3. C++ Programming (cont.) Libraries and namespaces functions Input/output 51

3. C++ Programming (cont.) Libraries and namespaces functions Variables Input/output 52

3. C++ Programming (cont.) Libraries and namespaces functions Variables Input/output Control Structure 53

Variables - Declaration C++ Identifiers Keywords/reserved words vs. Identifiers Case-sensitivity and validity of identifiers Meaningful names! Variables A memory location to store data for a program Must declare all data before use in program VARIABLE NAMING RULES 54

Variables Data Types 55

Variables Data Types 56

Variables - Assignment Initializing data in declaration statement Results "undefined" if you don t! int myvalue = 0; Assigning data during execution Lvalues (left-side) & Rvalues (right-side) Lvalues must be variables Rvalues can be any expression Example: distance = rate * time; Lvalue: "distance" Rvalue: "rate * time" 57

Variables - Assignment C++ offers some shorthand notations in assignment statements. Incrementing a variable: var = var+1; Shorthand increment operator: var++; Or ++var; Decrementing a variable: var= var-1; Shorthand decrement operator: var--; Or --var; 58

Variables - Assignment Assigning Data: Shorthand Notations 59

Variables - Assignment Are we allowed to declare a variable of some type and assign to it a value of a different type? Yes! And No! 60

Variables - Assignment Compatibility of Data Assignments Type mismatches General Rule: Cannot place value of one type into variable of another type intvar = 2.99; // 2 is assigned to intvar! Only integer part "fits", so that s all that goes Called "implicit" or "automatic type conversion" 61

Variables Type Casting Two types Implicit also called "Automatic" Done FOR you, automatically 17 / 5.5 This expression causes an "implicit type cast" to take place, casting the 17 17.0 Explicit type conversion Programmer specifies conversion with cast operator (double)17 / 5.5 Same expression as above, using explicit cast (double)myint / mydouble More typical use; cast operator on variable 62

Literals Literals Examples: 2 5.75 "Z" "Hello World" // Literal constant int // Literal constant double // Literal constant char // Literal constant string Considered constants: Cannot change values during execution Called "literals" because you "literally typed" them in your program! 63

Constants Naming your constants Literal constants are "OK", but provide little meaning e.g., seeing 24 in a pgm, tells nothing about what it represents Use named constants instead Meaningful name to represent data const int NUMBER_OF_STUDENTS = 24; Called a "declared constant" or "named constant" Now use it s name wherever needed in program Added benefit: changes to value result in one fix 64

65

Arithmetic Operators Standard Arithmetic Operators Precedence rules standard rules 66

Arithmetic Operators Standard Arithmetic Operators Precedence rules standard rules 67

Relational Operators Comparing Expressions 68

Boolean Expressions Recall that declaring a variable allocates memory for that variable s specific type. Arithmetic types include int and float. Symbolic types include char and string. Another type is the Boolean (only one byte) that is either true or false). 69

Boolean Expressions Data Types: true, false are predefined library constants 70

Boolean Expressions Be careful! In C++, 0 is false BUT any value other than 0 is considered true. For example: int x= 0; // Boolean false z-- >=3 int y = 1; // Boolean true 6==x+7 int z = 3; // Boolean true sum==x+y sum= x+y; //Boolean true y--; // Boolean false 71

Logical Operators Evaluating Boolean Expressions Logical Operators Logical AND (&&) Logical OR ( ) 72

Operators Operators Precedence 73

Display 2.3 Precedence of Operators (1 of 4) 2-74

Display 2.3 Precedence of Operators (2 of 4) 2-75

Display 2.3 Precedence of Operators (3 of 4) 2-76

Display 2.3 Precedence of Operators (4 of 4) 2-77

Console Input/output I/O objects cin, cout, cerr Defined in the C++ library called <iostream> Must have these lines (called pre-processor directives) near start of file: #include <iostream> using namespace std; Tells C++ to use appropriate library so we can use the I/O objects cin, cout, 78

Console Input/output cin for input, cout for output Differences: ">>" (extraction operator) points opposite Think of it as "pointing toward where the data goes" Object name "cin" used instead of "cout" No literals allowed for cin Must input "to a variable" cin >> num; Waits on-screen for keyboard entry Value entered at keyboard is "assigned" to num 79

Console Output What can be outputted? Any data can be outputted to display screen Variables Constants Literals Expressions (which can include all of above) cout << numberofgames << " games played."; 2 values are outputted: "value" of variable numberofgames, literal string " games played." Cascading: multiple values in one cout 80

Console Output Separating Lines New lines in output Recall: "\n" is escape sequence for the char "newline" A second method: object endl Examples: cout << "Hello World\n"; Sends string "Hello World" to display, & escape sequence "\n", skipping to next line cout << "Hello World" << endl; Same result as above 81

Console Output Formatting Numbers Formatting numeric values for output Values may not display as you d expect! cout << "The price is $" << price << endl; If price (declared double) has value 78.5, you might get: The price is $78.500000 or: The price is $78.5 We must explicitly tell C++ how to output numbers in our programs! 1-82

Console Output Formatting Numbers "Magic Formula" to force decimal sizes: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); These statements force all future cout ed values: To have exactly two digits after the decimal place Example: cout << "The price is $" << price << endl; Now results in the following: The price is $78.50 Can modify precision "as you go" as well! 1-83

Console Output Escape Sequences "Extend" character set Backslash, \ preceding a character Instructs compiler: a special "escape character" is coming Following character treated as "escape sequence char" 84

Display 1.3 Some Escape Sequences (1 of 2) 85

Display 1.3 Some Escape Sequences (2 of 2) 86

Libraries C++ Standard Libraries #include <Library_Name> Directive to "add" contents of library file to your program Called "preprocessor directive" Executes before compiler, and simply "copies" library file into your program file C++ has many libraries Input/output, math, strings, etc. 87

Namespaces Namespaces defined: Collection of name definitions For now: interested in namespace "std" Has all standard library definitions we need Examples: #include <iostream> using namespace std; Includes entire standard library of name definitions #include <iostream> using std::cin; using std::cout; Can specify just the objects we want 88

Adding Style to your Program Make programs easy to read and modify Comments, two methods: // Two slashes indicate entire line is to be ignored /*Delimiters indicates everything between is ignored*/ Both methods commonly used Indentation (arranging and spacing your lines of code) Identifier naming ALL_CAPS for constants lowertoupper for variables Most important: MEANINGFUL NAMES! Believe it or not, I reward these things! 89

3. C++ Programming (cont.) Libraries and namespaces functions Variables Input/output Control Structure 90

4. Examples 91

4. Examples (cont.) Take a number from user and display Number Squared Predecessor Successor Equivalent Character 3 9 2 4?? Write a program to take two numbers and divide them putting the integer and remainder results in separate variables. 92

4. Examples (cont.) 93

4. Examples (cont.) 94

5. References Textbook chapters 1, 2. Problem Solving with C++ chapters 1, 2. More on pseudo code: http://users.csc.calpoly.edu/~jdalbey/swe/pdl_std.html 95