include<iostream>
using namespace std;
int main()
{
int list[9] = {1,0,0,2,0,3,0,0,4};
int counter2nd = 0;
for( int I = 0; I < 9; I++)
if(list[I] == 0)
{
}
for(int l = 0; l < 9; l++)
{
if(list[l] != 0)
This is how your code looks in "code tags" (and fixed up a little).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int list[9] = {1,0,0,2,0,3,0,0,4};
for (int i = 0; i < 9; i++)
{
if (list[i] != 0)
cout << list[i] << ' ';
}
cout << endl;
return 0;
}
To put your code in code tags, simply paste it between [code] and [/code], like this:
[code]
paste your code here
[/code]
Your program does not actually "remove the zeros" from the array.
It just prints the array without the zeros.
That's a different thing, and as you've discovered, is much easier to do.
#include <iostream>
#include <algorithm>
int main()
{
constexprint Capacity {9} ;
int array[Capacity] {1,0,0,2,0,3,0,0,4} ;
// print it out
for( int v : array ) std::cout << v << ' ' ;
std::cout << '\n' ;
// copy non-zero elements to front of array
auto end = std::remove( array, array + Capacity, 0 ) ;
int size = end - array; // count of remaining elements
// print out the first size elements
for( int i=0; i < size; ++i ) std::cout << array[i] << ' ' ;
std::cout << '\n' ;
// print out the whole array
for( int v : array ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
Keep in mind allenmaki that the code you just presented here does not remove the unwanted 0's from the array. You are just skipping over them with that cout bit. To really remove the 0's you will need to go with one of the other suggestions here.
Visual Studio 2008 won't support C++11 syntax.
Microsoft has free versions of Visual Studio ("Visual Studio Community" I believe it's called), so I would suggest downloading that. But if you are truly stuck with 2008:
Change constexprint Capacity {9} ; to constint Capacity = 9;
Change for( int v : array ) std::cout << v << ' ' ;
to
1 2 3 4
for (int i = 0; i < 9; i++)
{
std::cout << array[i] << ' ';
}