CS 44001/54001 CS III: Programming Patterns

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Pointers Revisited l What is variable address, name, value? l What is a pointer? l How is a pointer declared? l What is address-of (reference) and dereference.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
C++ Pointer and Functions
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Classes: A Deeper Look Systems Programming.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Data Types, Expressions and Functions (part I)
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Basic Elements of C++ Chapter 2.
Review of C++ Programming Part II Sheng-Fang Huang.
Operator Overloading and Type Conversions
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
COMPUTER PROGRAMMING. Data Types “Hello world” program Does it do a useful work? Writing several lines of code. Compiling the program. Executing the program.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Iterative Constructs Review l What are named constants? Why are they needed? l What is a block? What is special about declaring a variable inside a block?
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
1 Functions in C++ Default arguments Overloading Inlining Call-by-reference Scope of variables, static, extern namespace new and delete assert.
CHAPTER 2 C++ SYNTAX & SEMANTICS #include using namespace std; int main() { cout
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Functions. Predefined Functions C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Today… Continue Building Expressions: –Literals –Constants –Casting –Array Declaration –Operators and Operator Precedence –Keywords Winter 2016CMPE212.
C++ Lesson 1.
Chapter Topics The Basics of a C++ Program Data Types
Computer Programming BCT 1113
Data types Data types Basic types
CS Computer Science IA: Procedural Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Introduction to C++ Systems Programming.
Sachin Malhotra Saurabh Choudhary
Variables A variable is a placeholder for a value. It is a named memory location where that value is stored. Use the name of a variable to access or update.
Basic Elements of C++.
Computing with C# and the .NET Framework
Basic Elements of C++ Chapter 2.
Conversions of the type of the value of an expression
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is legal identifier? what.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Pointers, Dynamic Data, and Reference Types
2. Second Step for Learning C++ Programming • Data Type • Char • Float
CS410 – Software Engineering Lecture #5: C++ Basics III
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Presentation transcript:

CS 44001/54001 CS III: Programming Patterns Mikhail Nesterenko

Procedural Programming without classes: using standalone functions, primitive types and simple control structures

Before We Go a computer program is governed by rules what are syntax rules? semantic rules? stylistic rules? any data may be declared const – cannot be modified typedef creates synonym for existing type: typedef ExistingType NewType; typedef bool Boolean;

Types, Variables primitive (basic/built-in) types – string, int, bool, char, double exist but won’t need int may be long or short, signed or unsigned char may be signed or unsigned floating point types may be float, double or long double auto – type to be determined by compiler (C++11) auto i =7; // nice for type of loop variables could also be auto & and const auto decltype(expr) – type is same as expr (C++11) decltype(i) j =8; variable – denotes memory location of particular type, holds values what is block? what is local variable? Can a variable be local to a block? what is scope of a variable? any data may be declared const – cannot be modified typedef creates synonym for existing type: typedef ExistingType NewType; typedef bool Boolean;

Operators, Arity operators – built-in functions fixed number of operands (parameters) arity – the number of operands unary ++ and -- prefix/sufix(postifx) preincrement/postincrement or predecrement /postdecrement use prefix porm prefix form returns an l-value (what’s that?) binary assingment, compound assingment ternary – what’s that? What are these operators? What is their arity? = ! - ++ += << ||

Expressions what is a constant? Literal constant? What other kind of constant is there? who is contant type determined? What is expression? What is expression evaluation? How is expression type determined?

Conditionals and Loops if/else switch ternary expression loops while do-while for for(init_statement; expression; post_statement) action range-based-for (C++11) int a[] = {10,20,30,40}; for(auto e: a) cout << e; how do I write a range-based-for to add 5 to each element of the array?

Functions what is function invocation/call/definition/declaration? what is the difference between argument and parameter? in procedural programming functions are standalone function definition – includes head and body (implementation) can be declared (with prototype/signature – definition that omits body) function overloading – multiple different functions within the same scope provided that they have different signatures double max(double, double); int max(int, int); resolution (of function call) – compile time process of associating function invocation with function declaration int i = max(10, 20); // resolved to second declaration client/caller – function that invokes another function when dealing with programming patterns, function that uses the pattern void – no return value, if no parameters – keep parentheses empty void myFunc();

Function Parameters, Default Values parameters may be passed by value, by reference, what’s the difference? default values default parameter value may be specified at function declaration void move(int from, int to=0, int by =1); client has an option of specifying parameter or using default value move (2, 3, 4); move (2, 3); move (2); provides convenient alternative to overloading only trailing parameters may have default values void move(int from, int to=0, int by); // illegal

References reference – alias (another name) for data declared as type& has to be initialized at declaration and cannot be changed int& b = a; ++b; // changes a can hold only l-values – values that refer to memory location, can be used on the left-hand-side of assignment used for parameter passing void swap(int &a; int &b){ int tmp = a; a = b; b = tmp; }

References (cont.) reference can be used to return values in which case function can be used on the left-hand side of assignment int& getElement(int x[], int i) { return x[i]; } ... int a[] = {10, 20, 30}; cout << getElement(a, 1); getElement(a, 2) = 55; careful with returning local function variables by reference: they are destroyed when function returns, why?

Pointers, Arrays and Dynamic Memory (review) what is stack, heap, frame? what is the relationship between array name and a pointer? what is dynamic variable and how is it allocated? deallocated? why is it needed? what is dynamic array and how is it allocated?

Pointers and Functions function may also return a pointer int* getElement(int x[], int i) { return &x[i]; } ... int a[] = {10, 20, 30}; cout << *getElement(a, 2); *getElement(a, 5) = 55;

nullptr use nullptr to signify uninitialized pointer nullptr – null pointer constant (C++11 addition) is of type pointer unlike NULL and 0, which are integer type what’s wrong with NULL and zero? void myFunc(int); // overloaded function void myFunc(char *); func(NULL); // invokes first function use nullptr to signify uninitialized pointer

Const keyword uses named constants: const int MyConst = 55; parameter protection void myFunction(const double myValue); reference protection void myFunction(const MyClass& myObj); const casting - allows a constant to be modified const int i = 3; const_cast<int>(i) = 1; what’s constant pointer? pointer to constant? can I have both?

Arrays What does these lines do? int myArray[10]; int myArray[10]={0}; // this one is tricky int myArray[10]={2};

Strings what is the difference between c-style and C++ style strings? how to convert c-style <-> c++-style string? what is argc argv ? what is concatentation? what do find() substr() insert(), replace(), erase() do? what is the difference between myfunc(string); myfunc(string &) and myfunc(const string&);

Static Variables static variables are initialized only once and retain their value across function invocations void login() { static int number1 = 0; int number2 = 0; ++number1; ++number2; cout << number1 << number2; } int main(){ login(); prints 112131

Conditional Compilation and Include Guards (review) what is preprocessor directive? what’s the difference between #include <file> and #include ”file” ? what does this code do? #ifndef MYHEADER_H #define MYHEADER_H ... #endif MYHEADER_H #pragma once is a windows-originated non-standard replacement that is widely supported may speed up computation may introduce sublte errors as header files are copied sym-linked, etc

enum Classes C++11 addition enum class Gender {Male, Female}; what’s wrong with pre C++ enum? constants are unscoped: enum Example1 {One, Two, Three}; enum Example2 {Three, Four, Five}; // is illegal constants are untyped: Example1 myEnum1=One; Example2 myEnum2=Five; if(myEnum1 != myEnum2) // is legal enum classes are scoped, and typed to refer to constant need to use scope: Example1::One

Namespaces what are namespaces and why are they needed? what are the three ways of importing names from a namespace? What are their advantages and disadvantages? how should the names be imported in a header file? how does this apply to std namespace? namespace definition is open – can be added to by defining another namespace with the same name (note that class definition is closed) common idiom: class interface is in a namespace in the header – exposed to clients class implementation is the added namespace in the source file variable shadows another variable with the same name in outer block or namespace, may refer to shadowed variable with scope resolution what does this construct mean? ::myName = 55; referring to a name in the global namespace

Comma Operator comma operator – binary operator that evaluates first operand, discards result (used for side effect), evaluates second and returns value, has lowest precedence int i = (a += 2, a+b); // what does this do? somewhat confusing, seldom used outside idioms, common for for-loop initialization: int i,j; for(i=1, j=i; i < 10 && j < 10; ++i, ++j) cout << i << j;

Casting (implicit) casting – type conversion without using specific type conversion operators (explicit) casting – otherwise promotion – casting with precision gain (ex: int to double) demotion – casting with precision loss (ex: double to int) explicit casting: static_cast<type>(value) int i =1; double d = 3.21; i = static_cast<int>(d); constant cast – allows a constant to be modified const int i = 3; const_cast<int>(i) = 1;

Naming Conventsion naming conventions – camelCase except GLOBAL_CONSTANTS class names start with upper case letter: NewClass variables, function names start with lower case letter: myVar, myFunc constant names are all upper case with underscore: MY_CONSTANT declare variables where they are first needed alternative (discouraged) declare at the beginning of scope use class attributes rather than global variables (violate modularity)