Chapter 2. Procedural Programming

Size: px
Start display at page:

Download "Chapter 2. Procedural Programming"

Transcription

1 Chapter 2 Procedural Programming

2 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic pointer operations.

3 2: Main function Java C++ Comments about C++ class C { public static void main(string args[]) {... } int main() {... return 0; } The main function is not included in any class.

4 2: Comments Comments about C++ /*... */ // C++ does not provide the Java comment /**... */, used to create documentation Remember about programming guidelines!

5 2: Primitive Data Types Comments about C++ char char is one byte long and does not use Unicode short int long float double The language does not define the size and range of numeric primitive data types, which are implementation dependent. There are no predefined wrapper classes for primitive data types.

6 2: More Primitive Data Types Java C++ Comments about C++ byte -- similar to unsigned char boolean bool Any non-zero numeric value can be treated as true, a zero value can be treated as false String string To use strings you must include the <string> library string language = "C" + "++"; bool mark = language < "Java"; char first = language[0];

7 2: typedef and sizeof A synonym for an existing type: typedef bool Boolean; Size of data type (in bytes): int k = 5;... sizeof(int)... sizeof k

8 2: Variables, Constants and Expressions Java C++ final const -- const int LINES = 25; Comma operator, e.g. e1, e2 for(i = 1, j = 2; i < N && j < M; ++i, ++j)...

9 2: Type Conversions between bool and int Implicit type conversions or casts are performed when: the value is promoted to a more precise type: double d = 3; // 3 is promoted to 3.0 the value is demoted, resulting in a loss of precision: double d = ; int i = d; // is demoted

10 2: Type Conversions (cont.) Better to use explicit cast: i = static_cast<int>(d); Example int i, j;... // initialization of i and j double d = static_cast<double>(i) / j; // avoids int division

11 2: Type Conversions (cont.) Conversion to remove constness, which allows a const identifier to be modified: const int i = 3; const_cast<int>(i) = 1; // not constant reinterpret_cast used to perform a low-level reinterpretation of the bit pattern to force the type conversion dynamic_cast used for derived classes

12 2: Control Structures Comments about C++ Conditional and switch statements Loops same break or continue cannot be labeled. A goto statement is available (if and when really needed).

13 2: Basic I/O Three predefined streams: cout - the standard output stream << (put-to) binary operator is used for output cin - the standard input stream >> (get from) operator is used for input cerr - the standard error stream.

14 2: Basic I/O (cont.) cout << "Enter value "; int i; cin >> i; // prompt // input integer cout << "The value is:"; cout << i; // output integer cout << "The value is:" << i << endl; // chain

15 // File ex2.1.cpp // Read integer values until a positive value is entered // If a non-integer value is entered, abort the program Example of I/O // Otherwise, output the integer value #include <iostream> int main() { int i = 0; bool correct = false; cout << "Enter a positive integer value" << endl; } while(cin >> i) { if(i > 0) { test for correct input correct = true; break; } cout << "non-positive value; re-enter" << endl; } if(!correct) cout << "incorrect integer value" << endl; else cout << "You entered " << i << endl;

16 2: Arrays C++ arrays are borrowed from C: Java C++ Comments about C++ int [] marks = new int[10] int marks[10] - lower bound equal to zero - size must be known at compile time The C++ standard library also provides vectors.

17 2: Reference Data Types A reference data type (which differs from Java references) is of the form type& It is used for: passing parameters and returning values providing an alias in a variable definition (must be initialized in the definition) int i = 1; int& pi = i; // pi is an alias for i pi++; // now i is 2, pi not changed

18 2: Reference Data Types (cont.) References must be initialized with expressions that are lvalues. You can declare the reference as constant; for example: const int& cpi = 8; (may be initialized with expressions that are not lvalues). Mostly used with parameters.

19 2: Functions Terminology: an expression that appears in a function call, such as x in f(x), is called an actual parameter, as opposed to the formal parameter that appears in the function definition. Construct Comments about C++ int foo(pars) { body } C++ allows global functions, that is functions that are defined outside of any class (also called stand-alone functions)

20 2: Functions (cont.) A function may be defined as inline: inline int sum(int i, int j) { return i + j; } which is a request to the compiler to generate code inline. Each call to the inlined function is replaced at compile time by its body: int i = sum(1, k); // replaced by: int i = 1 + k

21 2: Declarations and Definitions A function declaration merely provides a function signature and the return type: bool prime(int); // note the semicolon A function definition includes the declaration and the implementation of the function. A function can be called only if it has been declared or defined. Each function declaration must come with the documentation to be used by the client. A different kind of information is needed by the implementor of the function, and so the function definition comes with its own documentation.

22 2: Pass by Value, Pass by Reference, and Constant Pass by Reference Passing parameters by value means that the formal parameter is assigned the value of the actual parameter, and the actual parameter is not modified: void swap(int x, int y) { int temp = x; x = y; y = temp; } int i = 1; int j = 2; swap(i, j);

23 2: Pass by Value, Pass by Reference, and Constant Pass by Reference Passing by reference allows the function to modify the actual parameter. The type of the parameter passed by reference is a reference type, with an & following the parameter type: void swap(int& x, int& y) { int temp = x; x = y; y = temp; } int i = 3; int j = 4; swap(i, j); // i and j passed by reference

24 2: Pass by Value, Pass by Reference, and Constant Pass by Reference Constant pass by reference does not allow the client to inadvertently modify the actual parameter: double product(const double& block, int size); If a function has a non-constant parameter, then it may not be called with a constant actual parameter.

25 Pass by Value and by Reference If you do not want to modify the value of the actual parameter, then use - pass by value for parameters of primitive data types, - constant pass by reference for parameters of structured data types, such as classes. If you do want to modify the value of the actual parameter, then use pass by reference.

26 2: Default Values of Parameters A default value of a formal function parameter is useful if this function is frequently called with the same actual parameter. The client can call this function either without the actual parameter for this formal parameter (and so using the default value), or with an actual parameter to override the default value. A function move() that typically moves to position 0 by a step of 1 void move(int from, int to = 0, int by = 1);

27 2: Default Values of Parameters (cont.) Only trailing parameters may be assigned default values: void move(int from, int to = 0, int by); Overriding values of the actual parameters are assigned from left to right: void move(int from, int to = 0, int by = 1); move(2); // move(2, 0, 1) move(2, 3); // move(2, 3, 1) move(2, 3, 4); // move(2, 3, 4) It is not possible to override the second most trailing default parameter, without overriding the first default parameter.

28 2: Overloading Functions The name of a function should identify the action performed by this function. Overloading a function means that you can have several functions with the same name in a single scope, provided that these functions have different signatures: double max(double, double); int max(int, int); // overloaded bool max(int, int); // identical signatures

29 2: Overloading Functions (cont.) Sometimes, overloading can be replaced by using default parameter values: void move(int from, int to); void move(int from, int to, int by); can be replaced by a single function: void move(int from, int to, int by = 0);

30 2: Functions and Arrays When arrays are used as function parameters, their size has to be passed as another parameter: void maxmin(const double arr[], int size, double& max, double& min) { int i; for(max = min = arr[0], i = 1; i < size; ++i) { if(max < arr[i]) max = arr[i]; if(min > arr[i]) min = arr[i]; } }

31 2: Functions and Arrays (cont.) double arr[] = {1.3, 1.2, 1.1}; double maxi, mini; maxmin(arr, 3, maxi, mini); Consider a different maxmin1(): const double x[] = {3, 1, 7.8}; void maxmin1(double arr[],int size, double& max, double& min); maxmin1(x, 3, max, min); // error, x is const

32 2: Functions Returning References A function may return a reference type, and if so, a function call is an lvalue: int a[5]; int& index(int x[], int i) { // gives read/write access // to the i-th element of x return x[i]; } cin >> index(a, 1);

33 2: Functions Returning Constant References Functions may also be designed to provide read-only access, by returning a constant reference: const int& get(const int x[], int i) { } return x[i]; cout << get(a,2); cin >> get(a,1); // can't change the value

34 2: Pointers and Dynamic Memory Management Static memory is used to store the values of global variables, as well as function and class static variables. Stack-based memory is implicitly managed by function calls and function returns. Heap-based memory is used to dynamically manage memory as a result of a program s request, such as Java's new call.

35 2: Pointers and Dynamic Memory Management

36 2: Pointers and Dynamic Memory Management (cont.) Dynamic memory allocation means that a block of memory requested by a program is removed from the heap, and can be used by this program. Dynamic memory deallocation means that a program returns a block of memory to the heap - the de-allocated memory can be used the next time a memory request occurs.

37 2: Pointers and Dynamic Memory Management (cont.) Garbage collector decides when inaccessible objects are deallocated. Java objects are always allocated on the heap and never on the run-time stack, and all memory deallocation is done automatically by the garbage collector. Memory leakage occurs when memory that is no longer needed by the program has not been freed and made available for reuse. What's a reference to an object in Java? It is a memory address; specifically, the address of a block of memory allocated for this object on the heap.

38 2: Pointers and Dynamic Memory Management (cont.) In C++: objects may be allocated both on the stack and in the heap there is no standard garbage collector the programmer is fully responsible for explicitly deallocating memory. This may lead to various programming errors: dangling reference problem - the result of a variable referencing a memory block whose lifetime has expired (allocated on the stack and then deallocated) memory leakage.

39 2: Basic Pointers Operations Pointer variables, or just pointers have names, types, and values. The value of a pointer is the address of a memory block. The type of a pointer determines the size of that block (the size is essential to access data stored at that address). For any data type T, for example int, you can define a variable of type "pointer to T", such as "pointer to int : int* p; char* s; // pointer to int // pointer to char

40 2: Basic Pointers Operations (cont.) Dereferencing using pointer s name, prefixed with the asterisk *. For example, *p is the contents of the memory block that p points to, and *p behaves as an int variable. You can take a non-pointer variable and get a pointer by applying the address operator & to it: int i = 1;...i... // an int variable...&i... // like int pointer, pointing to i int* p; p = &i; // p points to i... *p... // dereferenced p is equal to i

41 2: Basic Pointers Operations (cont.) C++ provides NULL, but rather than using it, use 0 Two common errors associated with C++ pointers is the use of un-initialized pointers, pointers that point to 0. The language's run-time system does not provide the same safety as Java's exception handling mechanism; instead, your program may continue to execute following the use of an un-initialized pointer, and crash unexpectedly at a later time.

42 2: Constant Pointers Read these pointer declarations right-to-left: const int* p; a pointer to an integer that is constant; the value of p may change, but the value of *p cannot int* const cp; a constant pointer to integer; the value of *cp can change, but the value of cp cannot const int* const cpc; a constant pointer to a constant integer.

43 2: Constant Pointers (cont). In some exceptional cases you may want to remove const'ness: const_cast<type>(value) For example, to make pointer p const int* p; point to the value 3 (i.e. to assign 3 to *p), you can use *(const_cast<int*>(p)) = 3;

44 2: Pointers as Parameters Array parameters are treated like pointers. void maxmin(double* arr, int size, double& max, double& min); void maxminconst(const double* arr, int size, double& max, double& min); const double a[] = {1.5, 3.1}; double max, min; maxmin(a, 2, max, min); // a is const maxminconst(a, 2, max, min); maxmin(const_cast<double*>(a), 2, max, min);

45 Pointer Parameter 1. Functions that do not modify values pointed to by their pointer parameters should have these parameters specified as const; for example, const double*. This allows us to call the function both with non-constant and constant pointer parameters. 2. Functions that modify their pointer parameters should have these specified as passed by reference.

46 2: Functions Returning Pointers int* change(int arr[], int size, int i) { // return a pointer to the i-th element if(i < 0 i >= size) return 0; return &arr[i]; } const int* nonchange (const int arr[], int size, int i);... // as above int x[] = {1, 2, 3}; int* i = change(x, 3, 2); *i = 3; // OK, can modify through i const int* j = nonchange(x, 3, 2); cout << *j; *j = 3; // can't assign to a const i = nonchange(x, 3, 2); // can't: non-const

47 2: C-style Strings and main Function Parameters C++ provides two kinds of strings: string char* - pointer to char, (C-style) C-style strings cannot be avoided in the main function, and for file operations A C-style string can be passed as a parameter of a function: int foo(char* str); Within the body of this function, str is treated as an array of characters (terminated by the zero character). The size of this array is the length of the string, which can be obtained by using the strlen()

48 2: C-style Strings and main Function Parameters Java C++ Comments about C++ void main( String[] args) int main( int argc, char*argv[]) Integer function with two parameters: - the number of command line parameters - an array of C-style strings representing parameters The name of the program is taken from the command line as argv[0], and therefore argc is always greater than zero

49 2: C-style Strings and main Function Parameters // File: ex2.5.cpp // Copy words from the input file to the output // file; passing filenames on the command line // Output the total number of words to the standard output // Return 1 if can't open input file; // 2 if can't open output file #include <iostream> #include <fstream> #include <string> int main(int argc, char* argv[]) { // check command line if(argc!= 3) { cerr << "Usage: " << argv[0] << " file1 file2" << endl; return 1; }

50 } ifstream infile(argv[1]); if(!infile) { Example cerr << "can't open " << argv[1] << endl; return 1; } ofstream outfile(argv[2]); if(!outfile) { cerr << "can't open " << argv[2] << endl; return 2; } string word; long wordcounter = 0; while(infile >> word) { outfile << word << endl; wordcounter++; ifstream and ofstream constructors use C-style strings // copy words // end-of-file } cout << "Read " << wordcounter << " words" << endl; return 0;

51 2: Static Local Variables Local variables in a function are allocated on the stack, in the socalled instance, or frame for this function. It is sometimes useful to limit the scope but not the lifetime of a variable. void login() { static int counter = 0; counter++; }

52 2: File Organization and Standard Facilities A Java program: typically consists of multiple files when you compile it, you usually use the name of single file, which contains the main function to be invoked. the Java compiler checks what other files are needed, and whether these files have been recently compiled. All files that have been modified since the last compilation are recompiled, and finally, all compiled files are linked.

53 2: File Organization and Standard Facilities (cont.) A C++ program: is a set of compilation units, which must be linked together to form the executable code typically consists of multiple files; each file is a unit of compilation. the programmer is responsible for compiling all the necessary files you typically use separate compilation, and a tool such as make to update the executable code. Separate compilation: you can compile parts of your program, where each part is a file

54 2: Preprocessing and Header Files Related function declarations are typically stored in header files. You typically include the header file containing required declarations. Any line of C++ code that begins with the # (pound symbol) is referred to as a preprocessor command line: include command, which is used to include external files in the current file conditional compilation command, which tells the compiler that a part of the source file is included conditionally

55 2: Preprocessing and Header Files (cont.) Standard header files #include <filename> User-defined header files: #include "filename.h" (User-defined header file typically have the h extension, for example "screen.h".) These two formats differ in how the specified file is located by the compiler.

56 2: Preprocessing and Header Files (cont.) Conditional compilation directive is based on the definition of a name, called a macro, which specifies whether this file has already been included. By convention, an include file screen.h will have the macro name SCREEN_H. The header file might look like this: #ifndef SCREEN_H // conditional compilation #define SCREEN_H... // contents of the header file #endif

57 Include Guards The header file should be conditionally included; for example #ifndef SCREEN_H // conditional compilation #define SCREEN_H... // contents of the header file #endif

58 2: Namespaces To avoid name collisions, C++ provides namespaces, (similar to Java's packages): Each namespace defines a new scope, and a name used in one namespace does not conflict with the same name used in another namespace. The C++ standard library is defined in a namespace called std. Practically, in all programs, you include the header file: #include <iostream> In order to make every name from this namespace directly available, you specify the namespace with the using keyword: using namespace std;

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Operators. The Arrow Operator. The sizeof Operator

Operators. The Arrow Operator. The sizeof Operator Operators The Arrow Operator Most C++ operators are identical to the corresponding Java operators: Arithmetic: * / % + - Relational: < = >!= Logical:! && Bitwise: & bitwise and; ^ bitwise exclusive

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

EMBEDDED SYSTEMS PROGRAMMING Language Basics

EMBEDDED SYSTEMS PROGRAMMING Language Basics EMBEDDED SYSTEMS PROGRAMMING 2014-15 Language Basics (PROGRAMMING) LANGUAGES "The tower of Babel" by Pieter Bruegel the Elder Kunsthistorisches Museum, Vienna ABOUT THE LANGUAGES C (1972) Designed to replace

More information

Object Reference and Memory Allocation. Questions:

Object Reference and Memory Allocation. Questions: Object Reference and Memory Allocation Questions: 1 1. What is the difference between the following declarations? const T* p; T* const p = new T(..constructor args..); 2 2. Is the following C++ syntax

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Creating a C++ Program

Creating a C++ Program Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer. 1 Creating a C++ Program created using an

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

More information

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes, Chapter 5 Basic Semantics Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes, and the Environment Variables

More information

Chap 0: Overview. Overview of basic C++ syntax Refresh programming basics C++ Vs. Java differences Coding conventions used. EECS 268 Programming II 1

Chap 0: Overview. Overview of basic C++ syntax Refresh programming basics C++ Vs. Java differences Coding conventions used. EECS 268 Programming II 1 Chap 0: Overview Overview of basic C++ syntax Refresh programming basics C++ Vs. Java differences Coding conventions used EECS 268 Programming II 1 Basics - 1 Comments single line: // multi-line: /* */

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.) Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes

More information

C++_ MARKS 40 MIN

C++_ MARKS 40 MIN C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float

More information

Your first C++ program

Your first C++ program Your first C++ program #include using namespace std; int main () cout

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

More information

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

C11: Garbage Collection and Constructors

C11: Garbage Collection and Constructors CISC 3120 C11: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/5/2017 CUNY Brooklyn College 1 Outline Recap Project progress and lessons

More information

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

EL6483: Brief Overview of C Programming Language

EL6483: Brief Overview of C Programming Language EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions

More information

Basic Types, Variables, Literals, Constants

Basic Types, Variables, Literals, Constants Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 3 is due Thursday, 10/6 Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both sides) Tutoring

More information

C++ basics Getting started with, and Data Types.

C++ basics Getting started with, and Data Types. C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding

More information

In Java we have the keyword null, which is the value of an uninitialized reference type

In Java we have the keyword null, which is the value of an uninitialized reference type + More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are

More information

377 Student Guide to C++

377 Student Guide to C++ 377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided

More information

CMPS 221 Sample Final

CMPS 221 Sample Final Name: 1 CMPS 221 Sample Final 1. What is the purpose of having the parameter const int a[] as opposed to int a[] in a function declaration and definition? 2. What is the difference between cin.getline(str,

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

C++ For Science and Engineering Lecture 15

C++ For Science and Engineering Lecture 15 C++ For Science and Engineering Lecture 15 John Chrispell Tulane University Wednesday September 29, 2010 Function Review Recall the basics you already know about functions. Provide a function definition.

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

Model Viva Questions for Programming in C lab

Model Viva Questions for Programming in C lab Model Viva Questions for Programming in C lab Title of the Practical: Assignment to prepare general algorithms and flow chart. Q1: What is a flowchart? A1: A flowchart is a diagram that shows a continuous

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

EEE145 Computer Programming

EEE145 Computer Programming EEE145 Computer Programming Content of Topic 2 Extracted from cpp.gantep.edu.tr Topic 2 Dr. Ahmet BİNGÜL Department of Engineering Physics University of Gaziantep Modifications by Dr. Andrew BEDDALL Department

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

Strings and Stream I/O

Strings and Stream I/O Strings and Stream I/O C Strings In addition to the string class, C++ also supports old-style C strings In C, strings are stored as null-terminated character arrays str1 char * str1 = "What is your name?

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Memory Allocation in C

Memory Allocation in C Memory Allocation in C When a C program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment and heap segment. The text segment (also called

More information