Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask C/C++ Expert


Home >> C/C++

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(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.

C/C++, Programming

  • Category:- C/C++
  • Reference No.:- M91607631
  • Price:- $20

Priced at Now at $20, Verified Solution

Have any Question?


Related Questions in C/C++

Question 1find the minimum and maximum of a list of numbers

Question: 1. Find the Minimum and Maximum of a List of Numbers: 10 points File: find_min_max.cpp Write a program that reads some number of integers from the user and finds the minimum and maximum numbers in this list. Th ...

Project - space race part a console Project - Space Race Part A: Console Implementation

Project - Space Race Part A: Console Implementation INTRODUCTION This assignment aims to give you a real problem-solving experience, similar to what you might encounter in the workplace. You have been hired to complete a ...

What are the legal requirements with which websites must

What are the legal requirements with which websites must comply in order to meet the needs of persons with disabilities? Why is maximizing accessibility important to everyone?

Assign ment - genetic algorithmin this assignment you will

ASSIGN MENT - GENETIC ALGORITHM In this assignment, you will use your C programming skills to build a simple Genetic Algorithm. DESCRIPTION OF THE PROGRAM - CORE REQUIREMENTS - REQ1: Command-line arguments The user of yo ...

1 implement the binary search tree bst in c using the node

1. Implement the Binary Search Tree (BST) in C++, using the Node class template provided below. Please read the provided helper methods in class BST, especially for deleteValue(), make sure you get a fully understanding ...

There are several ways to calculate the pulse width of a

There are several ways to calculate the pulse width of a digital input signal. One method is to directly read the input pin and another method (more efficient) is to use a timer and pin change interrupt. Function startTi ...

Why do researcher drop the ewaste and where does it end

Why do researcher drop the ewaste and where does it end up?

Software development fundamentals assignment 1 -details amp

Software Development Fundamentals Assignment 1 - Details & Problems - In this assignment, you are required to answer the short questions, identify error in the code, give output of the code and develop three C# Console P ...

Assignment word matchingwhats a six-letter word that has an

Assignment: Word Matching What's a six-letter word that has an e as its first, third, and fifth letter? Can you find an anagram of pine grave. Or how about a word that starts and ends with ant (other than ant itself, of ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As