Programming Assignment #2 The dot product of two vectors A and B, each of size n
ID: 3726506 • Letter: P
Question
Programming Assignment #2
The dot product of two vectors A and B, each of size n, is
int product=0; for (int i=0; i<=n; i++) product+=A[i]*B[i] (Calculation 1)
In this assignment, you write C++ programs that compute the dot product of two given vectors. In these programs, in vectors A and B only nonzero elements are stored.
you must implement a linked list version of the program. That is, instead of an array, you use linked lists to store the non-zero elements of the vectors. This involves changing struct definition to include a link, and writing a new dotproduct() function.
Good Luck
Explanation / Answer
using namespace std;
struct node{
int data;
node *next;
};
class vectorlist
{
private:
node *head;
public:
vectorlist()
{
head=NULL;
}
void add_item(int value) // adding in the beginning of the linked list
{
node *temp=new node;
temp->data=value;
temp->next=head;
head=temp;
}
void display()
{
node *temp=new node;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout << " ";
}
int dotproduct(vectorlist &p, int n)
{
int prod = 0;
node t1 = (this).head;
node *t2 = p.head;
for(int i = 0; i < n; i++)
{
prod += ((t1->data) * (t2->data));
t1 = t1->next;
t2 = t2->next;
}
return prod;
}
}A,B;
int main(){
int n;
cout << "Enter number of elements ";
cin >> n;
int x;
cout << "Enter elements in A ";
for(int i = 0; i < n; i++)
{
cin >> x;
A.add_item(x);
}
A.display();
cout << "Enter elements in B ";
for(int i = 0; i < n; i++)
{
cin >> x;
B.add_item(x);
}
B.display();
cout << "Dot product is: " << A.dotproduct(B,n);
return 0;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.