I would like to edit numbers in p2 according to the code in for cycle. But If I try to write out actual number in p2, I don´t see anything in output. What could I change to see it?
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i; i >0; i ){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}
CodePudding user response:
As pointed out by Ilya, you need to change the condition in the for loop. Right now, at the beginning of the for loop, i = 0
, so the for loop never starts. Change it to the following:
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i ){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
}
CodePudding user response:
Since you did not initialize the value of i
it takes the random value that is stored in its location.
So just make i
0 and loop it through until 10.
#include <iostream>
using namespace std;
int main()
{
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i = 0; i < 10; i ){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
return 0;
}
CodePudding user response:
Because you didn't initialize the i
variable, it takes a random number of type int, causing the loop to misbehave. You need to make i=0
for it to work correctly.
int p1[10]={-5,-8,0,5,0,-8,-11,-2,1,-7};
int p2[10]={0,0,0,0,0,0,0,0,0,0};
for(int i=0; i < sizeof(p1)/sizeof(p1[0]); i ){
p2[i] = p2[i] - p1[i];
cout << p2[i];
}
sizeof(p1)/sizeof(p1[0])
is count of array elements.