CS 1410 Midterm 3 (7-8) Arrays, Strings and C-strings

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

strcat

C-string Concatenation Function (it's a pass by pointer, so its an INOUT) char* strcat(char* s1, const char* s2); Concatenates s2 at the end of s1, returns s1 Example: cout << strcat(s1, s2) << endl;

strcpy

C-string Copy Function Example: cout << strcpy(s1, s2) << endl;

strlen

C-string Length Function. returns the number of characters in a C-string before the nulltermination character; the null-termination character is NOT counted char* s1 = "hello world"; char s2[100] = "hello world"; V strlen(s1) and strlen(s2) both return 11

CLI

Command Line Interface

getline function for C-string

Example char score[10]; cin.getline(score, 10);

Will the compiler detect and report an error if you tried to access array element 14 in an array of size 10? T/F

F

Will the computer always detect and report an error when you run a program that tries to access array element 14 in an array of size 10? T/F

F

C-strings are not based on pointers, only arrays T/F

F C-strings are based on arrays and pointers

C++ has two string data types T/F

T

Can C-strings be shorter than the array it is being stored in? T/F

T

If you have an array named scores, you can't just write scores.length to find the length of the array? T/F

T

The extractor operator >> ignores spaces, and continues reading through the string T/F

T The >> operator stops reading a string when it encounters a space

A C++ program defines a function as void f(int* data) { . . . } where data is a one-dimensional array of integers. Choose the best statement about the size of (i.e., the number of elements in) the array. int size = sizeof(data) / sizeof(int); int size = data.length; The size of the array must either be known beforehand or be passed in as a function argument. Change the definition from "int* data" to "int data[]" and then answer (a) will work.

The size of the array must either be known beforehand or be passed in as a function argument.

What is npos?

The string class defines a symbolic constant named npos, which is the largest possible value for the data type size_t.

Does C++ allow four dimensional arrays? Yes/No?

Yes

Does an array function argument allow data to be passed both into and out of the function? Yes/No?

Yes

Write a statement that takes element j of array doubleArray and writes it to cout with the insertion operator.

cout << doubleArray[j];

Define an array of type double, that is named "coefficients", and matches the following array: ▯▯▯ ▯▯▯ ▯▯▯ ▯▯▯ ▯▯▯

double coefficients[5][3];

Write a statement that defines a one-dimensional automatic array called doubleArray of type double that holds 100 elements; define the array as an automatic variable.

double doubleArray[100];

Write a complete function (DO NOT WRITE A COMPLETE PROGRAM: no main, no input, no output) named average that takes two arguments as described below and returns a double: the first argument, named scores, is a one-dimension array of doubles, that are test scores the second argument, named size, is an int that is the number of elements in the scores array the return value is the average or mean of all of the test scores

double mean(double* scores, int size) { double sum = 0; for (x = 0; x < size; x++) { sum += scores[x]; } return sum / size; }

When a character is accessed in a C-string, C++ always checks index and validates that it is within bounds. true false

false

When a character is accessed in an instance of the string class, C++ always checks the index and validates that it is within bounds (caution, this is a trick question). true false

false

Given an array whose size is stored in the variable size, choose the correct for-loop to use to reverse the elements in the array. for (int i = 0; i < size; i++) for (int i = 0; i < size / 2; i++) for (int i = 1; i <= size; i++) for (int i = 1; i <= size / 2; i++)

for (int i = 0; i < size / 2; i++)

Given the variable definition string name; write a statement that is able to read "Chuck N. Testa" from the console into name.

getline(cin, name);

If s is an instance of the string class, choose the best way to find its length. strlen(s) s.strlen s.strlen() strlen.s s.length s.length()

s.length()

Test for inequality for strings

s1 != s2

Comparing strings

s1 < s2 (does s1 come before s2) s1.compare(s2)

Choose an expression that tests two instances of the sting class for equality. s1 == s2 strcmp(s1, s2) == 0

s1 == s2

Length operations for strings

s1.length() s1.size()

Character access for C-strings

s1[i] no bounds checking

Character access for strings

s1[i] no bounds checking s1.at(i) bounds checking enabled

If s1 and s2 are both instances of the C++ string class, choose the best statement to copy s1 to s2. s2 = s1; strcpy(s2, s1); strcpy(s1, s2);

s2 = s1; destination = source

Copying strings

s3 = s1

All the elements in an array must be the ____________data type

same

Given the definition string s; and assuming that variable s is appropriately initialized, which expression best converts s to a value of type double? to_string(s) stod(s) ftoa(f, s, 10) atof(s) strtod(s, nullptr);

stod(s)

Choose an expression that tests two C-strings for equality. s1 == s2 strcmp(s1, s2) == 0

strcmp(s1, s2) == 0

Test for inequality for C-strings

strcmp(s1,s2) != 0 or strcmp(s1,s2)

Comparing C-strings

strcmp(s1,s2) < 0

Write a statement that uses a C-string library function to copy the C-string "name" to the C-string "blank" which is defined as char blank[100];

strcpy(blank, name);

If s1 and s2 are defined C-strings, how would you copy s1 to s2? s2 = s1; strcpy(s2, s1); strcpy(s1, s2);

strcpy(s2, s1); (destination, source)

Copying C-strings

strcpy(s3, s1)

getline function for string class

string score; getline(cin, score);

If s is a C-string, what would be the best way to find it's length? strlen(s) s.strlen s.strlen() strlen.s s.length s.length()

strlen(s)

Length operations for C-strings

strlen(s1) strlen(s1) == 0

When a multidimensional array is accessed, each array INDEX is separated by commas. surrounded by brackets and separated by commas. separated by commas and surrounded by brackets. surrounded by brackets.

surrounded by brackets.

A program defines an array as: int a[10]; which function is able to correctly accept a as an argument? void func(int m[]) { ... } void func(int* m) { ... } void func(int m[10]) { ... } None of the above

void func(int m[]) { ... } void func(int* m) { ... } void func(int m[10]) { ... }

A program defines a two-dimensional array as: int mat[5][10]; which function is able to correctly accept mat as an argument? void func(int m[][]) { ... } void func(int m[][10]) { ... } void func(int m[5][10]) { ... } void func(int m[5][]) { ... } None of the above

void func(int m[][10]) { ... } void func(int m[5][10]) { ... }

C string header file

#include <cstring> Only needed if using the C-string functions #include <string.h>

If itr is a string iterator, write the expression to access the character currently referenced by the iterator (just get the character, don't increment or decrement the iterator).

*itr

/ Bulletproof Code

.

/ Calling-Scope Data Example char* get_name(char* name) void client() { { cin.getline(name, 100); char data[100]; . . . get_name (data); return name; . . . } // use data }

.

/ Command Line: System Side C:\Users\dab\>name_box Cranston Q. Snort main(int argc, char* argv[])

.

/ Command Line: User Side C:\Users\dab>name_box Cranston Q. Snort Current working directory: C:\Users\dab> Name of a program: name_box

.

/ Converting numbers to strings string s1 = to_string(123); string s2 = to_string(3.14);

.

/ Converting strings to double • double stod(string s); • double atof(char* s); • double strtod(char* s, char** end); • double strtod(char* s, nullptr);

.

/ Converting strings to numbers int i = stoi(s1); double d = stod(s2);

.

/ Dynamic Data Example char* get_name() { char* name = new char[100]; cin.getline(name, 100); . . . return name; }

.

/ Examples of some ways that the assignment and concatenations operators are called string s1("hello"); string s2; string s3; s2 = "world"; s3 = s1 + s2; s3 = s1 + "world"; s3 = s2 + '!';

.

/ Static Data Example char* get_name() { static char name[100]; cin.getline(name, 100); . . . return name; }

.

/ String constructors - no return type, not even void Prototype Example Comments string(); string s1; Default constructor string(const char* s); string s1("Hello"); Conversion constructor string(const string& s); string s2(s1); Copy constructor

.

/ c-strings and scope How to define and read C-strings • As a character array • Read with the getline function When is the memory for automatic variables allocated and deallocated? • Allocated when the variable comes into scope • Deallocated when the variable goes out of scope The relationship between pointers and arrays • The name of an array is address of the array How arrays are passed to and returned from functions • Always passed in and returned by pointer

.

// Function Prototypes: Documentation String Class: int stoi(const string&a str, size_t* = 0, int base = 10); C-string: int atoi(const char* str); long strtol(const char* str, char** endptr, int base);

.

The elements of a 10-element array are indexed from ____ to ____ 1 - 10 0 - 10 1 - 9 0 - 9 0 - 11

0 - 9

What does the following C++ code fragment print? char c = 'D'; cout << (c - 'A') << endl; The code will not compile because you can't subtract a char from an int. 51 33 3

3

What does the following C++ code fragment print? int k = 5; cout << (char)(k + '0') << endl; The code will not compile because you can't add an int and char. 51 33 3

5

Assuming that "employee" is the name of a structure, tell what this statement defines: employee* emplist = new employee[1000]; An array with 1000 elements of a structure named employee An array with 1000 elements that are pointers to structures named employee A pointer to an array with 1000 elements of a structure named employee There is insufficient information to determine what the array contains

A pointer to an array with 1000 elements of a structure named employee

The name of an array, without square brackets, represents the _____ of the array.

Address

Assuming that "employee" is the name of structure, tell what this statement defines: employee emplist[1000]; An array with 1000 elements of a structure named employee An array with 1000 elements that are pointers to structures named employee An pointer to an array with 1000 elements of a structure named employee There is insufficient information to determine what the array contains

An array with 1000 elements of a structure named employee

Assuming that "employee" is the name of a structure, tell what this statement defines: employee* emplist[1000]; An array with 1000 elements of a structure named employee An array with 1000 elements that are pointers to structures named employee An pointer to an array with 1000 elements of a structure named employee There is insufficient information to determine what the array contains

An array with 1000 elements that are pointers to structures named employee

strcmp

C-string Compare Function Comparing two strings for equality is a common and necessary operation int strcmp (char* s1, char* s2) strcmp is an ordering function based on the ASCII code that returns < 0 if s1 comes before s2 0 if s1 and s2 are the same > 0 if s2 comes before s1

In order to have a null C-string, have it equal to 0. T/F

False. To have a null C-string, you must use the null-termination character: '\0' char s[100]; s[0] = '\0';

GUI

Graphical User Interface

The string class function "end()" returns a string iterator that refers to a location in a string that is one character beyond the end of the string. Choose the best explanation for this. This is an error in the original implementation but the behavior has been retained to avoid breaking existing code. This done to reserve space for the null termination character at the end of a string object. If str is a string and itr is a string iterator, the expression itr != str.end() only becomes false after the iterator is advanced beyond the last character in the string. If gives the compiler an opportunity to delete memory allocated to hold the string.

If str is a string and itr is a string iterator, the expression itr != str.end() only becomes false after the iterator is advanced beyond the last character in the string.

When an array is passed to a function, the function: a) accesses exactly the same array (i.e., at the same address) as the caller. or b) accesses a copy of the array passed in by the caller.

a) accesses exactly the same array (i.e., at the same address) as the caller. Arrays are always passed by pointer. This means that there is only one copy of the array.

An array element is accessed using a first-in-first-out approach. a last-in-first-out approach. the dot operator. a member name. an index number.

an index number

size_t

an integer suitable for hold a data size

errno_t

an integer that encodes an error number

argc

argc: command count - stores the number of words or parts of the full command

argv

argv: argument vector - vector is another name for an array - argv is an array of character pointers (/ an array of C-strings)

Given the definition char* s; and assuming that variable s is appropriately initialized, which expression best converts s to a value of type double? to_string(s) stod(s) ftoa(f, s, 10) atof(s) strtod(s, nullptr);

atof(s) strtod(s, nullptr); also works, but isn't as simple

Write a statement that creates a dynamic array called manybirds that holds 50 objects of type bird. bird manybirds[49]; bird manybirds[50]; bird manybirds = new bird[49]; bird manybirds = new bird[50]; bird* manybirds = new bird[50];

bird* manybirds = new bird[50];

Write a statement that defines a C-string variable called city that can hold a string of up to 20 characters (this is tricky question, be careful). char city[19] char city[20] char city[21] char city[22]

char city[21]

The prototype given in the documentation for C-string concatenation is strcat(char* s1, const char* s2); Which of the following is the best definition AND initialization (to an empty string) of the variable s1? char *s1 = ""; char s1[] = ""; char s1[100] = ""; None of the above

char s1[100] = "";

Given the variable definition char name[100]; write a statement that is able to read "Chuck N. Testa" from the console into name.

cin.getline(name, 100);

Write a statement that will store 2 in the shaded area of the array ▯▯▯ ▯▯▯ ▯▯▯ ▯▮▯ ▯▯▯

coefficients[3][1] = 2;

In a stack (implemented as an array), the data item placed on the stack first is not given an index number. given the index number 0. the first data item to be removed. the last data item to be removed.

given the index number 0. and the last data item to be removed. When a stack is implemented as an array, the bottom of the stack is at index 0.

For a two-dimensional automatic array of type int, called arr, write a statement that declares the array and initializes the first row to 52, 27, 83; the second row to 94, 73, 49; and the third row to 3, 6, 1.

int arr[3][3] = {52, 27, 83, 94, 73, 49, 3, 6, 1};

Write a statement that defines a one-dimensional automatic array called bobby of type int that holds 10 elements; define the array as an automatic variable.

int bobby[10];

Write a single statement that defines an int array named coins and initializes the elements to the numeric values (in pennies) of US coins: penny, nickel , dime, quarter, half-dollar, and dollar.

int coins[6] = {1, 5, 10, 25, 50, 100};

A C++ program defines a function as void f(foo* data, int x, int y) { . . . } foo is the name of a fully specified structure and data is a one-dimensional array of foo objects. The variables x and y are valid indexes into data. Write the statements to swap the values stored in data[x] and data[y]. The size of data is not important for this problem.

int temp = data[x]; data[x] = data[y]; data[y] = temp;

Define an automatic array of ints, name is totals, and make it have 6 columns and 2 rows.

int totals[2][6]; int totals[rows][columns]

Given the following definitions int scores[50]; int* my_pointer = ...; // initialized to a valid value What statements are valid?: int* spointer = &scores; int* spointer = scores; scores = my_pointer;

int* spointer = scores;

If itr is a string iterator, write the expression to increment the iterator to the next character in the string (just advance the iterator to the next character, don't get the referenced character).

itr++

Explain what if anything is wrong with the following code (assume all header files are included and that the user enters fewer than 100 characters). Please note that the question is asking what, if anything, is wrong, NOT how to fix the code if needed. char* read() { char line[100]; cin.getline(line, 100); return line; }

line is going to be out of scope when it goes to be read by the function

Choose the correct main function definition to allow a program to access command line arguments. main(char argc, char argv) main(int argc, char* argv[]) main(char* argv[], int argc) main(int argc, char argv[])

main(int argc, char* argv[])

Examine the following code fragment. The character array "name" is defined as a global variable. char name[100]; char* get_name() { . . . return _______________; } From the following, choose the best code to compete the return statement to return the C-string variable "name" or to describe why the return statement cannot be completed correctly. It is not possible to convert an array in to a pointer. *name &name name

name The function return type is a char pointer, but the name of an array (without any additional operators or other syntax) IS a pointer. so the syntax IS correct. Notice that the array is defined as a global variable. That means that the array remains allocated and usable after the function returns and the address (pointer) returned by the function still points to allocated memory.


Set pelajaran terkait

ADN 106 Test 3 - Chapter 35, 36, 37, 71

View Set

NU142- Chapter 61: Management of Patients With Dermatologic Disorders

View Set

MKTG 409 Pride CH12 ATP/Cengage/Mindtap

View Set

Physics Chapter 15: Misconceptual Questions

View Set

Chapter 3: Drugs and the Nervous System

View Set

Chapter 36: Introduction to the Nervous System

View Set