Hey guys, I just started a week ago using C++. And I need your help to do my homework, so please be gentle with me.
Anyway, I looked for answers in this forum but it seems like other people use different logic to solve their problems. There is the vector A which consist different members with different values. And I need to form another vector B, which consists only the negative numbers that are at A . I looked at the book that I'm learning at school about C++. And could only find how to take the negative numbers from a matrix and form a vector from them. Kind of followed that logic and came up with this similar code. but the problem is that the vector B should have -1 and -4 as it's members, but instead when I run the code, it gives me the -4 and -4. Test it for yourself and please help me. If you can modify this code where it gives me the -1 and -4, I'd be happy.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
intconst m = 4;
int A[m] = { 4, -1, -4, 2 };
int k, i, B[m];
char v[] = "---------------------";
k = -1;
i = 0;
while (i < m)
{
if (A[i] < 0)
{
k = k + 1;
B[k] = A[i];
}
i++;
}
cout << "\nFormed vector B\n"
<< "\n Index Member \n"
<< v
<< endl;
for (i = 0; i <= k; i++)
cout << setw(5)
<< i
<< setw(10)
<< B[k]
<< endl;
cout << v
<< endl;
return 0;
}
alright guys, thanks thomas and borges, both of your methods worked, and they made me see where my mistake was, I should've written at the end B[i] instead of B[k]
because when it was B[k] it only showed the last negative number. B[i] is the whole vector, B[k] it's just a member I guess (in this case)
well thanks :D