2.1 Study the following descriptions and write only the statements to achieve the required
objectives in both algorithm and C++ syntax.
2.1.1 The array called quantity has 20 elements. Write statements that will help in counting
how many of these elements have a value of less than 50. Also determine the sum of
the values that are more than or equal to 50. Display these 2 answers.
2.1.2 The array called itemPrice has 150 elements. Write the statements to determine and
display the highest price. If there is more than one item with this price, the number of
items must also be displayed.
Solution 2.1.1
using namespace std;
#define ARRAY_SIZE 20
#define MIN_NUM 0
#define MAX_NUM 100
#define NUM_TSH 50
main(void)
{
int Quantity[ARRAY_SIZE],n,NumCount=0,Sum=0;
srand(time(0));
cout<<"\nThe values are: ";
for(n=0;n<ARRAY_SIZE;n++)
{
Quantity[n]=-1;
while(Quantity[n]<MIN_NUM || Quantity[n]>MAX_NUM) Quantity[n] = rand();
cout<<Quantity[n]<<", ";
if(Quantity[n]<NUM_TSH) NumCount++;
else Sum = Sum + Quantity[n];
}
cout<<"\n\nSolution-1: No. of values < "<<NUM_TSH<<" = "<<NumCount;
cout<<"\n\nSolution-2: Sum of values >= "<<NUM_TSH<<" = "<<Sum;
return(0);
}
Output:
Solution 2.1.2
using namespace std;
#define ARRAY_SIZE 150
#define MIN_PRICE 0
#define MAX_PRICE 100
main(void)
{
int ItemPrice[ARRAY_SIZE],n=0,MaxPr,Count=0;
srand(time(0));
cout<<"\nThe price values are: ";
MaxPr = MIN_PRICE;
for(n=0;n<ARRAY_SIZE;n++)
{
ItemPrice[n]=-1;
while(ItemPrice[n]<MIN_PRICE || ItemPrice[n]>MAX_PRICE) ItemPrice[n] = rand();
cout<<ItemPrice[n]<<", ";
if(MaxPr<=ItemPrice[n]) MaxPr=ItemPrice[n];
}
for(n=0;n<ARRAY_SIZE;n++)
{
if(ItemPrice[n]==MaxPr) Count++;
}
cout<<"\n\nThe highest price = "<<MaxPr;
cout<<"\n\nNo. of Items with highest price (="<<MaxPr<<") are: "<<Count;
return(0);
}
Output:
Comments
Leave a comment