Question :
I have a problem with the following statement:
Given a vector A with n real numbers, get another vector B, also with n real numbers, as follows:
B [1] = 2 * A [1]
B [2] = 3 * A [1] + 2 * A [2]
B [3] = 4 * A [1] + 3 * A [2] + 2 * A [3]
(… and so on)
I made the program, but my logic is wrong and I can not identify the error. Can someone help me? Here is the code I wrote.
#include <iostream>
using namespace std;
int main(){
int tamanho;
cout << "Qual o tamanho do vetor? ";
cin >> tamanho;
float vetorA[tamanho], vetorB[tamanho];
for (int i = 0; i < tamanho; i++){
cout<< "Digite o numero :";
cin >> vetorA[i];
}
for(int i = 0; i < tamanho; i++){
for(int j = 2; j <= tamanho + 1; j++){
vetorB[i] += j * vetorA[i];
}
}
int i = 0;
while(i < tamanho){
cout << "nA["<< i << "] = " << vetorA[i] << "t B[" << i << "] = " << vetorB[i];
i++;
}
}
Answer :
Perhaps, having thought of a “formula” would help you to get the correct result more quickly.
(n + 1) * A [1] + n * A [2] + (n-1) * A [3] + … + 3 * A [n-1] 2 * A [n]
The error was really only in logic. By analyzing the statement carefully we can see some patterns.
Graphic explanation http://i62.tinypic.com/2ikf94.jpg
It is noticeable that you have recognized the pattern by looking at your code.
for(int i = 1; i <= tamanho; i++){
aux = i + 1;
for(int j = aux, k = 1; k <= i; j--, k++){
vetorB[i-1] += j * vetorA[k-1];
}
}
The for outermost, has as stop condition, the size of the vector. By storing the value of i in an auxiliary variable plus one unit, it covers one of the conditions so that the right result is obtained.
In the second for , ensure that the rule will be executed for each expression term until the j and are equal.
Another important way to test your code (as a beginner) to find what is wrong is to crawl.
Good Studies!
Error resolved. I leave the code to help anyone with the same problem.
#include <iostream>
using namespace std;
int main(){
int tamanho, aux = 0;
cout << "Qual o tamanho do vetor? ";
cin >> tamanho;
float vetorA[tamanho], vetorB[tamanho];
for (int i = 0; i < tamanho; i++){
cout<< "Digite o numero :";
cin >> vetorA[i];
}
for(int i = 1; i <= tamanho; i++){
aux = i + 1;
for(int j = aux, k = 1; k <= i; j--, k++){
vetorB[i-1] += j * vetorA[k-1];
}
}
int c = 0;
while(c < tamanho){
cout << "nA["<< c << "] = " << vetorA[c] << "t B[" << c << "] = " << vetorB[c];
c++;
}
}