Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge | Intro to Arrays
Introduction to C++

book
Challenge

Let's practice!

Tarea

Swipe to start coding

Lily went to the shop to buy some clothes. It was the sales day so all the clothes she bought were at discount. Let’s calculate the total discount she got.

We have two arrays of the same length (6): prices and sales. The first array stores prices (in dollars) for Lily’s clothes and the second one stores discounts (in percent, 0.1 means that the thing has a 10% discount) for the corresponding clothes.

You should:

  1. Use for loop to go through the arrays, don't forget to open curly brackets.
  2. Calculate the discount for each thing by multiplying the corresponding elements of two arrays and store the result in the variable discountForEach.
  1. To find the sum of all discounts, add variables discountForEach and totalDiscount, and store the result in the variable totalDiscount.
  1. Close curly brackets.
  2. Print the variable totalDiscount.

Please, don’t forget to type the semicolon at the end of the lines.

Solución

#include <iostream>
using namespace std;

int main() {
// Define arrays
double prices[6] = {100, 200, 50, 300, 900, 200};
double sales[6] = { 0.1, 0.2, 0.5, 0.4, 0.9, 0.4};

// Declare variables for calculations
double totalDiscount = 0;
double discountForEach;

// Go thought arrays
for (int i = 0; i <= 5; i++) {
// Calculate the discount for each thing
discountForEach = prices[i] * sales[i];

// Calculate total discount
totalDiscount += discountForEach;
}

// Print the result
cout << totalDiscount;

return 0;
}

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 4
#include <iostream>
using namespace std;

int main() {
// Define arrays
double prices[6] = {100, 200, 50, 300, 900, 200};
double sales[6] = { 0.1, 0.2, 0.5, 0.4, 0.9, 0.4};

// Declare variables for calculations
double totalDiscount = 0;
double discountForEach;

// Go thought arrays
_ _ _
// Calculate the discount for each thing
_ _ _

// Calculate total discount
_ _ _
_ _ _

// Print the result
_ _ _

return 0;
}
toggle bottom row
some-alt