I need assistance in writing this code. I\'m still confused on using structs. So
ID: 3789853 • Letter: I
Question
I need assistance in writing this code. I'm still confused on using structs. So, if you are able to clarify how you are using the struct that would be great.
Edit: The code needs to return the most common repeating element found in an array, using the info in the struct, "string pname; and int price; " . The array and its size has already been created, hence the " int arr[] and int length" inside the string. I hope this makes sense, I apologize in advance if this is confusing, I am new to coding so I don't know much terminology.
Write a C++ function that returns the most common repeating element in an array of structs. The function takes two arguments the input array of structs and the size of the array, and returns the most common product name. struct Product string pname; int price Use the following function header string (Product arro,int length) Answer: 1 struct Products 3 string p int price 5 7 string Common Repeating Element Product arr 0, int length) 8 9 int Common WordCount 10 11 13 14 15 16 17 CheckExplanation / Answer
#include<iostream>
#include<string>
using namespace std;
int length;
struct Product
{
string pname;
int price;
};
string CommonRepeatingElement(Product arr[],int length); //function declaration
int main()
{
cout<<"enter length:";
cin>>length; //array of structures length
Product arr[length];
cout<<"enter products details"<<endl;
for(int i=0;i<length;i++)
cin>>arr[i].pname>>arr[i].price; //inputs product details
string sm=CommonRepeatingElement(arr,length); //function calling
cout<<sm;
return 0;
}
string CommonRepeatingElement(Product arr[],int length)
{
int max=0,count=0,j,k;
for(int i=0;i<length;i++)
{
count=0; //count variable to calculate common repeating element
for(j=0;j<length && j!=i;j++)
{
if(arr[i].pname.compare(arr[j].pname)==0) //string comparisongs
count++;
}
if(count>max)
{
k=i;
}
}
return arr[k].pname; //returning max occurence string
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.