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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
cout << "You chose the perimiter calculator!" << endl;
cout << "Please enter the amount of sides on your shape: " << endl;
cin >> numberOfSides;
longdouble 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!
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.
1 2 3 4 5 6
double sum = 0;
for(int i = 0; i < numberOfSides; i++)
{
sum += sides[i];
}
cout << "Perimeter is: " << sum << endl;
The code I posted will add the sides together and store the result in sum.
1 2 3 4 5 6 7 8 9 10 11 12
// 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.
1 2 3 4 5
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];