Fondamenti di C++ - Cay Horstmann 1

Size: px
Start display at page:

Download "Fondamenti di C++ - Cay Horstmann 1"

Transcription

1 Fondamenti di C++ - Cay Horstmann 1 Review Exercises R10.1 Line 2: Can't assign int to int* Line 4: Can't assign Employee* to Employee Line 6: Can't apply -> to object Line 7: Can't delete object Line 10: Explicit parameter of seconds_from must be an object, not a pointer Line 11: Can't delete object Line 14: Can't apply dot operator to pointer Line 16: Need parentheses (*t2).get_minutes() R10.3 a) You reach the object to which the pointer points b) It depends. The object may appear to be valid for some time, but it iscorrupted eventually c) The program dies with a segmentation or general protection fault d) It depends. There may appear to be an object at the random memory location,or the program may die. R10.5 The program prints The first two values are separate objects. Thus, raising the salary of onedoesn't affect the other. The second pair of values are pointers to a shared object. R10.7 The computation p[i] reaches the value that starts at address of p + i *sizeof(int) and is sizeof(int) bytes long. Since sizeof(int)!= sizeof(double),those values are just memory blocks consisting of some of the bytes of floating-pointdata. They are meaningless when considered as integers. R10.9 a) The second storage location in the array b) A pointer to that location c) The same as a) d) The fifth storage location in the array e) A pointer to the sixth storage location in the array f) 3

2 Fondamenti di C++ - Cay Horstmann 2 R10.11 You cannot return the array as the function result. Therefore, you must passin the array as a parameter: void minmax(double values[], double result[]) R10.13 a) A pointer set to 0 b) A pointer set to point to an array that contains a single 0 byte c) An array that contains a single 0 byte R10.15 Both functions append to an existing memory array instead of returning anew string that contains the concatenation. Generally, returning a new stringis more convenient, but it is impossible if you work with character arrays. The strcat function does not check whether it exceeds the target array'scapacity. The strncat function can be used instead, but it is cumbersometo compute the maximum number of characters to copy, and even more cumbersometo deal with the 0 terminator. The + operator simply allocates a string ofthe correct size. Programming Exercises P10.1 #include <string> #include <iomanip> #include <vector> using namespace std; class Person public: Constructs a person with a given n the name Person(string n); Gets the name of this the name string get_name() const; Sets the best friend of this p a pointer to the best friend void set_best_friend(person* p); Gets the best friend of this a pointer to the best friend

3 Fondamenti di C++ - Cay Horstmann 3 Person* get_best_friend() const; Adjusts the popularity counter of this d +1 or -1 void adjust_popularity(int d); Gets the popularity counter of this the popularity counter int get_popularity() const; private: string name; Person* best_friend; int popularity; ; Person::Person(string n) name = n; best_friend = NULL; popularity = 0; void Person::set_best_friend(Person* p) if (best_friend!= NULL) best_friend->adjust_popularity(-1); best_friend = p; if (best_friend!= NULL) best_friend->adjust_popularity(1); Person* Person::get_best_friend() const return best_friend; void Person::adjust_popularity(int d) popularity = popularity + d; int Person::get_popularity() const return popularity; string Person::get_name() const return name; vector<person*> people; bool more = true; while (more)

4 Fondamenti di C++ - Cay Horstmann 4 cout << "Enter name, q to quit: "; string name; getline(cin, name); if (name == "q") more = false; else people.push_back(new Person(name)); for (int i = 0; i < people.size(); i++) cout << "Who is the best friend of " << people[i]->get_name() << "? "; string name; getline(cin, name); for (int j = 0; j < people.size(); j++) if (people[j]->get_name() == name) people[i]->set_best_friend(people[j]); for (int i = 0; i < people.size(); i++) cout << setw(20) << people[i]->get_name() << "best friend=" << setw(20) << people[i]->get_best_friend()- >get_name() << "popularity=" << setw(10) << people[i]->get_popularity() << "\n"; P10.3 #include <string> #include <vector> class BankAccount public: Constructs a bank account with a zero balance. BankAccount(); Deposits money into this amount the amount to deposit. void deposit(double amount); Withdraws money from this amount the amount to withdraw. void withdraw(double amount); Gets the balance of this the balance double get_balance() const;

5 Fondamenti di C++ - Cay Horstmann 5 private: double balance; ; class Employee public: Constructs an employee with a given name, salary, and bank n the s the annual a a pointer to the bank account Employee(string n, double s, BankAccount* a); Deposits one month's salary into the bank account. void deposit_monthly_salary(); Prints this employee's information to cout. void print() const; private: string name; double salary; BankAccount* account; ; BankAccount::BankAccount() balance = 0; void BankAccount::deposit(double amount) balance = balance + amount; void BankAccount::withdraw(double amount) balance = balance - amount; double BankAccount::get_balance() const return balance; Employee::Employee(string n, double s, BankAccount* a) name = n; salary = s; account = a; void Employee::deposit_monthly_salary()

6 Fondamenti di C++ - Cay Horstmann 6 const int MONTHS_PER_YEAR = 12; account->deposit(salary / MONTHS_PER_YEAR); void Employee::print() const cout << "Employee[name=" << name << ",salary=" << salary << ",account balance=" << account->get_balance() << "]\n"; vector<employee> staff; bool more = true; string previous_lname = "q"; BankAccount* previous_account = NULL; while (more) string lname; cout << "Enter last name, q to quit: "; getline(cin, lname); if (lname == "q") more = false; else string fname; cout << "Enter first name: "; getline(cin, fname); cout << "Enter salary: "; double salary; cin >> salary; string dummy; getline(cin, dummy); if (lname!= previous_lname) previous_account = new BankAccount(); previous_lname = lname; staff.push_back(employee(lname + ", " + fname, salary, previous_account)); for (int i = 0; i < staff.size(); i++) staff[i].deposit_monthly_salary(); for (int i = 0; i < staff.size(); i++) staff[i].print(); P10.5 Computes the average of the values in an a the array

7 Fondamenti di C++ - Cay Horstmann a_size the number of elements in the the average, or 0 if the array is empty double average(double a[], int a_size) double sum = 0; double* p = a; for (int i = 0; i < a_size; i++) sum = sum + *p; p++; if (a_size == 0) else return sum / a_size; double data[] = 1, 4, 9, 16, 25 ; cout << average(data, 5) << "\n"; P10.7 Reverses the values in an a the array void reverse(double a[], int a_size) double* p = a; double* q = a + a_size - 1; while (p < q) double temp = *p; *p = *q; *q = temp; p++; q--; double data[] = 1, 4, 9, 16, 25 ; reverse(data, 5); for (int i = 0; i < 5; i++) cout << data[i] << "\n"; P10.9

8 Fondamenti di C++ - Cay Horstmann 8 Computes the length of the prefix of a string that is composed of characters in a given s the string whose maximum prefix is to be t the string whose characters are to be contained in the the length of the prefix of s consisting of characters of t (in any order) int strspn(const char s[], const char t[]) int n = 0; while (*s!= '\0') const char* p = t; while (*p!= *s && *p!= '\0') p++; if (*p == 0) // no match return n; n++; s++; return n; cout << strspn("mississippi", "ims") << "\n"; P10.11 #include <cstring> Concatenates two character arrays into a result a the first character b the second character result the array to hold the result_maxlength the maximum length of the result (not counting the '\0' terminator) void concat(const char a[], const char b[], char result[], int result_maxlength) int n = strlen(a); strncpy(result, a, result_maxlength); if (n < result_maxlength) strncat(result + n, b, result_maxlength - n); result[result_maxlength] = '\0'; char a[] = "Woozle"; char b[] = "Heffalump"; char c[5];

9 Fondamenti di C++ - Cay Horstmann 9 char d[10]; char e[20]; concat(a, b, c, 5); concat(a, b, d, 10); concat(a, b, e, 20); cout << c << "\n"; cout << d << "\n"; cout << e << "\n"; P10.13 using namespace std; const int BUFFER_CAPACITY = 1000; const int LINES_CAPACITY = 100; char buffer[buffer_capacity]; char* lines[lines_capacity]; int buffer_size = 0; int lines_size = 0; bool more = true; bool newline = true; while (more) char c = cin.get(); if (cin.fail()) more = false; else if (buffer_size >= BUFFER_CAPACITY) more = false; if (newline) if (lines_size < LINES_CAPACITY) lines[lines_size] = buffer + buffer_size; lines_size++; newline = false; else more = false; if (more) if (c == '\n') buffer[buffer_size] = '\0'; buffer_size++; newline = true; else buffer[buffer_size] = c; buffer_size++;

10 Fondamenti di C++ - Cay Horstmann 10 buffer[buffer_capacity - 1] = '\0'; for (int i = lines_size - 1; i >= 0; i--) cout << lines[i] << "\n"; P10.15 using namespace std; int buffer_capacity = 1000; int lines_capacity = 100; char* buffer = new char[buffer_capacity]; char** lines = new char*[lines_capacity]; int buffer_size = 0; int lines_size = 0; bool more = true; bool newline = true; while (more) char c = cin.get(); if (cin.fail()) more = false; else if (buffer_size >= buffer_capacity) char* new_buffer = new char[2 * buffer_capacity]; for (int i = 0; i < buffer_capacity; i++) new_buffer[i] = buffer[i]; for (int i = 0; i < lines_size; i++) lines[i] = new_buffer + (lines[i] - buffer); buffer = new_buffer; buffer_capacity = 2 * buffer_capacity; if (newline) if (lines_size >= lines_capacity) char** new_lines = new char*[2 * lines_capacity]; for (int i = 0; i < lines_capacity; i++) new_lines[i] = lines[i]; lines = new_lines; lines_capacity = 2 * lines_capacity; lines[lines_size] = buffer + buffer_size; lines_size++; newline = false; if (c == '\n') buffer[buffer_size] = '\0';

11 Fondamenti di C++ - Cay Horstmann 11 buffer_size++; newline = true; else buffer[buffer_size] = c; buffer_size++; for (int i = lines_size - 1; i >= 0; i--) cout << lines[i] << "\n";

Moving from Java to C++

Moving from Java to C++ Moving from Java to C++ This appendix explains how to transfer your Java programming skills to a substantial subset of C++. This is necessary for students who take their first programming course in Java

More information

Engineering Problem Solving with C++, Etter

Engineering Problem Solving with C++, Etter Engineering Problem Solving with C++, Etter Chapter 7 Strings 12-11-13 1 Strings Character Strings The string Class. 2 C style strings functions defined in cstring CHARACTER STRINGS 3 C Style Character

More information

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch3 Implementing Classes PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com,

More information

CISC 181 Project 3 Designing Classes for Bank Accounts

CISC 181 Project 3 Designing Classes for Bank Accounts CISC 181 Project 3 Designing Classes for Bank Accounts Code Due: On or before 12 Midnight, Monday, Dec 8; hardcopy due at beginning of lecture, Tues, Dec 9 What You Need to Know This project is based on

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

More information

Lecture 4 Notes: Arrays and Strings

Lecture 4 Notes: Arrays and Strings 6.096 Introduction to C++ January 10, 2011 Massachusetts Institute of Technology John Marrero Lecture 4 Notes: Arrays and Strings 1 Arrays So far we have used variables to store values in memory for later

More information

Chapter 3 Basic Input & Output

Chapter 3 Basic Input & Output Chapter 3 Basic Input & Output 3-1 Basic Output in C++ cout is a predefined variable in C++ that indicates you are going to output a stream of characters to an output device. cout uses an operator called

More information

Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++

Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++ Adjusted/Modified by Nicole Tobias 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

More information

Chapter 8. Arithmetic in C++

Chapter 8. Arithmetic in C++ Christian Jacob Chapter 8 Arithmetic in C++ 8.1 The C++ Vocabulary 8.2 Variables and Types 8.2.1 Data Objects 8.2.2 Variables 8.2.3 Declaration of Variables 8.3 Elementary C++ Data Types 8.3.1 Integers

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

C++ String Variables. 12. C++ Strings. The standard C++ library provides an object string type to complement the string literals used earlier:

C++ String Variables. 12. C++ Strings. The standard C++ library provides an object string type to complement the string literals used earlier: C++ String Variables 1 The standard C++ library provides an object string type to complement the string literals used earlier: string Name1, Name2; // must #include A string variable may be assigned

More information

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

UEE1302 (1102) F10 Introduction to Computers and Programming (I) Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming (I) Programming Lecture 08 Strings: C-String, Character Manipulation and Class string Learning

More information

Introduction to Programming

Introduction to Programming Introduction to Programming SS 2012 Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 Stand: April 25, 2012 Betriebssysteme / verteilte Systeme Introduction

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

CSCI-B 565 DATA MINING Project Report for K-means Clustering algorithm Computer Science Core Fall 2012 Indiana University

CSCI-B 565 DATA MINING Project Report for K-means Clustering algorithm Computer Science Core Fall 2012 Indiana University CSCI-B 565 DATA MINING Project Report for K-means Clustering algorithm Computer Science Core Fall 2012 Indiana University Jayesh Kawli jkawli@indiana.edu 09/17/2012 1. Examining Wolberg s breast cancer

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

Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

More information

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 4: Arrays,Strings, File I/O 2 Problem: Write a program to calculate the average test score for 10 students

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova Data types define the way you use the storage (memory) in the programs. By specifying a data type, you tell the sompiler how to create a particular piece

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum James P. Kelsh James.Kelsh@cmich.edu Roger Y. Lee lee@cps.cmich.edu Department of Computer Science Central

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Strings in C++ and Java. Questions:

Strings in C++ and Java. Questions: Strings in C++ and Java Questions: 1 1. What kind of access control is achieved by the access control modifier protected? 2 2. There is a slight difference between how protected works in C++ and how it

More information

C File Input and Output (I/O) CSE303 Todd Schiller November 9, 2009

C File Input and Output (I/O) CSE303 Todd Schiller November 9, 2009 C File Input and Output (I/O) CSE303 Todd Schiller November 9, 2009 Lecture goal Build a practical toolkit for working with files 11/09/09 2 Files in C #include FILE object contains file stream

More information

C Strings. Handout #06 January 23, CS106L Winter Introduction

C Strings. Handout #06 January 23, CS106L Winter Introduction CS106L Winter 2007-2008 Handout #06 January 23, 2008 C Strings Introduction C strings are very difficult to work with. Very difficult. In fact, they are so difficult to work with that C++ programmers invented

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch8 Arrays and Array Lists PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com,

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Chapter 4 Intro to Programming in C++

Chapter 4 Intro to Programming in C++ Chapter 4 Intro to Programming in C++ 4-1 Computer Programming Earlier we defined an algorithm to be a step by step process for solving a problem. Computer programming is the process of implementing the

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

1 Problem Description

1 Problem Description CSCE2014 Programming Foundations II Lab Two (week 9-9 to 9-13) By Wing Ning Li 1 Problem Description We have introduced and studied the concept of pointer variable and learned that the name of an array

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

Supplement V.F: C-Strings. For Introduction to C++ Programming By Y. Daniel Liang

Supplement V.F: C-Strings. For Introduction to C++ Programming By Y. Daniel Liang Supplement V.F: C-Strings For Introduction to C++ Programming By Y. Daniel Liang NOTE 7.8 gave a brief introduction on C-string from the array s perspectives. This supplement provides a detailed coverage

More information

1) String initialization can be carried out in the following ways, similar to that of an array :

1) String initialization can be carried out in the following ways, similar to that of an array : Strings in C : Overview : String data type is not supported in C Programming. String is essentially a collection of characters to form particular word. String is useful whenever we accept name of the person,

More information

Python to C/C++ Fall 2011

Python to C/C++ Fall 2011 Python to C/C++ Fall 2011 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. C: Both require #include directives to access libraries

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch16 Files and Streams PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch13 Inheritance PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for accompanying

More information

Variables, Constants, and Data Types

Variables, Constants, and Data Types Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class: L&L, 2.1-2.3, App C 1 Primitive Data There are eight

More information

C++ Basics. C++ Basics: Names: Identifiers. Names: Identifiers. Display 2.1 A C++ Program (1 of 2) Display 2.1 A C++ Program (2 of 2)

C++ Basics. C++ Basics: Names: Identifiers. Names: Identifiers. Display 2.1 A C++ Program (1 of 2) Display 2.1 A C++ Program (2 of 2) C++ Basics C++ Basics: 2.1 Variables and Assignments Variables and Assignments Input and Output Data Types and Expressions Simple Flow of Control Program Style A C++ variable can hold a number or other

More information

SYSTEMS PROGRAMMING C++ INTRODUCTION

SYSTEMS PROGRAMMING C++ INTRODUCTION Faculty of Computer Science / Institute of Systems Architecture / Operating Systems SYSTEMS PROGRAMMING C++ INTRODUCTION Alexander Warg WHY C++? C++ is the language that allows to express ideas from the

More information

ICOM 4015: Advanced Programming

ICOM 4015: Advanced Programming ICOM 4015: Advanced Programming Lecture 10 Reading: Chapter Ten: Inheritance Copyright 2009 by John Wiley & Sons. All rights reserved. Chapter 10 Inheritance Chapter Goals To learn about inheritance To

More information

Answers to Selected Exercises

Answers to Selected Exercises DalePhatANS_complete 8/18/04 10:30 AM Page 1049 Answers to Selected Exercises Chapter 1 Exam Preparation Exercises 1. a. v, b. i, c. viii, d. iii, e. iv, f. vii, g. vi, h. ii. 2. Analysis and specification,

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

A Rudimentary Intro to C programming

A Rudimentary Intro to C programming A Rudimentary Intro to C programming Wayne Goddard School of Computing, Clemson University, 2008 Part 4: Strings and Pointers 18 Strings.................................... D1 19 String Functions..............................

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

GETTING STARTED WITH C++ C++ BASICS - 1 -

GETTING STARTED WITH C++ C++ BASICS - 1 - - 1 - GETTING STARTED WITH C++ Programming is a core activity in the process of performing tasks or solving problems with the aid of a computer. An idealised picture is: PROBLEM COMPUTER SOLUTION Unfortunately

More information

Programming Fundamental. Instructor Name: Lecture-2

Programming Fundamental. Instructor Name: Lecture-2 Programming Fundamental Instructor Name: Lecture-2 Today s Lecture What is Programming? First C++ Program Programming Errors Variables in C++ Primitive Data Types in C++ Operators in C++ Operators Precedence

More information

String Processing in C

String Processing in C String Processing in C C Programming and Software Tools N.C. State Department of Computer Science Standard Library: Many functions for checking whether a character is a digit, is upper case,

More information

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Chapter 9, More SQL: Assertions, Views, and Programming Techniques Chapter 9, More SQL: Assertions, Views, and Programming Techniques 9.2 Embedded SQL SQL statements can be embedded in a general purpose programming language, such as C, C++, COBOL,... 9.2.1 Retrieving

More information

Primitive Data Types Summer 2010 Margaret Reid-Miller

Primitive Data Types Summer 2010 Margaret Reid-Miller Primitive Data Types 15-110 Summer 2010 Margaret Reid-Miller Data Types Data stored in memory is a string of bits (0 or 1). What does 1000010 mean? 66? 'B'? 9.2E-44? How the computer interprets the string

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

Selection: if Statement

Selection: if Statement : if Statement The simplest selection structure in C++ is the if statement. Syntactically: 1 if The Boolean expression must be enclosed in parentheses, and

More information

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

7.7 Case Study: Calculating Depreciation

7.7 Case Study: Calculating Depreciation 7.7 Case Study: Calculating Depreciation 1 7.7 Case Study: Calculating Depreciation PROBLEM Depreciation is a decrease in the value over time of some asset due to wear and tear, decay, declining price,

More information

CS101 Computer programming and utilization

CS101 Computer programming and utilization CS101 Computer programming and utilization Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 3, Basic features of C++ Tuesday, 2 August 2011

More information

CSCI 123 Introduction to Programming Concepts in C++

CSCI 123 Introduction to Programming Concepts in C++ CSCI 123 Introduction to Programming Concepts in C++ Brad Rippe String and Vectors Overview 8.1 An Array Type for Strings 8.2 The Standard string Class 8.3 Vectors 8.1 An Array Type for Strings An Array

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

Format String Vulnerability. printf ( user input );

Format String Vulnerability. printf ( user input ); Lecture Notes (Syracuse University) Format String Vulnerability: 1 Format String Vulnerability printf ( user input ); The above statement is quite common in C programs. In the lecture, we will find out

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

C++ Keywords. If/else Selection Structure. Looping Control Structures. Switch Statements. Example Program

C++ Keywords. If/else Selection Structure. Looping Control Structures. Switch Statements. Example Program C++ Keywords There are many keywords in C++ that are not used in other languages. bool, const_cast, delete, dynamic_cast, const, enum, extern, register, sizeof, typedef, explicit, friend, inline, mutable,

More information

Lecture: #6. More About Characters, Strings, and the string Class

Lecture: #6. More About Characters, Strings, and the string Class Lecture: #6 More About Characters, Strings, and the string Class 1 C-Strings Topics 2 Library Functions for Working with C-Strings 3 Conversions Between Numbers and Strings 4 Character Testing 5 Character

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Each statement is ended by a semi-colon (;). The formatting is free.

Each statement is ended by a semi-colon (;). The formatting is free. Example 1 cout x; double err, tol=1e-12, x1; int it, maxit=100; it = 0; err = tol + 1; while( err > tol && it < maxit ) x1 = x - (x-cos(x))/(1+sin(x)); err = fabs(

More information

Pointers and Strings. Objectives

Pointers and Strings. Objectives 5 Pointers and Strings Objectives To be able to use pointers. To be able to use pointers to pass arguments to functions by reference. To understand the close relationships among pointers, arrays and strings.

More information

Logging. Working with the POCO logging framework.

Logging. Working with the POCO logging framework. Logging Working with the POCO logging framework. Overview > Messages, Loggers and Channels > Formatting > Performance Considerations Logging Architecture Message Logger Channel Log File Logging Architecture

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

Inheritance, overloading and overriding

Inheritance, overloading and overriding Inheritance, overloading and overriding Recall with inheritance the behavior and data associated with the child classes are always an extension of the behavior and data associated with the parent class

More information

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Dr. Martin O. Steinhauser University of Basel Graduate Lecture Spring Semester 2014 Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Friday, 7 th March

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

strsep exercises Introduction C strings Arrays of char

strsep exercises Introduction C strings Arrays of char strsep exercises Introduction The standard library function strsep enables a C programmer to parse or decompose a string into substrings, each terminated by a specified character. The goals of this document

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

Exercise 4 Logical Operators & Branching

Exercise 4 Logical Operators & Branching Exercise 4 Logical Operators & Branching Informatik I für D-MAVT (FS 2013) Christian Schumacher chschuma@inf.ethz.ch Agenda Branching relational operators logical expressions: and, or, not if, else if,

More information

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. JAVA TYPES BASIC DATA TYPES GENERAL Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type

More information

Using C++ with CPLEX

Using C++ with CPLEX Using C++ with CPLEX Daniel Simmons, Dr. Qipeng Phil Zheng Department of Industrial and Management Systems Engineering West Virginia University Nonlinear Programming, Summer 2012 D. A. Simmons (IMSE@WVU)

More information

Characters and Strings. Constants

Characters and Strings. Constants Characters and Strings Constants Characters are the fundamental building blocks of source programs Character constants One character surrounded by single quotes A or? Actually an int value represented

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD 1 Slides 1. Table of Contents 2. Definitions 3. Simple 4. Recursive Execution Trace 5. Attributes 6. Recursive Array Summation 7. Recursive Array Summation Trace 8. Coding Recursively 9. Recursive Design

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types In this lecture Computer Languages Assembly Language The compiler Operating system Data and program instructions Bits, Bytes and Data Types ASCII table Data Types

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 3 Control Structures 1 Control structures Algorithm Development Conditional Expressions Selection Statements Repetition Statements Structuring

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

Python 3.3 to C/C++ Summer 2014

Python 3.3 to C/C++ Summer 2014 Python 3.3 to C/C++ Summer 2014 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. Both require #include directives to access libraries

More information

Common Syntax and Semantic Errors

Common Syntax and Semantic Errors C H A P T E R 2 Common Syntax and Semantic Errors 2.1 CHAPTER OBJECTIVES To understand the fundamental characteristics of syntax and semantic errors To be able to identify specific common syntax and semantic

More information

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s Quiz 4 Solutions Q1: What value does function mystery return when called with a value of 4? int mystery ( int number ) { if ( number

More information

SIF Validation Tool. Wages Protection System Qatar Central Bank& Ministry of Labour And Social Affairs. End User Guide

SIF Validation Tool. Wages Protection System Qatar Central Bank& Ministry of Labour And Social Affairs. End User Guide SIF Validation Tool Wages Protection System Qatar Central Bank& Ministry of Labour And Social Affairs End User Guide [1] SIF Validation Tool at a Glance Content 1 SIF VALIDATION TOOL AT A GLANCE 3 2 GETTING

More information