Programming Fundamentals 3 rd lecture Szabolcs Papp.

Slides:



Advertisements
Similar presentations
Chapter 9 – One-Dimensional Numeric Arrays. Array u Data structure u Grouping of like-type data u Indicated with brackets containing positive integer.
Advertisements

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Computer Science 1620 Loops.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
Computer Science 1620 Programming & Problem Solving.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
Introduction to Programming (in C++) Introduction Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
CSC 8310 Programming Languages Meeting 2 September 2/3, 2014.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 12: How Long Can This Go On?
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
26 Sep 2014Lecture 3 1. Last lecture: Experimental observation & prediction Cost models: Counting the number of executions of Every single kind of command.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to algorithmic problem solving
Programming Fundamentals 9 th lecture Szabolcs Papp.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Fundamentals 5 th lecture Szabolcs Papp.
Programming Fundamentals 6 th lecture Szabolcs Papp.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
CSIS 113A Lecture 5 Random Numbers, while, do-while.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Application: Correctness of Algorithms Lecture 22 Section 4.5 Fri, Mar 3, 2006.
CS101 Computer Programming I Chapter 4 Extra Examples.
Control Structures Repetition or Iteration or Looping Part II.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Programming Fundamentals 2 nd lecture Szabolcs Papp.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Homework #2: Functions and Arrays By J. H. Wang Mar. 20, 2012.
Overview Go over parts of quiz? Another iteration structure for loop.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
1 CS161 Introduction to Computer Science Topic #8.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
1 10/3/05CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Programming Fundamentals 8 th lecture Szabolcs Papp.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Vectors Jordi Cortadella Department of Computer Science.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
int [] scores = new int [10];
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
ALGORITHMS AND FLOWCHARTS
REPETITION CONTROL STRUCTURE
Data Structures and Algorithms
C++ Basic Syntax – Homework Exercises
CS 213: Data Structures and Algorithms
Arrays, For loop While loop Do while loop
One-Dimensional Array Introduction Lesson xx
Chapter 6: Repetition Statements
Presentation transcript:

Programming Fundamentals 3 rd lecture Szabolcs Papp

ELTE /41  Loops – specification+algorithm+coding Loops  First example for arrays First example for arrays  The array The array  Array instead of conditional statement Array instead of conditional statement  Constant arrays Constant arrays Content

ELTE /41 Loops Problem: Let’s calculate the non-1 least divisor of and integer (N>1)! Specification:  Input: N:Integer  Output: D:Integer  Precondition: N>1  Post condition: 1<D  N and D|N and  i (2  i<D): i ł N

ELTE /41 Loops An idea for solution: Let’s try 2; if not good then try 3; if still not good then try 4, …, worst case N will be a divisor! Algorithm expressing this: i:=2 i ł N i:=i+1 D:=i

ELTE /41 Loops Problem: Let’s calculate both the non-1 least and the non-N greatest divisor of an integer (N>1)! Specification:  Input: N:Integer  Output: LD,GD:Integer  Precondition: N>1  Post condition: 1<LD  N and 1  GD<N and LD|N and  i (2  i<LD): i ł N and GD|N and  i (GD<i<N): i ł N

ELTE /41 Loops Note: By knowing LD, GD can be definied in post condition in another way: LD*GD=N! Algorithm expressing this: i:=2 i ł N i:=i+1 LD:=I GD:=N Div LD

ELTE /41 Loops Problem: Let’s calculate the non-1 and non-N least divisor of and integer (N>1), if exists! Specification :  Input: N:Integer  Output: D:Integer, EXISTS:Boolean  Precondition: N>1  Post condition: EXISTS=  i (2  i<N): i|N and EXISTS  D|N and 2  D<N and  i (2  i<D): i ł N

ELTE /41 Loops Algorithm: Note: Whenever i is a divisor of N, then ( N Div i) is also a divisor, so we are good to go until the square root of N! i:=2 i<N and i ł N i:=i+1 EXISTS:=i<N EXISTS D:=i  I N 2  i  N Div i  N Div 2 thus i*i  N thus i  N

ELTE /41 Loops Problem: Let’s calculate the sum of all the divisors of an integer (N>1)! Specification:  Input: N:Integer  Output: S:Integer  Precondition: N>1  Post condition:

ELTE /41 Loops Algorithm: S:=0 i=1..N i|N S:=S+i  I N

ELTE /41 Loops Problem: Let’s calculate the sum of all odd divisors of an integer (N>1)! Specification:  Input: N:Integer  Output: S:Integer  Precondition: N>1  Post condition: S=

ELTE /41 Algorithm 1 : Algorithm 2 : Loops S:=0 i=1..N i|N és odd(i) S:=S+i  S:=0 i=1..N; by 2 i|N S:=S+i  I N I N

ELTE /41 Loops Problem: Let’s calculate the sum of all prime divisors of an integer (N>1)! Specification:  Input: N:Integer  Output: S:Integer  Precondition: N>1  Post condition: S= isprime(i)???

ELTE /41 Loops Algorithm: The least divisor is prime for sure; let’s divide N by it as many times as we can; the next divisor of the reduced N will be prime again. S:=0 i:=2 iNiN i|N S:=S+i  i|N N:=N Div i i:=i+1 I N

ELTE /41 Loops Problem: Let’s determine the count of i,j (i,j>1) integer pairs, where i*j<N! Specification:  Input: N:Integer  Output: S:Integer  Precondition: N>1  Post condition: S=

ELTE /41 Loops S:=0 i=2..N Div 2 j=2..N Div 2 i*j<N S:=S+1  Algorithm 1 : I N

ELTE /41 Loops S:=0 i=2..N Div 2 j:=2 i*j≤N S:=S+1 j:=j+1 Algorithm 2 : Algorithm 3 : S:=0 i=2..N Div 2 S:=S+(N Div i)-1

ELTE /41 Loops Let’s observe that:  If there is , , or  sign in post condition, then the solution always contains loop!  If there is  or  sign in post condition, then the solution is mostly a conditional loop!  If there is  sign in post condition, then the solution is mostly a for loop! (  also)  In case of two embedded  signs, we will have two for loops embedded in each other.  In case of conditional , there will be a conditional statement within the loop.

ELTE /41 Loops algorithm – code Conditional loop: For loop: condition statement while (condition){ statements } i=1..N statement for (int i=1;i<=N;i++){ statements } i=1..N; by x statement for (int i=1;i<=N;i+=x){ statements } statement condition do{ statement }while (condition) Typical usage at console inputs (see 2 nd lecture) 2 nd lecture2 nd lecture

ELTE /41 Sample exercise for conditional statement, or do we need something else ? Problem: The Japanese calendar contains 60 years cycles. The years are paired, and a color is assigned to each pair (green, red, yellow, white and black). o 1,2,11,12, …,51,52: green years o 3,4,13,14,…,53,54: red years o 5,6,15,16,…55,56: yellow years o 7,8,17,18,…57,58: white years o 9,10,19,20,…,59,60: black years We know that the last cycle has started in 1984 that will end in Let’s write a computer program which determines the color assigned to a given M year (1984≤M≤2043)!

ELTE /41 Conditional statement or do we need something else ? Specification 1 :  Input year:Integer  Output: c:Color  Precondition: 1984≤year and year≤2043  Post cond. ((year-1984) Mod 10) Div 2=0 and c=”green” or ((year-1984) Mod 10) Div 2=1 and c=”red” or …  Definition: Color:=(”green”,”red”, ”yellow”,”white”, ”black”)  Text This is still an “unknown” set. We define the set Color, which is derived from Text

ELTE /41 Conditional statement or do we need something else ? Specification 2 :  Input: year:Integer  Output: c:Color Color=(”green”,”red”,”yellow”, ”white”,”black”)  Text  Precondition: 1984≤year and year≤2043  Post cond: ((year-1984) Mod 10) Div 2=0 and c=”green” or ((year-1984) Mod 10) Div 2=1 and c=”red” or … We can define Color set here, too

ELTE /41 Conditional statement or do we need something else ? y:=((year-1984) Mod 10) Div 2 y=0y=1y=2y=3y=4 sc:= ”green” s:= ”red” s:= ”yellow” s:= ”white” s:= ”black” Question: Would we do the same if we had 90 ways instead of 5? Before answering this, a new structure: array Algorithm:

ELTE /41 Arrays Related concepts:  Sequence: a countable sequence of same typed data elements  Array: finite length sequence, we can define operations for i th element (we know the least and the greatest index, or the count).  Index: sometimes 1..N, sometimes 0..N–1.  Operations on elements of an array: reference to an element, modification of an element (the element is selected by a given index).

ELTE /41 Arrays (in algorithm) Examples for declaration: X:Array[1..N:Integer] Y:Array[0..4:Text] We can represent the Color set from the previous example with a constant array: Constant Color:Array[0..4:Text]= (”green”,”red”,”yellow”,”white”,”black”) Examples for referencing: X[1]:=X[N]; Y[i]:=Color[0]

ELTE Declaration: X:Array[1..N:Integer] Y:Array[0..4:Text] We can represent the Color set from the previous example with a constant array: Constant Color:Array[0..4:Text]= (”green”,”red”,”yellow”,”white”,”black”) /41 Arrays (in algorithm and code) string Y[5] const string Color[5]={"green","red", "yellow","white","black"}; int X[N+1] Tömb-elemszám  indexelés 0..N index 0..???  count of elements in C++ :

ELTE /41 Arrays (C++ code – overview) Static arrays:  Declaration:  References : const int MaxN=???;//maxcount type array[MaxN]; //array declaration //with indices 0..MaxN-1 … … array[ind] //reference to an element … array[ind]=expr;//modification of elem. … This is a difference between usual algorithm and code!

ELTE /41 Arrays (C++ code – overview) Static array constants:  Declaration: or const int N=???;//number of elements const type array[N]={t1,t2,…,tN}; //declaration of constant array, //with indices 0..N-1 const type array[]={t1,t2,…,tN}; //declaration of const. array const int N=sizeof array/sizeof(type); //number of elements //indices: 0..N-1 Note that syntax is different in case of identifiers and types!

ELTE /41 Arrays (C++ code – overview) Array variables:  Declaration:  Creation:  References (the same) : int N; //actual number of elements … N=???;//N to be defined, e.g. input type array[N];//an array containing N //elements with type “type” … array[ind] //reference to an element … array[ind]=expr;//modification of elem. …

ELTE /41 Array input (with check) : bool err; //is there an error? … ! do{ cout > N; err=!IsCorrectN(N); if (err) { cout << „error message" << endl; } }while (err); bool err; //is there an error? … ! do{ cout > N; err=!IsCorrectN(N); if (err) { cout << „error message" << endl; } }while (err); IsCorrectN does both syntax and semantic check Arrays (C++ code – overview) In algorithm: Input: N [IsCorrectN(N))]

ELTE Array input (with check) : Let’s get back to our question… bool err; //is there an error? … ! do{ cout > N; err=!IsCorrectN(N); if (err) { cout << „error message" << endl; } }while (err); bool err; //is there an error? … ! do{ cout > N; err=!IsCorrectN(N); if (err) { cout << „error message" << endl; } }while (err); /41 for (int i=0;i > v[i]; err=!Correct(v[i]); if (err) { cout > v[i]; err=!Correct(v[i]); if (err) { cout << "hibaüzenet" << endl; }; }while (hiba); } In algorithm: Input: v(1..N) [Helyes(v(1..N))] Correct does both syntax and semantic check Arrays (C++ code – overview)

ELTE /41 Array instead of conditional statement Specification:  Input: year:Integer  Output: c:Color Color=(”green”,”red”,”yellow”, ”white”,”black”)  Text Constant Colors:Array[0..4:Color]= (”green”,”red”,”yellow”,”white”,”black”)  Precondition: 1984≤year and year≤2043  Post condition: c=Colors[((year-1984) Mod 10) Div 2]

ELTE /41 Array instead of conditional statement Algorithm: y:=((year-1984) Mod 10) Div 2 c:=Colors[y]

ELTE /41 Applying constant arrays Problem: Let’s create a computer program, which writes an integer between 1 and 99 with letters! Specification:  Input: N:Integer Constant ones:Arrays[0..19:Text]= (””, ”one”,…,”nineteen”) Constant tens: Array[2..9:Text]= (”twenty”,…,”ninety”)  Output: S:Text  Preconditon: 1  N  99 This is a better place here. Constant array is an output from the point of view of the algorithm.

ELTE /41 Applying constant arrays  Post condition: N<20  S=ones[N] and N≥20  S=tens[N Div 10]+ ones[N Mod 10] Algorithm: N<20otherwhise S:=ones[N]S:=tens[N Div 10]+ ones[N Mod 10]

ELTE /41 Applying constant arrays Problem: Let’s create a computer program that writes the serial number of a month based on the name of the month. Specification:  Input: H:Text Constant MonName:Array[1..12:Text]= (”January”,…,”December”)  Output: S:Integer  Precondition: M  MonName  Post cond.: 1  S  12 and MonName[S]=M

ELTE /41 Algorithm: Question: What would happen if we didn’t meet the precondition? Runtime error? Infinite loop? Applying constant arrays i:=1 MonName[i]  M i:=i+1 S:=i

ELTE /41 Constant arrays – What do we store? Problem: We have a non leap year. What is the serial number of a given day (month, day)? Specification 1 :  Input: M,D:Integer Constant mon:Array[1..12:Integer]= (31,28,31,…,31)  Output: S:Integer  Precondition: 1≤M≤12 és 1≤D≤mon[M]  Post condition:

ELTE /41 Constant arrays – What do we store? Algorithm: Homework: How to modify this if we allow leap year? S:=D i=1..M–1 S:=S+mon[i]

ELTE /41 Constant arrays – What do we store? Another solution: For each months, l et’s store the total number of days preceding the given month! Specification 2 :  Input: … Constant mon:Array[1..12:Integer]= (0,31,59,90,…,334)  Post condition: S=D+mon[M] Question: Is it a better solution? How do we express the precondition?

Programming Fundamentals End of 3 rd lecture