Reputation: 43
In a vector, I must insert product and sum between every two consecutive elements.For example the 1 2 3 4 vector will become 1 3 2 2 5 6 3 7 12 4.
This is the code i did till now.
You can see that the function which makes the insertion is insertInVector().
#include <iostream>
void sumProduct(int a, int b, int* suma_functie, int* produs_functie)
{
*suma_functie = a + b;
*produs_functie = a * b;
}
void insertInVector(int &n,int v[])
{
int suma, produs;
for (int i = 1; i <= n; i++)
{
sumProduct(v[i], v[i + 1], &suma, &produs);
v[i + 4] = v[i + 1];
v[i + 1] = suma;
v[i + 5] = v[i + 2];
v[i + 2] =produs ;
}
}
void readVector(int n, int v[])
{
for (int i = 1; i <= n; i++)
std::cin >> v[i];
}
void displayVector(int& n, int v[])
{
for (int i = 1; i <= n; i++)
std::cout << v[i]<<" ";
}
int main()
{
int n,v[100];
std::cin >> n;
readVector(n, v);
insertInVector(n, v);
displayVector(n, v);
}
Upvotes: 0
Views: 357
Reputation: 100
User8411584 is completely correct in pointing out that you need to create a temporary copy of the array first instead of simply beginning to overwrite it.
Just a little addition though:
The term for the new length of the resulting array n+(2*(n-1)) can be simplified to 3n-2.
Upvotes: 0
Reputation: 156
I changed some things in your code. One of the main things is that you can't insert in the middle of an array as it has a static memory (if you want to change only in the given array without using anything extra then you should use vector
instead of array
). So for this purpose, I have used an extra temp
array and reflected those changes in the original array at the end. Also, I used pass by reference
in the function sumProduct
as I am not aware of the way you were using it; you can change it if you want. Also n+(2*(n-1))
is the new length of the array which can easily be predicted from the question. Just check out the changes in insertInVector
function you will understand the rest.
#include <iostream>
void sumProduct(int a, int b, int& suma_functie, int& produs_functie)
{
suma_functie = a + b;
produs_functie = a * b;
}
void insertInVector(int &n,int v[])
{
int suma, produs;
int temp[100];
for (int i = 1, j=1; i <= n-1; i++)
{
temp[j]=v[i];
sumProduct(v[i], v[i + 1], suma, produs);
temp[j+1]=suma;
temp[j+2]=produs;
j+=3;
}
int n2=n;
n=n+(2*(n-1));
temp[n]=v[n2];
for (int i=1; i<= n; i++)
{
v[i]=temp[i];
}
}
void readVector(int n, int v[])
{
for (int i = 1; i <= n; i++)
std::cin >> v[i];
}
void displayVector(int& n, int v[])
{
for (int i = 1; i <= n; i++)
std::cout << v[i]<<" ";
}
int main()
{
int n,v[100];
std::cin >> n;
readVector(n, v);
insertInVector(n, v);
displayVector(n, v);
}
Hope it helps!
Upvotes: 1