Crash Course into. Prof. Dr. Renato Pajarola

Similar documents
Short Notes of CS201

CS201 - Introduction to Programming Glossary By

CS105 C++ Lecture 7. More on Classes, Inheritance

Introduction to C ++

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

Programming in C and C++

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

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

Introducing C++ to Java Programmers

CE221 Programming in C++ Part 1 Introduction

Outline. 1 About the course

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Fast Introduction to Object Oriented Programming and C++

6.096 Introduction to C++ January (IAP) 2009

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

AN OVERVIEW OF C++ 1

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

C Introduction. Comparison w/ Java, Memory Model, and Pointers

CS 376b Computer Vision

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

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

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

SAURASHTRA UNIVERSITY

CS201 Some Important Definitions

Introduction to Programming Using Java (98-388)

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

Introduction to C++ Systems Programming

5.Coding for 64-Bit Programs

Interview Questions of C++

Chapter 2. Procedural Programming

Fundamentals of Structured Programming

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):

C++ Programming for Non-C Programmers. Supplement

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Chapter 1: Object-Oriented Programming Using C++

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, Dynamic Data, and Reference Types

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

Structure of this course. C and C++ Past Exam Questions. Text books

Motivation was to facilitate development of systems software, especially OS development.

Your first C and C++ programs

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

Procedural programming with C

CS3157: Advanced Programming. Outline

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Extending Classes (contd.) (Chapter 15) Questions:

Data Structures (INE2011)

C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS

Motivation was to facilitate development of systems software, especially OS development.

Absolute C++ Walter Savitch

COMP322 - Introduction to C++ Lecture 01 - Introduction

Object Oriented Programming. Solved MCQs - Part 2

COEN244: Class & function templates

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

C++ (Non for C Programmer) (BT307) 40 Hours

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Computers Programming Course 5. Iulian Năstac

CSCI 171 Chapter Outlines

Documentation. Programming / Documentation Slide 42

Part III Synchronization A bit of C++ and ThreadMentor

Conversions and Overloading : Overloading

Computer Science II Lecture 1 Introduction and Background

Chapter 1 Introduction to Computers and C++ Programming

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Pointers, Arrays and C-Strings

EC 413 Computer Organization

September 10,

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Partha Sarathi Mandal

3. Java - Language Constructs I

W3101: Programming Languages C++ Ramana Isukapalli

CSE 303: Concepts and Tools for Software Development

C++ Important Questions with Answers

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

C++ Programming for Non-C Programmers. Supplement

G52CPP C++ Programming Lecture 20

Operator overloading

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

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

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

pointers + memory double x; string a; int x; main overhead int y; main overhead

C++_ MARKS 40 MIN

Friend Functions and Friend Classes

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

This lists all known errors in The C Programming Language, Second Edition, by Brian Kernighan and Dennis Ritchie (Prentice-Hall, 1988).

CS201- Introduction to Programming Current Quizzes

CS304 Object Oriented Programming

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

STRUCTURING OF PROGRAM

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Exercise 1.1 Hello world

Transcription:

Crash Course into Prof. Dr. Renato Pajarola These slides may not be copied or distributed without explicit permission by all original copyright holders

C Language Low-level programming language General purpose imperative language procedures and structures as only way to structure code and data types Syntax similar to Java Typed language with derived data types but not strongly as explicit casting of types is possible int short long float double char pointers arrays structures unions

ANSI-C Standard language with set of libraries for I/O, string handling, character operations, math functions etc. Simple and compact language independent of machine architecture efficient compilation into native machine code small required run-time library source code portable no GUI C++ extension provides object-oriented language features

C++ C++ is a general purpose programming language with a bias towards systems programming that is a better C supports data abstraction supports object-oriented programming supports generic programming Java derived much of its syntax from C and C++ but Java has fewer low-level facilities typically compiled into intermediate bytecode for Java VM

Program Structure Definitions and implementations are separated into header (.h/.hpp) and source (.c/.cc/.cpp) files Encapsulation and modularization is strongly encouraged by grouping code into header/source file pairs header file contains all declarations of global variables, type definitions, data structures, procedures, objects and methods actual implementation of procedures and methods is in the source file

Quicksort Routines Header file /* * quicksort.h */ void sort_array(float list[], int l, int r); int partition_array(float list[], int l, int r); Source file /* * quicksort.cpp */ #include "quicksort.h" void sort_array(float list[], int l, int r) { int pivot_index; } if (l < r) { pivot_index = partition_array(list, l, r); sort_array(list, l, pivot_index); sort_array(list, pivot_index+1, r); } int partition_array(float list[], int l, int r) { float tmp, pivot; int i; int j; pivot = list[l]; i = l; j = r; while (1) { while (list[j] > pivot) j--; while (pivot > list[i]) i++; if (i < j) { tmp = list[i]; list[i] = list[j]; list[j] = tmp; } } /* skip these two elements */ j--; i++; } else return j;

Main Quicksort Program must contain one main() function which is called at process startup /* * main.cpp */ #include <unistd.h> #include <stdlib.h> #include <iostream> #include "quicksort.h" int main(void) { int i; float numbers[array_size]; /* initialize array of random float numbers */ srandom(getpid()); for (i = 0; i < SIZE; i++) numbers[i] = random(); #define ARRAY_SIZE 8 using namespace std; } /* quicksort the array */ sort_array(numbers, 0, SIZE-1); /* output result */ for (i = 0; i < SIZE; i++) cout << "Number " << i << ": " << numbers[i] << endl; return 0;

External Code External functionality is imported via header files #include <header_file> /* * main.cpp */ #include <unistd.h> #include <stdlib.h> #include <iostream> #include is a preprocessor directive preparing the source files for compilation #include "quicksort.h" #define ARRAY_SIZE 8 unistd.h declares the getpid() system function stdlib.h declares the random number generator functions iostream declares the standard C++ I/O streams #define is a preprocessor directive for symbolic constants

Namespaces C++ includes a number of standard classes and libraries e.g I/O streams, strings or containers (STL) standard C headers included as <c_name> instead of <_name.h> Namespaces used to limit scope of symbols to specific blocks of code generally to avoid naming collisions namespace std space the C++ standard library resides in Declare namespace usage within scope of source code or for individual elements using namespace std; using std::cout; // imports all standard C++ library // symbols into the current scope // import iostream cout only

Compiling and Linking At compile time only the header information is needed only the function and variable definitions need to be verified cc -c quicksort.cpp generates quicksort.o object file include file directories can be specified with compiler flags At link time the actual object files and/or libraries are needed object and libraries are merged and linked into one binary executable cc -o sort main.o quicksort.o generates executable standard libraries are linked automatically extra libraries are indicated with compiler flags

Control Flow Sequence of statements terminated by ; definitions, assignments, procedure calls blocks of statements within { } Selection of code blocks if, else if, else and switch statements Loops over statement blocks while, do and for iterations Recursive calls of procedures

Data Types and Variables Declaration of variables by type generally at beginning of code block float numbers[array_size]; Range of numeric types is machine dependent int and float are typically 4 bytes on 32- or 64-bit systems can check with sizeof(<type>) use #include <sys/types.h> or <inttypes.h> for fixed size numerical types uint8_t, int16_t, uint32_t C++ strings are ASCII characters and modifiable string test = "Hello"; test += " World";

Arithmetic Arithmetic expressions are based on implicit type conversion starts with int continues with truncated computations #include <iostream> using namespace std; int main(void) { int fahr, celsius; /* Fahrenheit-Celsius */ fahr = 57; celsius = (5 / 9 * (fahr - 32)); cout << "Fahrenheit: " << fahr << " Celsius: " << celsius; Convert Fahrenheit to Celsius Fahrenheit: 57 Celsius: 0 Celsius: 23 Fahrenheit: 55 } /* Celsius-Fahrenheit */ celsius = 23; fahr = (9 / 5 * celsius) + 32; cout << "Celsius: " << celsius << " Fahrenheit: " << fahr;

Functions Functions are identified via return value and parameters void sort_array(float list[], int l, int r); not part of any class global functions Must be defined before being used just procedure header without code body Arguments are call-by-value functions receive a copy of the actual parameters original cannot be modified inside function

References Call-by-reference can be enforced by & if passed by reference, function can modify original variable void raisesalary(employee &e, int amount); normal behavior in Java on objects C++ references also work on basic types void swap(int &a, int &b) { } int tmp = a; a = b; b = tmp; use references in C++ when function needs to modify parameters

Class Headers The class definition only contains the declaration of members and methods implementation is separated in the source file Classes have public and private sections class Employee { public: Employee(); Employee(string input); string getname() const; private: string name; }; protected access by members and friends of derived classes

Class Implementation Methods are implemented in the source file methods are prefixed by the class name and :: for correct class association Employee::Employee { name = "Muster"; } Employee::Employee(string input) { name = input; } string Employee::getName() const { return name; }

Objects In C++ variables hold values not references definition of variables causes memory to be allocated and a constructor to be called Employee admin; object is constructed using default constructor causes only uninitialized reference in Java Assignment of variables causes copy of value similar to clone in Java no two variables for the same object need to use pointers for that Object variable can only hold one particular type

Inheritance C++ syntax similar to Java use of : public instead of extend to denote inheritance class Manager : public Employee { public: Manager(string nm, int salary, string dept); virtual void print() const; // dynamically bound private: string department; }; Unless specified with virtual, methods cannot be dynamically bound

Superclass Methods Invokation of superclass constructor done outside of constructor code body Manager::Manager(string nm, int salary, string dept) : Employee(nm, salary) // initialization list { } department = dept; Reference to superclass via ::operator void Manager::print() const { Employee::print(); // call superclass method } cout << department << endl;

Polymorphism C++ variable of type T holds objects only of this type variables hold value not reference to object Polymorphism requires use of pointer variable type T* T *p; can point to T or any subclass of T Employee *e = new Manager("Steve", 100000, "HW"); Dynamic binding supported via pointers only vector<employee*> staff;... for (i = 0; i < staff.size(); i++) staff[i]->print();

Pointers Variables hold values float x; writes the float representation of 0.5 x = 0.5; into the 4 bytes of variable x Pointers declared by * indicate memory addresses float *px; is a memory address of a float px = &x; address given by the & operator Pointers are dereferenced again by * to get value float y; y = *px + 1.0;

Pointers as Reference Similar to object variables in Java, pointers can be set to NULL and initialized with new Employee *staff = NULL; // always initialize! Employee *chief = new Employee("Steve Jobs"); staff = chief; // two variables pointing to the same delete chief; // leaves staff dangling To access object, point must be dereferenced string boss = (*chief).getname(); or use the arrow operator -> string boss = chief->getname();

Arrays Defined as type name[dimension] start index is at 0 Access via name[expression] where expression is an integer expression implicit type cast converts any expression to integer index array bounds are not implicitly checked Represents continuous block of memory number of used bytes is dimension * sizeof(type) variable name indicates start of array s memory name is in fact a memory address (pointer)

Pointer-Array Equivalence NULL indicates a void pointer not pointing to any valid memory address (=0) int *pnum = NULL; initialize pointers to NULL for safety Allocation via new and delete[] malloc, calloc, free in standard C Array variables are pointers char string[5]; char *pc; pc = string; pointer to fixed sized array arbitrary pointer to a char Array indexing is dereferencing pc = &string[2]; *pc = string[3]; point to third element in array copy value to location at pc

Books The C++ Programming Language, by Bjarne Stroustrup, Addison Wesley, 2000 The C Programming Language ANSI C, by Brian Kernighan and Dennis Ritchie, Prentice Hall, 1988

These slides may not be copied or distributed without explicit permission by all original copyright holders