C++ Arrays and Vectors
|
|
- Carol Harrison
- 5 years ago
- Views:
Transcription
1 C++ Arrays and Vectors Contents 1 Overview of Arrays and Vectors 2 2 Arrays Declaring Arrays Initializing Arrays Referring to Elements of an Array Using Constants to Prevent Hardcoding of Array Sizes Passing Arrays to Functions Multidimensional Arrays List of Array Difficulties Vectors Creating Vectors Referring to Elements of Vectors Determining the Length of a Vector Growing/Shrinking Vectors Passing Vectors to Functions Returning Vectors from Functions An Overview of all Vector methods/operators Common Misconceptions about Vectors
2 1 Overview of Arrays and Vectors So far in C++ we ve been working with variables of different types We ve talked about data structures, but haven t actually used any Today we start talking about and working with simple data structures known as arrays and vectors Both arrays and vectors are essentially the same thing, but vectors are a bit more flexible Arrays are built-in to the C++ language, but vectors are provided as a standard extension, the same way strings are As such, we ll talk about arrays first Arrays and vectors allow one to define an ordered sequence of variables, each of the same time, and each accessible by a different name We can use such data structures to store a list of data, such as grades (ints or floats), usernames (strings), etc. 2
3 2 Arrays 2.1 Declaring Arrays As mentioned above, an array is a sequence of variables each of the same type Arrays are defined by adding a set of square brackets ([ ]) after a variables name, and... Inside the square brackets goes a whole number, 0, that tells C++ how many elements will be stored in the array (call this the size of the array) So, to define an array named grades which contains 10 grades, each stored as floats, we would do the following float grades[10]; If we wanted to define an array containing the price (in pennies) of 20 different items, we could do the following int prices[20]; When array declarations are made, and those arrays come into scope, the amount of memory allocated is equal to the amount of memory needed for a single variable, times the size of the array Note that with arrays, each of the n variables (where n is the size of the array) are stored continuously in memory (right next to each other, in order) Note also that the size of an array can never change! They are a fixed size data structure (we ll see how vectors can overcome this difficulty) When declaring an array, its size must be able to be determined at compile time!, NOT at run time! E.g. the following will not work the way you expect... cout << "Enter number of students: "; cin >> numstudents; float studentgrades[numstudents]; string studentnames[numstudents]; Specifically, the size of an array in an array declaration must be an integer constant 0! We ll see later how vectors can also overcome this difficulty 3
4 2.2 Initializing Arrays When we define normal (non-array) variables, we ve seen how we can set the value of the variable in the declaration. E.g. double pi = ; We can do the same thing with arrays, setting their values in their declaration This is accomplished by putting the sequence of values in a set of curly braces ({ }), each separated by a comma (,). float grades[3] = { 100.0, 92.3, 79.5 }; Note that the number of elements in curly braces must be the the size of the array If fewer elements are initialized than the size of the array, then only the first few are set If more elements are initialized then the size of the array, a compiler error is generated 2.3 Referring to Elements of an Array Now that we can declare arrays and initialize them, how do we access them? To access each element of an array named foo, use the name foo (just like you would for a variable) with a set of square brackets after the name ([ ]) containing the index of the element you want CAVEAT: Note that array indices start at 0, not 1!!! cout << foo[5] << endl; So if you define an array of size n, valid indices are 0 to n 1 EVEN WORSE CAVEAT: If we declare an array of size, say 10, only indices of 0 to 9 will actually access memory within the array Values larger than 9 will compile, and retrieve something But that something is usually garbage! Note that you can also modify memory outside the range of the array by using indices which are too large This is called an (array) out-of-bounds error, and is (sadly) extremely common Failing to check an index to make sure it s valid for a given array is the key component in code injection techniques (responsible for many, many security breaches) 4
5 2.4 Using Constants to Prevent Hardcoding of Array Sizes In the examples so far, all of the arrays have been declared using fixed integers like 5 or 10 This can become cumbersome when we use the size of the array for things like looping through the array As we said earlier, the size must be a constant integer expression so that the size can be determined at compile time To make things easier, we can use const int constants to make things a little easier const int arraysize = 5; float studentgrades[arraysize]; string studentnames[arraysize]; 2.5 Passing Arrays to Functions Now that we have arrays, and have recently covered functions, we ll see how to pass an array to a function The syntax is rather easy... To pass an array to a function, the parameter of the function that will be filled with an array simply needs an empty set of square brackets ([]) after the parameter name int sumarray(int somearray[], int size) It s not required to pass the size of the array as a parameter, but if you do not, you will be unable to determine the size of the array from within the function! Again, vectors do not have this problem/requirement C++ always passes arrays to functions by reference, since the cost of allocating a copy of the array for each function call would be rather costly example... This is a nice optimization, but if the function should not modify the array (like in the previous example), const should be used to ensure this example... int sumarray(const int somearray[], int size) 5
6 2.6 Multidimensional Arrays We ve seen how to construct and use simple arrays, which are just sequences of values Now we (briefly) look at multidimensional arrays, which are used primarily to store tables of values Multidimensional arrays are initialized just like regular arrays, only we have to include additional brackets & sizes for each dimension E.g. So, if we wanted to create a 10x2 array of integers... type name[size1][size2][size3];\verb int mytable[10][2]; To initialize multidimensional arrays we use the curly braces just as we did for normal arrays, only each element of the array is treated as another array, and thus specified using another set of curly braces For example, int mytable[4][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; Array elements are accessed just as we did for regular arrays, only we must specify an index for each dimension mytable[0][2] = -5.6; 6
7 Be sure to note the following caveat of multidimensional arrays, discussed in the book! When passing multidimensional arrays to functions, we use the syntax you would probably expect, except that we must include the size for all dimensions except the first! example... Keep in mind that a 2-dimensional array is simply an array of arrays. A 3-dimensional array is simply an array of arrays of arrays. With multidimensional arrays, each sub-array must be of the same size. I.e. one cannot have an array containing one 10 element array, one 2 element array, and one 5 element array 7
8 2.7 List of Array Difficulties As we ve seen above, arrays in C++ have the following problems 1. The size of an array must be able to be determined at compile time 2. The size of an array cannot change/grow/shrink with the needs of the program 3. When working with arrays, we usually need a constant set to the size to eliminate use of integer constants such as 5 and When passing arrays to functions, we need to pass the size as well 5. Array out-of-bounds errors! One of the most common bugs in large software 6. When passing multidimensional arrays to functions, we have to include all but the first dimension in the function definition, making it difficult to define functions over general multidimensional arrays 7. Also, multidimensional arrays are of fixed size 8. Arrays are always allocated continuously in memory. Although this makes for quick access to each element, allocating large arrays may require more time, and if enough continuous memory isn t available an error will occur 9. Common operators like assignment (=), equality checking (== and!=), and ordering (<, <=, etc.) do not work as expected with arrays For each of these problems, C++ vectors have a solution 8
9 3 Vectors Unlike arrays, vectors are not a built-in data type to C++ Vectors are, however, a standard extension As such, in any environment (OS/compiler/architecture), you can simply use #include <vector> include the vector library 3.1 Creating Vectors Before we show how to create a vector, let s consider the following... As said previously, vectors are very much like arrays We would like to be able to create vectors of, say, integers (int), doubles (double), and even strings (string). BUT, we want to be able to create a vector of any type To do this, C++ provides a mechanism called templated classes, which are very similar to the notion of a templated function Vectors are implemented this way, so for any data type you can create a vector The general format for declaring a vector is the following vector< type > name; where type is the type of vector you want to create (int, double, string, etc.) and name is the name of the vector For example, a vector containing a list of, say, student names would be vector< string > studentnames; Unlike arrays, we do not have to specify a size in the declaration of a vector. It can grow or shrink as we need it! However if you know ahead of time how large of a vector you would need, you can specify how many elements by 9
10 vector< string > studentnames(20); Note that the size is NOT placed in square brackets, but rather parentheses! If you wanted to initialize a vector by simply setting all elements to the same value, you could use E.g. the following creates a vector named studentgrades which contains 20 doubles, all initialized to 0 vector<double> studentgrades(20, 0.0); There is no way to initialize vectors to individual values like we can with arrays! 3.2 Referring to Elements of Vectors Similar to an array, individual elements of a vector can be read or modified using square brackets with an index within them E.g. studentnames[0] = "Optimus Prime"; cout << studentnames[0] << endl; Using the square brackets provides direct access to each of the elements HOWEVER, just like with arrays, use of the square brackets can result in out-of-bounds problems To solve this, the vector class has a method called at, which you pass an index (just like brackets) and it provides direct access both for retrieving and modifying individual elements of a vector studentnames.at(0) = "Optimus Prime"; cout << studentnames.at(0) << endl; That is, the at method is used exactly the same as the square brackets 10
11 The only difference, however, is that any attempt to access elements beyond the size of the array will result in a run-time error! So why do the brackets not check for out-of-bounds errors? 3.3 Determining the Length of a Vector Given a vector named, say, studentnames, we can determine the current size of the vector (how many elements it has), simply by using studentnames.size(); So, rather than passing around constants for the size of an array, we can retrieve the length from the object itself! for (int count = 0; count < studentnames.size(); count++) studentnames.at(count) = rand() % Growing/Shrinking Vectors As mentioned previously, vectors can grow and shrink with the needs of our program We ll cover two methods for growing & shrinking vectors... Suppose we have a vector that we want to incrementally add new elements to, without knowing how many total ahead of time We could use the method push back(element) which extends the size of the vector by one and inserts the element element into the new position (It pushes a new element onto the back of the vector) Note that this method only increases the size of a vector, by exactly one element 11
12 Similarly, we may want to remove a single element from a vector at a time, and shrink the size of the vector by one element as-we-go For this, we could use the pop back() method, which removes the last element of the vector (freeing the memory) and shrinking the size of the vector by exactly 1 In addition to the above methods, we could have also use the method resize(newsize) to set the size of the vector to newsize If newsize is greater than the current size of the vector, new un-assigned elements are added to the end of the vector If newsize is less than the current size of the vector, then all elements after the newsize th element will be removed! 3.5 Passing Vectors to Functions We can pass vectors to functions much easier that we can arrays void printstudentgrades(vector<double> grades); Note that unlike arrays, vectors will not be passed by reference by default If you want to do that, you ll have to explicitly say so... be sure to use const if you re only doing this to save memory! void printstudentgrades(const vector<double> &grades); 12
13 3.6 Returning Vectors from Functions In addition to passing vectors as individual values to functions, we can also return vectors! vector<int> multiplypolynomials(vector<int> polya, vector<int> poly2); 3.7 An Overview of all Vector methods/operators The following operators work with vectors. Suppose vec, vec1, and vec2 are vectors... vec[i] (Bracket-access) Provides direct access to the i th element of a vector. vec1 = vec2 (Assignment) Copies the vector vec2 into vec1. All memory consumed by vec1 is either re-used or freed. vec1 == vec2 (Equality) Returns true if and only if vec1 and vec2 have the same size, and each element in each vector are equal vec1!= vec2 (Inequality) Returns the negation of vec1 == vec2 vec1 < vec2 (Less-Than) Compares vectors lexicographically (same for <=, >, >=). Additionally, the following methods are provided. Suppose vec is a vector... vec.at(i) Provides direct access to the element at location i in the vector. If there is no i th element, an error is produced (this is meant to replace the [i] operators with vectors). Note that this can also be used for assignment (e.g. vec.at(i) = 5). vec.size() Returns an integer indicating how many elements are in the vector. Does not modify the vector. vec.resize(newsize) Will shrink/grow the vector to contain newsize elements. If newsize is less than vec.size(), all elements after the newsize th element are deleted. vec.empty() Returns a boolean value. True is returned if the vector is empty (has no elements). Otherwise, false is returned. Does not modify the vector. vec.clear() Clears all data from the vector, freeing all memory allocated. Does not return a value. vec.push back(newelement) Extends the size of the vector by one and inserts newelement into this new location. Nothing is returned. vec.pop back() Deletes the last element in the vector and shrinks the vector by one element. vec.capacity() Returns a positive integer indicating how many more elements can be added to the array before more memory will need to be allocated. (Vectors allocate memory in chunks ) Does not modify the vector. 13
14 3.8 Common Misconceptions about Vectors Many people think that the standard C++ vector class is inefficient (either in terms of memory or time, or both). Nothing could be further from the truth! The vector class is highly optimized for both time and memory. Although the vector class appears the same no matter where you use it (in UNIX, Linux, Mac OS X, Windows, Windows using Visual Studio compiler, Windows using Borland compiler, on Intel architecture, AMD architecture, Sparc64, PowerPC architecture, etc.) each combination has a highly specific implementation that takes advantage of all the system has available! In addition, the standard C++ vector class(es) are extremely well tested. The chance of finding an error in this class (or any of the standard C++ classes) is quite small. Using these standard C++ data structures such as vectors is considered an extremely good practice 14
CSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College October 25, 2017 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Function Details Assert Statements
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More informationCONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays
CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202
More informationC++ Data Types. 1 Simple C++ Data Types 2. 3 Numeric Types Integers (whole numbers) Decimal Numbers... 5
C++ Data Types Contents 1 Simple C++ Data Types 2 2 Quick Note About Representations 3 3 Numeric Types 4 3.1 Integers (whole numbers)............................................ 4 3.2 Decimal Numbers.................................................
More informationCS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals
CS125 : Introduction to Computer Science Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals c 2005, 2004, 2003, 2002, 2001, 2000 Jason Zych 1 Lecture 6 : Compound Statements, Scope,
More informationCSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,
More informationMemory and Pointers written by Cathy Saxton
Memory and Pointers written by Cathy Saxton Basic Memory Layout When a program is running, there are three main chunks of memory that it is using: A program code area where the program itself is loaded.
More informationLab # 02. Basic Elements of C++ _ Part1
Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special
More informationC++ PROGRAMMING SKILLS Part 4: Arrays
C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More information6. Pointers, Structs, and Arrays. March 14 & 15, 2011
March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More informationArrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff
and Arrays Comp Sci 1570 Introduction to C++ Outline and 1 2 Multi-dimensional and 3 4 5 Outline and 1 2 Multi-dimensional and 3 4 5 Array declaration and An array is a series of elements of the same type
More informationCISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)
CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts) For this lab you may work with a partner, or you may choose to work alone. If you choose to work with a partner, you are still responsible for the lab
More informationObjectives. 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 informationChapter 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 informationChapter 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 informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationControl Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003
Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an
More informationDiscussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;
More informationCSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators
Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationExam 3 Chapters 7 & 9
Exam 3 Chapters 7 & 9 CSC 2100-002/003 29 Mar 2017 Read through the entire test first BEFORE starting Put your name at the TOP of every page The test has 4 sections worth a total of 100 points o True/False
More informationPointers in C/C++ 1 Memory Addresses 2
Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................
More information6. Pointers, Structs, and Arrays. 1. Juli 2011
1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung
More informationcalling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
More informationFor example, let s say we define an array of char of size six:
Arrays in C++ An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location, we specify the name and then the positive index into
More informationC++ 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 informationArray Elements as Function Parameters
Arrays Class 26 Array Elements as Function Parameters we have seen that array elements are simple variables they can be used anywhere a normal variable can unsigned values [] {10, 15, 20}; unsigned quotient;
More informationC++ Support Classes (Data and Variables)
C++ Support Classes (Data and Variables) School of Mathematics 2018 Today s lecture Topics: Computers and Programs; Syntax and Structure of a Program; Data and Variables; Aims: Understand the idea of programming
More informationCS2255 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 information1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?
1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming
More informationCSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators
CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationCOMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal
COMSC-051 Java Programming Part 1 Part-Time Instructor: Joenil Mistal Chapter 4 4 Moving Toward Object- Oriented Programming This chapter provides a provides an overview of basic concepts of the object-oriented
More informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More information1. In C++, reserved words are the same as predefined identifiers. a. True
C++ Programming From Problem Analysis to Program Design 8th Edition Malik TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/c-programming-problem-analysis-program-design-8thedition-malik-test-bank/
More informationCSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory
Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.
More informationChapter 6 SINGLE-DIMENSIONAL ARRAYS
Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference
More informationCSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC
CSCI 262 Data Structures 9 Dynamically Allocated Memory POINTERS AND ARRAYS 2 Arrays Arrays are just sequential chunks of memory: Arrays and Pointers Array variables are secretly pointers: x19 x18 x17
More informationThe Dynamic Typing Interlude
CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,
More informationObjectives. In this chapter, you will:
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 arithmetic expressions Learn about
More informationChapter 4 Computation
Chapter 4 Computation Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/spring_2011/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using C++ Abstract
More informationCSE 142 Su 04 Computer Programming 1 - Java. Objects
Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request
More information377 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 informationEC312 Chapter 4: Arrays and Strings
Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. EC312 Chapter 4: Arrays and Strings (c) Describe the implications of reading or writing
More informationData types. CISC 1600/1610 Computer Science I. Array syntax. Memory allocation. Zero-indexing 4/4/2016. Arrays
4/4/6 CISC 6/6 Computer Science I rrays Professor Daniel Leeds dleeds@fordham.edu JMH 38 Data types Single pieces of information one integer int one symbol char one truth value bool Multiple pieces of
More informationThese are notes for the third lecture; if statements and loops.
These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern
More informationMultiple-Subscripted Arrays
Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and
More informationConcurrent Data Structures in C++ CSInParallel Project
Concurrent Data Structures in C++ CSInParallel Project July 26, 2012 CONTENTS 1 Concurrent Data Structures in C++: Web crawler lab 1 1.1 Your goals................................................ 1 1.2
More informationC++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections
C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics
More informationChapter 3: Arrays and More C Functionality
Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading
More informationLecture on pointers, references, and arrays and vectors
Lecture on pointers, references, and arrays and vectors pointers for example, check out: http://www.programiz.com/cpp-programming/pointers [the following text is an excerpt of this website] #include
More informationArrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming
Arrays: Higher Dimensional Arrays CS0007: Introduction to Computer Programming Review If the == operator has two array variable operands, what is being compared? The reference variables held in the variables.
More information7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using
More informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationTutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays
Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing
More informationPIC 10A Flow control. Ernest Ryu UCLA Mathematics
PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if
More informationCSCE 121 ENGR 112 List of Topics for Exam 1
List of Topics for Exam 1 If statements o How is an if statement constructed? o Does every if need an else? Looping o While loop! What does a while loop look like?! How do you ensure you will not have
More informationPointers, 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 informationFunctions, Pointers, and the Basics of C++ Classes
Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.
More informationLESSON 3 CONTROL STRUCTURES
LESSON CONTROL STRUCTURES PROF. JOHN P. BAUGH PROFJPBAUGH@GMAIL.COM PROFJPBAUGH.COM CONTENTS INTRODUCTION... Assumptions.... Logic, Logical Operators, AND Relational Operators..... - Logical AND (&&) Truth
More informationChapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array variable that can store multiple values of the same type (aggregate type) Values are stored in adjacent memory locations
More informationFor Teacher's Use Only Q No Total Q No Q No
Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9
More informationChapter Six: Arrays and Vectors
Chapter Six: Arrays and Vectors Slides by Evan Gallagher Chapter Goals To become familiar with using arrays and vectors to collect values To learn about common algorithms for processing arrays and vectors
More informationBoolean Expressions. Is Equal and Is Not Equal
3 MAKING CHOICES Now that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer
More informationBoolean Expressions. Is Equal and Is Not Equal
3 MAKING CHOICES ow that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer program
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More information7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology
Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More informationpublic class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {
Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they
More informationObjectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips
Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and
More informationRelational Operators and if. Class 10
Relational Operators and if Class 10 Data Type a data type consists of two things: Data Type a data type consists of two things: a set of values Data Type a data type consists of two things: a set of values
More informationReview: Expressions, Variables, Loops, and more.
Review: Expressions, Variables, Loops, and more. 1 An Expression Evaluator Example [2] Wk02.1 Slide 1 2 Case Study : Parsing PostFix Expressions What is an expression? A series of symbols that return some
More informationUEE1302 (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 07 Arrays: Basics and Multi-dimensional Arrays Learning Objectives
More informationChapter 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 information9. MATHEMATICIANS ARE FOND OF COLLECTIONS
get the complete book: http://wwwonemathematicalcatorg/getfulltextfullbookhtm 9 MATHEMATICIANS ARE FOND OF COLLECTIONS collections Collections are extremely important in life: when we group together objects
More informationC++ Programming Lecture 1 Software Engineering Group
C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in
More informationCS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010
CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please
More informationQuiz 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 informationCS201 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 informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More information11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:
11. Arrays An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example,
More informationPIC 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 informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationKingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS
Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size
More informationComp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57
Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike
More informationVariables. 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 informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More information6.096 Introduction to C++
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. 6.096 Lecture 3 Notes
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More informationLecture Notes on Memory Layout
Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,
More informationCS50 Supersection (for those less comfortable)
CS50 Supersection (for those less comfortable) Friday, September 8, 2017 3 4pm, Science Center C Maria Zlatkova, Doug Lloyd Today s Topics Setting up CS50 IDE Variables and Data Types Conditions Boolean
More informationC Language Programming
Experiment 2 C Language Programming During the infancy years of microprocessor based systems, programs were developed using assemblers and fused into the EPROMs. There used to be no mechanism to find what
More informationAlgorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14
Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14 Ziad Matni Dept. of Computer Science, UCSB Administra:ve Turn in Homework #12 Homework #13 is due Tuesday Lab
More informationThere are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.
Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate
More informationModule 201 Object Oriented Programming Lecture 10 - Arrays. Len Shand
Module 201 Object Oriented Programming Lecture 10 - Arrays Len Shand Methods Arrays One dimensional Multi dimensional The variables you have been working with so far have only been able to hold one value
More informationChapter 4. Computation. Bjarne Stroustrup.
Chapter 4 Computation Bjarne Stroustrup www.stroustrup.com/programming Abstract Today, I ll present the basics of computation. In particular, we ll discuss expressions, how to iterate over a series of
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #44 Multidimensional Array and pointers In this video, we will look at the relation between Multi-dimensional
More informationArrays in Functions!
Arrays in Functions! 1E3! Topic 12! 12 Arrays in Functions 1 Objectives! n This topic should allow students to! n Pass array elements to functions! n Pass whole arrays to functions! n Write functions that
More informationLoops and Files. of do-while loop
L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.
More informationCome and join us at WebLyceum
Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad
More information