Help please :)

Hello , I'm kind of noobish , and I won't lie , this is a homework . But I can't seem to figure this out . So the code must remove from a vector all the elements divisible with 5 . Example : Count of items = 3 ; Item 1 = 5 ; item 2 = 6 ; item 3 = 7; Cout 6 7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
int v[100],n,i,;
cout<<"Count of elements =";cin>>n;
for(i=1;i<=n;++i){
    cout<<"Element "<<i<<" =";cin>>v[i];
    if (v[i] % 5 == 0){
    v[i]=v[i+1];}  
    else 
  cout<<v[i]<<" ";}
return 0;
}



this is what I've got so far . Thank you in advance !
Last edited on
Hello ialexsandu,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

You have not included the header file <vector> nor have you defined a vector to use. What you have done is define a C style array of "int"s.

While discussing that area:

It is ALWAYS a good practice and programming to initialize your variables. If your compiler is using the C++11 standards or after the easiest way to initialize variables is with empty {}s, e.g., int num{};. This will initialize the variable to 0 (zero) or 0.0 for a double. A "char" will be initialized to "\0". "std::string"s are empty to start with and do not need to be initialized. Should you need to you can put a number between the {}s.You can also Initialize an array, e.g., int aNumbers[10]{};. This will initialize all elements of the array to 0 (zero). A use of
int aNumbers[10]{ 1 }; will initial the first element to "1" and the rest of the array to "0".. Following the "1" with ", 2 ..." will initialize the array with the numbers that you have used up to the entire array.

Unless you have a use for "i" outside the for loop it is better to define "i" inside the for loop as: for(int i = 0;i < n; ++i). And try to avoid using "<=" unless you are absolutely sure of what you are doing. Other wise you are likely to go past the end of the array or vector if you use them.

The array or vector along with others start at zero not one as C, C++ and other languages are zero based.

If you used a vector there is a function "vectorName.erase()" that will remove an element and adjust the vector's size for you. Using the C style array you will wither have to set an element to zero to deal with later or write all good elements to a new array. Otherwise you will have to keep track and change things dealing with the length of the array as you shorten things when you move things to the left.

Decide on which you would like to use the array or the vector? Or maybe you are calling the array by the wrong name.

Hope that helps,

Andy
Thanks , but i don't really understand much of what you said . The problem with my code is that after every element that is not divisible to 5 this happens
1
2
3
4
5
Count of elements =3
Element 1 =5
Element 2 =6
6 Element 3 =7
7  

and is supposed to show this
1
2
3
4
5
6

Count of elements =3
Element 1 =5
Element 2 =6
Element 3 =7
6 7 

And tomorow i have to give it , so if you don't mind at least telling me what did i do wrong i'd be really happy , thanks for the rest of what you said tho , it might be helpful sometime in the near future :).
an array of 3 elements is v[0], v[1], and v[2].
your loop starts at 1, which is weird. it works for 3 because you have 100, but its weird. you have reindexed from C++ style to some other language like basic that starts at 1. This is not your problem, but its a bit off.

your assignment looks wrong to me:

let me put your code in english and see if you can fix it:

for i = 1 to n
read in v[i] //v[i+1 is not defined/filled in yet]
if something
v[i] = v[i+1] (which again, isnt filled in yet)

does this explain some of your problem?
does that mean the program should start after i insert every array . Like after writing every v[0] v[1] .. v[n] then the for should start?
First, you need to come up with a removal plan. It's unclear what exactly you need to do, because you described a vector but then wrote code for a basic array.

If you had a basic array whose size cannot change, your "removal" might actually be about shifting elements towards the removal spot and zeroing out the back. This would make sense if you had a rule that the "usable" range in the array had to be non-zero. In this case it might make sense to have a second, already-zero'd out array with same size as original and just copy over elements that do not divide 5.

But you're in luck because there are built-in algorithms and ideas to help. Specifically, first calling a std::remove_if , followed by a std::erase , as per the whitespace removal example in http://en.cppreference.com/w/cpp/algorithm/remove .

This makes use of (link in that first page too) https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom,
The algorithm library provides the remove and remove_if algorithms for this. Because these algorithms operate on a range of elements denoted by two forward iterators, they have no knowledge of the underlying container or collection.[1][4]

These algorithms do not remove elements from the container, but move all elements that don't fit the remove criteria to the front of the range, keeping the relative order of the elements. This is done in a single pass through the data range.

...

As no elements are actually removed and the container has still the same size, there is a number of elements equal to the number of "removed" items left in the back of the range, having a valid but unspecified state. remove returns an iterator pointing to the first of these elements, so they can be deleted using a single call to erase.

Hello ialexsandu,

If there is something I said just ask.

If you code would look like this it is easier to read:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>


using namespace std;

int main()
{
	int v[100], n, i, ;

	cout << "Count of elements =";
        cin >> n;

	for (i = 1; i <= n; ++i)
	{
		cout << "Element " << i << " =";
                cin >> v[i];

		if (v[i] % 5 == 0)
		{
			v[i] = v[i + 1];
		}
		else
			cout << v[i] << " ";
	}

	return 0;
}

Line 7 should look like: int v[100]{}, n{}, num{}; or int v[100] = { 0 }, n = 0, num = 0;. Either works, but the first is the newest way to initialize your variable.

Line 12 will not work. First you start "i" at 1 when it should start at 0. You are missing the first element of the array. In the middle the "<=" would exceed the boundary of the array if it was not so big to start with.

In line 14 "i" should be "i + 1" for the screen display.

Line 15 do not input directly into the array yet. Back at line 7 I added "num" for input here.

Line 17 should be checking num not "v[i]". If num is divisible by 5 you do not want to store the number.

Line 19 v[i]=v[i+1]; since the array was not initialized "v[i + 1]" contains garbage at the t memory location. When you defined the variable it only reserved space for the array. Whatever is at those memory locations is unknown and referred to as garbage. So what you are trying to do is set a good location in the array to garbage. If you initialize the array to zeros then you would just be setting "v[i]" to zero.

The else part does not really do much and in the end I just scrapped this part.

Your code might be made to work I am not really sure. I came up with this to do the job. It is not pretty or even the best way to do this, but I hope that it is something you can understand and work with.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <limits>

//using namespace std;

int main()
{
	int v[100]{}, n{}, num{};

	std::cout << "Count of elements = ";
	std::cin >> n;

	for ( int i = 0; i < n; ++i)
	{
		std::cout << "\n Element " << i + 1 << " = ";
		std::cin >> num;

		if (num % 5 != 0)
		{
			v[i] = num;
		}
		//else
		//{
		//	//std::cout << v[i] << " ";  // If first number divisible by 5 element zero is zero and there is nothing to print.
		    // Also not the right to print.
		//}
	}

	for (int lc = 0; lc < n; lc++)
	{
		if (v[lc] == 0)
			continue;
		else
			std::cout << v[lc] << ' ';
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue";
	std::cin.get();

	return 0;
}

If you use some blank lines it makes the code easier to read and to find problems.

Hope that helps,

Andy

Edit:
Last edited on
@Andy, kinda skirting the goal by never adding the elements to the array to begin with, though technically reasonable solution.

I often advise against user input unless it's specifically required, and esp. not until the algorithm is nearly ready -- will just slow you down in testing.

This is more what I had in mind:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void Show(const vector<int>& v)
{
    for(auto& ele : v)
        cout << ele << " ";
    cout << endl;
    cout << "Size: "<<v.size() << endl << endl;
}

void Show(int* a, int a_size)
{
    for(int i=0; i<a_size; ++i)
        cout << a[i] << " ";
    cout << endl << endl;
}

// Zero out from beginning iterator to end iterator
void ZeroOut(int* it_begin, int* it_end)
{
    for(; it_begin!=it_end; ++it_begin)
        *it_begin = 0;
}

bool Divides5(int x) { return x%5 == 0; }

int main() 
{
    vector<int> nums = { 2, 6, 5, 10, 13, 15, 9 };
    
    cout << "Before:\n";
    Show(nums);
    
    cout << "After removal:\n";
    nums.erase(remove_if(nums.begin(), 
                         nums.end(), 
                         Divides5),
               nums.end());
    Show(nums);
    
    const int arr_size = 7;
    int arr[] = { 2, 6, 5, 10, 13, 15, 9 };
    cout << "Basic array before:\n";
    Show(arr, arr_size);
    
    cout << "Basic array after zeroing out:\n";
    ZeroOut(remove_if(&arr[0],
                      &arr[0]+arr_size,
                      Divides5),
            &arr[0]+arr_size);
    Show(arr, arr_size);
    
    return 0;
}

Before:
2 6 5 10 13 15 9 
Size: 7

After removal:
2 6 13 9 
Size: 4

Basic array before:
2 6 5 10 13 15 9 

Basic array after zeroing out:
2 6 13 9 0 0 0 
Last edited on
Topic archived. No new replies allowed.