Question

In: Computer Science

Exercise 4: We will use the code in ArrayDemo.cpp to explore arrays and the relationships between...

Exercise 4: We will use the code in ArrayDemo.cpp to explore arrays and the relationships between arrays and pointers. First of all, make sure you understand the purpose and syntax of the forward declarations at the beginning of the file. Then do the following (90 minutes in coding):

  1. Coding (finish in 30min):
    1. Add a function called linearSearch()
    2. This function takes as input an array, its size, and a target integer to find
    3. It should return -1 if the item is not found, or its (non-negative) index if found
    4. Test it on one of the provided arrays
  2. Coding (finish in 10min): Rewrite swap() so that it takes two pointers only and swaps the values at those two memory locations.
  3. Coding (finish in 30min): Rewrite bubble() so that it uses a pointer and pointer arithmetic, rather than an array with array indexing. Which version of the code do you think is better? Why?
  4. Coding (finish in 20min):
    1. Change all int array parameter declarations in the function definitions using int[] to declarations using int* pointers.
    2. Remember to change the function prototypes, too.
    3. In main(), declare arrays set and set2 dynamically using "new".
    4. Also in main(), you now need to delete this memory manually (it's an array, so use delete []).
    5. Set all pointer variables in main() to null after deleting storage (why?).

------------------------------------------------------------------------------------------------------------------------------------

ArrayDemo.cpp (below)

#include <iostream>

using namespace std;

// Forward declarations.

void display(int data[], int size);

void bubble(int data[], int size);

void swap(int data[], int idx1, int idx2);

int main(int argc, const char * argv[])

{

const int SIZE = 7;

// These are auto variables.

int set[] = {1,4,3,2,5,9,8}; // Size implicit

int set2[] = {30, 23, 25, 19, 100, 12, 7};

// How does it look like in JAVA?

// int[] myArray = new int[3];

// int[] myArray = {1, 2, 3};

// int[] myArray = new int[] {1, 2, 3};

// You have to pass the size in; a C++ array is just a dumb block of

// storage; no size information is carried with it and no bounds

// checking is done.

display(set, SIZE);

bubble(set, SIZE);

display(set, SIZE);

return 0;

}

void display(int data[], int size) {

for(int i = 0; i < size; i++) {

cout << data[i] << ",";

}

cout << std::endl;

}

void bubble(int data[], int size) {

for(int i = 0; i < size; i++) {

for(int k = 0; k < size - 1 - i; k++) {

if(data[k] < data[k+1]) {

swap(data, k, k+1);

}

}

}

}

void swap(int data[], int idx1, int idx2) {

int temp = data[idx1];

data[idx1] = data[idx2];

data[idx2] = temp;

}

Solutions

Expert Solution

//Forward Declaration in the above program are function prototypes. These are used to define return type and data type of parameters passed to the function.

For part 3 of the question :- Memory access through pointers is said to be more efficient than memory access through an array ie the second method because it reduces the storage space and complexity of the program.

Setting all pointer variables in main() to null after deleting storage is a precautionary step so that our pointer does not points to any garbage value .This makes the program much safer and cleaner.

CODE SNIPPET: ( Check the //comments for better understanding of each question)

#include <iostream>

using namespace std;

// Forward declarations.

void display(int data[], int size);

void bubble(int* pointer, int size);

void swap( int *idx1, int *idx2);

int LinerSearch(int data[], int size,int target);

int main(int argc, const char * argv[])

{

const int SIZE = 7;

int *set = new int[SIZE] {1,4,3,2,5,9,8}; //part 4 of question: declaring arrays set and set2 dynamically using "new"

int *set2 = new int[SIZE] {30, 23, 25, 19, 100, 12, 7};

display(set, SIZE);

bubble(set, SIZE);

display(set, SIZE);

int SearchIndex=LinerSearch(set2,SIZE,25); //part 1 of qs : testing LinerSearch
cout<<SearchIndex;

delete[] set;
delete[] set2;
set=NULL;
set2=NULL;
return 0;

}

void display(int *data, int size) {

for(int i = 0; i < size; i++) {

cout << *(data+i) << ",";

}

cout << std::endl;

}

void bubble(int* pointer, int size) // Part 3 of question: bubble() so that it uses a pointer and pointer arithmetic
{

for(int i = 0; i < size; i++) {

for(int k = 0; k < size - 1 - i; k++) {

if(*(pointer+k) < *(pointer+k+1)) {

swap(pointer+k,pointer+k+1);

}

}

}

}


void swap( int *idx1, int *idx2) { //part2 of qs: swap() so that it takes two pointers

int temp = *idx1;

*idx1 = *idx2;

*idx2 = temp;


}


int LinerSearch(int *data, int size,int target) //part1 of the question :ADDING LinerSearch()
{
for(int i=0;i<size;i++)
{
if(*(data+i)==target)
return(i);
}
return(-1);
}

SCREENSHOT OF MY IDE

SCREEN SHOT OF OUTPUT

*2 on the last line of output is the index printed after calling LinearSearch().


Related Solutions

In this exercise, we will use our knowledge of the relationships between revenue, variable costs, fixed...
In this exercise, we will use our knowledge of the relationships between revenue, variable costs, fixed costs, contribution margin, operating margin, and unit charge or sales price. We will calculate the number of UOS we need to perform to break even, what the revenue needed to achieve a target operating income, and compute the contribution income statement to prove our results. Please use the Contribution Margin Method to arrive at your answers and show all your calculations for the answer...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 4: Calorie Counting Specifications: Write a program that allows the user to enter the number of calories consumed per day. Store these calories in an integer vector. The user should be prompted to enter the calories over the course of one week (7 days). Your program should display the total calories consumed over...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 1: Largest and Smallest Vector Values Specifications: Write a program that generates 10 random integers between 50 and 100 (inclusive) and puts them into a vector. The program should display the largest and smallest values stored in the vector. Create 3 functions in addition to your main function. One function should generate the...
In this exercise, we will look at descriptive statistics and how to explore and summarize data...
In this exercise, we will look at descriptive statistics and how to explore and summarize data sets. For this, we use the Heart Disease dataset from the UCI data repository. This dataset consists of 4 small datasets of people with heart disease admitted to 4 hospitals. For now, we only work with the file. this data consists of 271 instances with 7 attributes. The attributes are described as below: Age: age in years sex: 1 = male; 0 = female...
Create a research problem that would use a statistic that would explore differences(not relationships) related to...
Create a research problem that would use a statistic that would explore differences(not relationships) related to something of interfere to you then identify the following: (a) population (b) sample (c) research hypothesis, (d) null hypothesis (e) the variables (f) the inferential statistics that you might use and why.
We are to make a program about a car dealership using arrays. I got the code...
We are to make a program about a car dealership using arrays. I got the code to display all cars in a list, so I'm good with that. What I'm stuck at is how to make it so when a user inputs x for search, it allows them to search the vehicle. We need two classes, one that shows the car information and another that shows the insert, search, delete, display methods. Here is what I have so far package...
4. Review the pressure relationships of the thoracic cavity, and understand the definitions and relationships between...
4. Review the pressure relationships of the thoracic cavity, and understand the definitions and relationships between all of the associated terms (atmospheric pressure, respiratory pressure, intrapulmonary pressure, intrapleural pressure, transpulmonary pressure).
Do not use arrays and code a program that reads a sequence of positive integers from...
Do not use arrays and code a program that reads a sequence of positive integers from the keyboard and finds the largest and the smallest of them along with their number of occurrences. The user enters zero to terminate the input. If the user enters a negative number, the program displays an error and continues. Sample 1: Enter numbers: 3 2 6 2 2 6 6 6 5 6 0 Largest Occurrences Smallest Occurrences 6 5 2 3. Do not...
Researchers have found general relationships between testicular cancer and exercise. increased exercise is associated with a...
Researchers have found general relationships between testicular cancer and exercise. increased exercise is associated with a decrease in incidence of testicular cancer. However, a positive relationship( increased incidence of testicular cancer) was found between testicular cancer and riding bikes or horses. several factors might be hypothesized to bring about this result. which of these hypotheses is properly related to a prediction that arises from it?
This exercise stresses the relationships between the information recorded in a periodic inventory system and the...
This exercise stresses the relationships between the information recorded in a periodic inventory system and the basic elements of an income statement. Each of the five lines represents a separate set of information. You are to fill in the missing amounts. (Enter loss amounts as a negative number.) Not necessarily looking for the answer but trying to find out the calculations of net sales, ending inventory, exepenses, and net income or (loss). Thanks!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT