Explain the concept of arrays

Assignment Help C/C++ Programming
Reference no: EM13936748

Intro to Arrays

An array is a powerful data structure in C++ that lets us keep track of lists of different types of information. They are quite flexible in that we can put almost anything we want into an array and then access it at a later time. Arrays have two main requirements when we define them: first of all we must give them a type...int, float, string, char, etc. Second of all we need to specify the length of the array. Here are a few examples:

int scores[10]; // this creates an array that can hold 10 integers
char word[5]; // this creates an array that can hold a 5 characters (5 letter word)
float list[60]; // this creates an array that can hold 60 floats.

int evens[4] = {2,4,6,8}; // Here we've defined our array size to be 4 and initialized our array to hold these 4 elements.

char letters[3] = {'a','b','c'}; // We can initialize a char array the same way;

If we want to change the value of an item in an array, we can do this:

evens[0] = 10; // This would change the first item in the array above from a 2 to a 10.
letters[2] = 'd' // This would change the 'c' in the above example to a 'd'

We call the number inside the brackets the index of the array.

Some Important Considerations:

1. The first item in the array is always stored at index 0. This is very, very, very important. So the 2nd item in the array is actually at index 1, the 3rd at index 2,etc.

2. You cannot directly copy an array, even if they are the same size for example you cannot write: Evens[] = otherEvens[]

To accomplish this you actually need to use a for loop to carefully copy each element over one by one. Here's an example of how we can set all of the elements of an array equal to 0 using a for loop:

int numbers[10]; // Create an array of size 10

for( int i = 0; i<10; i++)
n[i] = 0; // We'll put a 0 in at each place of the array as we count up

This is the fundamental process we are going to be working with when we work with arrays....we will have some sort of for loop that we will use to access or fill up the array.This loop prints out everything in an array:

for( int i = 0; i<10; i++)
cout << "Element " << I << " Has Value: " << n[i];

This is the standard input loop for arrays:

for( int i = 0; i<10; i++)
{
cout << "Please Enter a Number: ";
cin >> n[i];
}

We can do all of the same arithmetic we can do with normal numbers using arrays (provided the information stored in the array is actually a float or int). Remember that we start indexing from 0! For instance, if we had the two following arrays:

int odd[5] = {1,3,5,7,9};
int even[5] = {2,4,6,8,10};

Then:
sum = odd[1] + even[3]; // This is 3 + 8 = 11
product = odd[2] * even[0]; // This is 5 * 2 = 10
odd[4] = odd[0]; // This would turn the 9 into a 1 in the above list {1,3,5,7,1}
number = even[1+2]; // This would assign the value 8 to number (i.e. even[3])

We will be doing a lot with arrays moving forward....here are a few problems to help you get comfortable!

1. Averages Revisited - Ask the user how many numbers they would like to average (between 0 and 100), store their input into an array and use it to calculate the average.

2. Roll the Dice - We often want to keep track of the frequencies of something occurring. If we set up our array properly, we can use it to keep track of quite a few things we might use counters for in the past (think of it as an array of counters almost). For this problem, write a program that asks the user how many times they would like to roll a 6-sided die and then keep track of how many of each roll occurred. Print the results to the screen.

3. Histogram - Modify #1 so that after the user has entered in their numbers, the program prints out a histogram (bar graph) of how many values fell between a certain range (i.e. 0 - 9, 10 - 19, etc.). Here is an example of what it should look
like (Hint: you can be clever with % here and avoid a bunch of if statements):

4. Pot Shots at Pi - Let's calculate pi! We're not going to do it by measuring circumferences, though; we're going to do it with Monte Carlo methods - using random numbers to run a simulation. Let's take a circle of radius 1 around the origin, circumscribed by a square with side length 2, like so:

Imagine that this square is a dartboard, and that you are tossing many, many darts at it at random locations on the board. With enough darts, the ratio of darts in the circle to total darts thrown should be the ratio between the area of the circle and the area of the square. Since you know the area of the square, you can use this ratio to calculate the area of the

circle, from which you can calculate pi using:

π=a/r^2

We can make the math a little easier. All we really need to calculate is the area of one quadrant and multiply by 4 to get the full area. This allows us to restrict the domain of our x and y coordinates to [0,1] (instead of having to deal with negative numbers).

In the past we have always come up with random integers. We can also convert the random integers to decimal values in the range [0, 1] simply by dividing by the value RAND_MAX:

double randomDecimal = rand() / static_cast<double>(RAND_MAX);

The static_cast keyword creates a temporary copy of the variable in parentheses, where the copy is of the type indicated in angle brackets. This ensures that our division is done as floating-point, and not integer division. This is called casting RAND_MAX to a double. Note that a double is basically a float that lets us hold more decimals...this is honestly better to use than floats most of the time.

To make this work you will have to follow a few steps:

1. Write two variable declarations representing the x-coordinate and y-coordinate of a particular dart throw. Each one should be named appropriately, and should be initialized to a random double in the range [0,1].

2. Place your variable declarations within a loop that increments a variable named totalDartsInCircle if the dart's location is within the circle's radius. You'll need to use the Euclidean distance formula ( d^ 2 =x^2 +y^2 ).

3. Now use your loop to build a program that asks the user to specify the number of "dart throws" to run, and returns the decimal value of pi, using the technique outlined above. You should get pretty good results for around 5,000,000 dart
throws.

4. Making a List...Checking it Twice - Write a program that generates 20 random integers between 1 and 20 and:

a. Prints it to the screen

b. Prints the same list to the screen, but skips any number that has already been printed to the screen (i.e. no number should appear more than once).

c. Bonus(x2) - Have the list print out in ascending order.

Reference no: EM13936748

Questions Cloud

What is the frequency of heterozygotes for the allele : If heterozygotes for the beta-thalassemia allele are protected against malaria, what is the selection coefficient s1 aganist homozygotes for the normal allele? Again, what assumption must you make in your calculation?
Define the first step of research in your own words : Read the article titled, "As drug industry's influence over research grows, so does the potential for bias," Write a one to two (1-2) page essay in which you: Identify the first step in the student's guide to research. Define the first step of resear..
S la quintas strategy one of product cost leadership : Is La Quinta's 2008 strategy one of product differentiation or cost leadership? Explain briefly. Indicate two measures you would expect to see under each perspective in La Quinta's balanced scorecard for 2008.
Purpose of the global marketing research : Describe the purpose of the global marketing research described in the article?
Explain the concept of arrays : n array is a powerful data structure in C++ that lets us keep track of lists of different types of information. They are quite flexible in that we can put almost anything we want into an array and then access it at a later time. Arrays have two ma..
What is the mutation rate for this gene : Write a DNA sequence of 10 bases, and show how a missense mutation results in a mutant sequence. Show the sequence of the transcript and hypothetical amino acid sequence.
Leading the internal investigation of the accident : You are the chief systems engineer for Sir Richard Branson of Virgin Galactic Corporation, Ltd. As you are aware, last Friday, October 31st, there was a tragic and serious failure of SpaceShipTwo, during a powered test flight from the Mojave Spa..
Is merediths strategy one of product cost leadership : Is Meredith's strategy one of product differentiation or cost leadership? Explain briefly. Describe briefly key elements that you would include in Meredith's balanced scorecard and the reasons for doing so.
Figure out what amino acids joined to make protein : figure out what amino acids will be joined to make the protein coded for by this segment of dna if the bottom strand is used to make the mRNA.

Reviews

Write a Review

C/C++ Programming Questions & Answers

  Create a template class

Create a template class, SVector, that implements a constructor

  Client function that merges two instances of the sorted list

Write a client function that merges two instances of the Sorted List ADT using the following specification.

  Write a recursive function to draw the pattern

write a program that prompts the user to enter the number of lines in the pattern and uses the recursive function to generate the pattern. For example, specifying 4 as the number of lines generates the above pattern.

  Convert celsius temperatures to fahrenheit temperatures

Write a C++ program that converts Celsius Temperatures to Fahrenheit Temperatures.

  Write Relational Algebra queries

Attributes cid and fid in Reservation are foreign keys referencing homonymous attributes in Customer and Flight, respectively. Write Relational Algebra queries

  Implement solver for stiff system of differential equations

Implement a solver for the stiff system of differential equations - Array of doubles of length n containing the initial value.

  Write a c++ function that removes and counts all occurrences

Write a C++ function that removes and counts all occurrences of a given string from such a bag. Your function should return this number.

  A minivan has two sliding doors

A minivan has two sliding doors.  Each door can be opened by either a dashboard switch, its inside handle, or its outside handle. However, the inside handles do not work if a child lock switch is activated.  In order for the sliding doors to open, th..

  Code should include a loop that displays income

This code should include a loop that displays income generated from ticket sales for each night. Shows are performed on Thursday, Friday and Saturday nights.

  Take an n x n matrix, and create a new, (n-1) x (n- 1)

take an N x N matrix, and create a new, (N-1) x (N- 1), matrix with each element being the sum of four nearby elements. You need to figure out a way to break the matrix up into squares and iterate through the matrix, while staying within its bounds.

  Write a program to evaluate infix expressions

Write a program to evaluate infix expressions and summarize differences between array notation and pointer notation

  Program that will output the solution to the quadratic eq

Create a C++ program that will output the solution to the quadratic equation for any range of integer coefficients

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd