### Trying to make a perimeter calculator!

Hello! I am working on a calculator. In this calculator I want to have a perimeter calculator. Everything was going good, until I wanted to get the perimeter!!! I don't know what to do to get the perimeter. I had the number of sides that the user entered stored in a variable. That variable then was stored as the length for an array. So if the user entered 5 then the size of the array would be 5. Here is the little cut-out of the perimeter calculator so far:

 ``1234567891011121314`` `````` cout << "You chose the perimiter calculator!" << endl; cout << "Please enter the amount of sides on your shape: " << endl; cin >> numberOfSides; long double sides[numberOfSides]; for(int x = 0; x <= numberOfSides; x++) { cout << "Enter the length of one of your walls your shape: " << endl; cin >> sides[x]; } ``````

I just do not know how to add the sides. It is probably really obvious and I am just missing it! Any help would be appreciated! If you need any explaining as to what some of the code is doing I will gladly explain!
Last edited on
First off you need to change your for loop condition to just <, not <=. Arrays start at index 0, so if you let the counter get up to the size of the array and try to access that index you will get an out of bounds error.

 ``123456`` ``````double sum = 0; for(int i = 0; i < numberOfSides; i++) { sum += sides[i]; } cout << "Perimeter is: " << sum << endl;``````
Last edited on
Ok but how do I add the sides together? How do I access a certain element in the array? Is it possible?
The code I posted will add the sides together and store the result in sum.
 ``123456789101112`` ``````// This double will hold the sum of all the sides double sum = 0; // Will loop through each index in the array for(int i = 0; i < numberOfSides; i++) { // Access index i of the sides array and add it to the sum sum += sides[i]; } // After all of the sides have been added sum will be the perimeter of the object cout << "Perimeter is: " << sum << endl;``````

To access a certain element in the array you just simply plug in the index which you wish to get.

 ``12345`` ``````sides[0]; // This will access the very first index in the array sides[1]; // This will access the second double first_side = sides[0]; double second_side = sides[1];``````
Last edited on
Oh. Thanks for the help! =)

EDIT: For an area calculator would I do the same but do this instead:

`sum *= sides[x];`
Last edited on
Topic archived. No new replies allowed.