how would i write nested for loops for this program?

there are 3 products. product 1 is $12.50, product 2 is $8.90 and product 3 is $20.10. write a C++ program that reads the product number and the quantity sold per day, and then calculates and display the total retail value for this product sold at the end of the week. the program shud also calculate and display the total retail value of all products sold at the end of the week. use a switch statement and nested for loops.

this is wat i got so far.

#include <iostream>
using namespace std;
int main( )
{
const int NrOfProducts = 3;
const int NrOfDays = 7;
int proNr, quantity;
float price, totAll = 0.0, totWeek = 0.0;
for (int i = 0; i < 3; i++)
{ 
cout << "Enter the product number: ";
cin >> proNr;
 while (proNr > 3)
 {
 cout <<"Invalid product number. Enter a product number: ";
 cin >> proNr;
 }

for (int j=1; j<8; j++)
{
cout << "Enter the quantity sold for ";
if (j == 1)
cout << "Monday: ";
else if (j == 2)
cout << "Tuesday:";
else if (j == 3)
cout << "Wednesday:";
else if (j == 4)
cout << "Thursday:";
else if (j == 5)
cout << "Friday:";
else if (j == 6)
cout << "Saturday:";
else 
cout << "Sunday:";
cin >> quantity;
}
switch (proNr)
{
case 1:
price = 12.50;
break;
case 2:
price = 8.90;
break;
case 3:
price = 20.10;
}

for (int k=0; k<8; k++)
{
totWeek = 0.0;
quantity++;
price *= quantity;
totWeek += price;
}
cout << "The total retail value of this product sold for this week is R"
<< totWeek << endl;
for (int l=0; l<8; l++)
{
totWeek = 0.0;
quantity++;
price *= quantity;
totWeek += price;
}


}
cout << endl;


return 0;
}

Recommended Answers

All 4 Replies

You can write nested loops like this. Just put a loop inside of a loop:

for(int x=0 ; x<=10; x++){      
    //outer loop runs last
    for(int y=1; y<=10; y++){ 
        //this loop runs second
        for(int z=0; z<=10;z++){
            //inner loop runs 1st 
        }//end for z 
    }//end for y
}//end for x

if you make two for loops nested like above, for each value of x, it will iterate to all values of y and go to next iteration which will do the same until all values of x are finished

if you make two for loops nested like above, for each value of x, it will iterate to all values of y and go to next iteration which will do the same until all values of x are finished

In other words, it will loop over all values of y for all values of x, so the inner loop y runs x times.

In other words, it will loop over all values of y for all values of x, so the inner loop y runs x times.

+1 for clarification

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.