Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

CSE 105 Structured Programming Language Presentation - 2
C Language.
Adapted from Scott, Chapter 6:: Control Flow Programming Language Pragmatics Michael L. Scott.
Communicating in Code: Layout and Style Programming Studio Spring 2009 Note: several examples in this lecture taken from The Practice of Programming by.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Chapter 10.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
. Welcome to PLAB. Course Staff Teacher:  Nir Friedman Teaching Assistants:  Yoseph Barash  Liad Blumrosen  Michael Okun.
COMP2004 Programming Practice Sam Holden Department of Computer Science University of Sydney.
Guide To UNIX Using Linux Third Edition
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
COP 3275 COMPUTER PROGRAMMING USING C Instructor: Diego Rivera-Gutierrez
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Programming Language C++ Xulong Peng CSC415 Programming Languages.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Best Practices. Contents Bad Practices Good Practices.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
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.
Copyright © Curt Hill Structured Data What this course is about.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Introduction to Programming
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
ATS Programming Short Course I INTRODUCTORY CONCEPTS Tuesday, Feb 10th, 2009 Introduction to Programming.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Programming Fundamentals Enumerations and Functions.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Welcome to C and Computer Structure #include int main() { printf ("hello class\n"); return 0; }
Introduction to C Programming I Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
From C to C++. 2 Why C++ is much more fun than C (C++ FAQ)? 1.Classes & methods - OO design 2.Generic programming - Templates allow for code reuse 3.Stricter.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Enum. enum – a new type 2 enum is a set of constant int values, that defines a type: enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,//
Chapter 15 - C++ As A "Better C"
Basic Data Types & Memory & Representation
Program style.
From C to C++.
Input and Output: I/O Finish reading chapters 1 and 2 of the text
Introduction to Computer Science / Procedural – 67130
C #include <stdio.h> int main() { printf ("hello class\n");
CSE 143 Introduction to C++ [Appendix B] 4/11/98.
From C to C++.
The Elements of Programming Style
Chapter 2: Introduction to C++.
An Overview of C.
Variables in C Topics Naming Variables Declaring Variables
C Structures and Commands
Standard Version of Starting Out with C++, 4th Edition
Enum.
Presentation transcript:

Welcome to Data Structures in C++

Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich

Communications 3 WWW: moodle Forums: Q & A – ask the staff about material. Exercises forums.

Course 4 1. ~4 programming exercises 2. Frontal exam

Books & Websites 5 Books: A list here: Recommended for the more advanced stuff: Scott Meyers “Effective” books (STL, C++). C++ FAQC++ FAQ – Explaining the complicated stuff, corners etc. C++ FQAC++ FQA – A bit lot more cynical & pragmatic view of the above

Program style

7 1. Take the time for it. Very important. If not followed your code will be “write only”. 2. Common sense 3. Read “real” coding guidelines document – will give you insight how important it is. e.g. good one from Microsoft or one from Google. MicrosoftGoogle Principles : 1. Readability 2. Common Sense 3. Clarity 4. Right focus

What’s in a name 8 Example #define ONE 1 #define TEN 10 #define TWENTY 20 More reasonable #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20

What’s in a name 9 Use descriptive names for global variables int npending = 0; // current length of input queue Naming conventions vary (style) numPending num_pending NumberOfPendingEvents Be consistent, with yourself and peers.

What’s in a name 10 Consider (wording) int noOfItemsInQ ; int frontOfTheQueue ; int queueCapacity ; … The word “queue” appears in 3 different ways Be consistent, with yourself and peers.

What’s in a name 11 Compare for( theElementIndex = 0; theElementIndex < numberOfElements; theElementIndex++ ) elementArray[theElementIndex] = theElementIndex; and for( i = 0; i < nelems; i++ ) elem[i] = i; Use short names for locals

What’s in a name 12 Use active name for functions now = getDate() Compare if( checkdigit(c) ) … to if( isdigit(c) ) … Accurate active names makes bugs apparent

Indentation 13 Use indentation to show structure Compare for(n++; n <100; field[n++] = 0); c = 0; return ‘\n’; To for( n++; n <100; n++) { field[n] = 0; } c = 0; return ‘\n’;

Expressions 14 Use parentheses to resolve ambiguity Compare leap_year = y % 4 == 0 && y %100 != 0 || y % 400 == 0; to leap_year = ((y % 4 == 0) && (y %100 != 0)) || (y % 400 == 0);

Statements 15 Use braces to resolve ambiguity Compare if( i < 100 ) x = i; i++; To if( i < 100 ) { x = i; } i++;

Idioms 16 Do not try to make code “interesting”! i = 0; while( i <= n-1 ) { array[i++] = 1; } for( i = 0; i < n; ) { array[i++] = 1; } for( i = n; --i >= 0; ) { array[i] = 1; } for( i = 0; i < n; i++ ) { array[i] = 1; } This is the common “idiom” that any programmer will recognize

Idioms 17 Use “else if” for multiway decisions if ( cond 1 ) { statement 1 } else if ( cond 2 ) { statement 2 } … else if ( cond n ) { statement n } else { default-statement }

Idioms 18 Compare: if( x > 0 ) if( y > 0 ) if( x+y < 100 ) {... } else printf(Too large!\n" ); else printf("y too small!\n"); else printf("x too small!\n"); if( x <= 0 ) { printf("x too small!\n"); } else if( y <= 0 ) { printf("y too small!\n"); } else if( x+y >= 100 ) { printf("Sum too large!\n" ); } else {... }

Comments 19 Don’t write the obvious // return SUCCESS return SUCCESS; // Initialize total to number_received total = number_received; Test: Does comment add something that is not evident from the code? Note: “//” Comments are Not Strict ANSI C, but supported by all modern compilers, and clearer in many cases

Comments 20 Don’t comment bad code – rewrite it! … // If result = 0 a match was found so return // true; otherwise return false; return !result; Instead … return matchfound;

Style recap 21 Descriptive names Clarity in expressions Straightforward flow Readability of code & comments Consistent conventions & idioms

Why Bother? 22 Good style: Easy to understand code Smaller & polished Makes errors apparent Sloppy style  bad code Hard to read Broken flow Harder to find errors & correct them

Note - style in slides: 23 In the slides we try to follow the style we dictate. But due to space restriction we sometimes bend the rules. Don’t follow everything you see in the slides.

Debugging

Debugging “Define” the bug --- reproduce it 2. Use debugger and printouts (and other tools e.g. valgrind) 3. Don’t panic --- think! 4. Divide & Conquer

From C to C++

27 Why C++ is much more fun than C (C++ FAQ)? 1.Classes & methods - OO design 2.Generic programming - Templates allow for code reuse 3.Stricter type system (e.g. function args) 4.Some run-time checks & memory control A common and mature language that gives you high level and low level control Have fun Why C++ is much more fun than C (C++ FAQ)? 1.Classes & methods - OO design 2.Generic programming - Templates allow for code reuse 3.Stricter type system (e.g. function args) 4.Some run-time checks & memory control A common and mature language that gives you high level and low level control Have fun

28 Why C++ is much more fun than c (C+ FQA)? 1.Tons of corner cases 2.Duplicate features 3.Cryptic syntax 4.Undecidable syntax (uncompilable progarms!) 5.No two compilers agree on it Probably one of the hardest computer languages to master. Have fun Why C++ is much more fun than c (C+ FQA)? 1.Tons of corner cases 2.Duplicate features 3.Cryptic syntax 4.Undecidable syntax (uncompilable progarms!) 5.No two compilers agree on it Probably one of the hardest computer languages to master. Have fun

History 29 The C++ Prog. Manual (85-90) C++98C++03C++11 Major compilers: Latest versions are starting to implement features from c++11 (prev. c++0x) approved draft Practically current c++ Minor changes auto, lambdas, threading, … tr1: library additions ('05)

Course Objectives Learn the language 2. Practice of programming data structures Design Testing & Debugging Efficiency & Portability Modularity

Course structure 31 The basic mechanism underlying many of the extensions. Overloading The C++ version. Object Oriented programing A hidden monster Copying and Conversion Templates - Generics++. Compile time polymorphism Statics, etc. Other topics

First Program in C++ 32 // This line includes the standard // I/O library file (similar to “copy here this file”) #include int main() { std::cout << "Hello class!\n"; return 0; }

Compiling & Running… 33 Visual Studio… In Linux: > g++ –Wall hello.cpp –o hello > hello Hello class! >

Fill in missing types from C, in somewhat crude way 34 The missing types

strings in C++ 35 #include #include int main() { std::string str; int a; double b; std::cin >> str >> a >> b; if(std::cin.fail()) { std::cerr << "input problem\n"; return 1; } std::cout << "I got: "<< str << ' ' << a << ' ' << b << std::endl; } More about string functions:

Boolean variables 36 #include int main() { int a = 5; bool isZero = (a == 0); // same conditions if(!isZero && isZero==false && isZero!=true && !!! isZero && a ) { std::cout << "a is not zero\n"; } }

Enum (C)

User Defined Type - enum Enumerated data - a set of named constants. Usage: enum [identifier]{enumerator list} enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enum Color {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; // enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enum Color {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; //

enum enum Season curr_season; curr_season= AUTUMN; curr_season= 19; // legal, but ugly, g++: warning int SUMMER; // error, redefinition int prev_season = SUMMER; // legal, but ugly, g++ warning enum Season curr_season; curr_season= AUTUMN; curr_season= 19; // legal, but ugly, g++: warning int SUMMER; // error, redefinition int prev_season = SUMMER; // legal, but ugly, g++ warning 39 enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 };

Use enum to eliminate magic numbers – alternative to #define 40

C++-11 enum class 41 Season curr_season; curr_season= Season::AUTUMN; curr_season= SUMMER; // won’t compile! curr_season= 19; // won’t compile! int prev_season= Season::SUMMER; // won’t compile! class char enum class Season : char { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 };

enums – why? More readable code Code less error prone Accessible for debugger Use of the numerical values is not disabled bad programming usually! 42

Understand and remember. More than syntactic sugar. This is how a lot of stuff works under the hood (e.g. inheritance) 43 Overloading

#include void foo() { printf ("foo()\n"); } void foo(int n) { printf ("foo(%d)\n", n); } int main() { foo(12); foo(); return 0; } Function overloading - C 44 Compilation output: Error: Multiple definition of foo

Function overloading – C++ 45 #include void foo() { std::cout << "foo()\n"; } void foo(int n) { std::cout<<"foo("<<n<<")\n"; } int main() { foo(12); foo(); } Output: Compile, and print: foo(12) foo()

Default parameters 46 #include void foo(int n=5) { std::cout << n; } int main() { foo(); } Output: Compile, and print: foo(5)

Overload resolution 47

48 Memory & Arrays (C)

Memory 49 int main() { char c; int i,j; double x; cijx

Arrays Defines a block of consecutive cells int main() { int i; int a[3]; ia[0]a[1]a[2]

Arrays - the [ ] operator 51 int arr[5] = { 1, 5, 2, 1,3 }; /*arr begins at address 40*/ Address Computation Examples: 1. arr[0] 40+0*sizeof(int) = arr[3] 40+3*sizeof(int) = arr[i] 40+i*sizeof(int) = *i 4. arr[-1] 40+(-1)*sizeof (int) = 36 // can be the code // segment or other variables

Arrays 52 C does not provide any run time checks int a[4]; a[-1] = 0; a[4] = 0; This will compile and run (no errors?!) …but can lead to unpredictable results. It is the programmer’s responsibility to check whether the index is out of bounds…

Arrays C does not provide array operations: int a[4]; int b[4]; a = b; // illegal if( a == b ) // legal. ==0, address comparison. 53

Array Initialization 54 int arr[3] = {3, 4, 5}; // Good int arr[] = {3, 4, 5}; // Good - The same int arr[3] = {0}; // Init all items to 0, takes O(n) int arr[4] = {3, 4, 5}; // Bad style - The last is 0 int arr[2] = {3, 4, 5}; // Bad int arr[2][3] = {{2,5,7},{4,6,7}};// Good int arr[2][3] = {2,5,7,4,6,7}; //Good – The same int arr[3][2] = {{2,5,7},{4,6,7}}; // Bad int arr[3]; arr = {2,5,7}; // Bad - array assignment only in initialization