+ 2

Usin arrays write a program that inputs five numbers and if there are any zeros, removes them and shows the app nput without 0s.

My attempt so far #include <iostream> using namespace std; int main() { int i = 0; int num[5]; for (int j = 1; j < 6; j++) { cout << "Enter number [" << j << "]= " << endl; cin >> i; } for (int j = 0; j < 5; j++) { if (i!='0') { i++; } } cout << "Non zero: " << endl; for (int i= 0; i < 5; i++) { cout << num[i] << "\t"; } return 0; }

23rd Jan 2020, 7:24 PM
Shakiba
7 Respuestas
0
int main(){ int numbers[5]; int counter = 0, i = 0; for (int j = 0; j < 5; j++) { cout << "Enter number [\" << j << \"]= " << endl; cin >> i; numbers[j] = i; } for(int x = 0;x < 5;x++) if(numbers[x] != 0) counter++; int numbers2[counter]; // declare a second array to the size of non-zero count for(int x = 0,z = 0; x < 5; x++) if(numbers[x] != 0){ numbers2[z] = numbers[x]; z++; } for(int x = 0; x < counter; x++) cout << numbere2[x] << ','; return 0; }
23rd Jan 2020, 8:55 PM
rodwynnejones
rodwynnejones - avatar
+ 1
blackwinter thank you so much. you have no idea how helpful you’ve been.
23rd Jan 2020, 8:40 PM
Shakiba
0
Thanks. unfortunately it doesn’t. If there was a way that I could keep the first and last for and change the middle for it would be great.
23rd Jan 2020, 7:34 PM
Shakiba
0
if your looking to actually remove the zeros then, I would use a vector. http://www.cplusplus.com/reference/vector/vector/ edit:- On second thoughts.... I would use list:- http://www.cplusplus.com/reference/list/list/
23rd Jan 2020, 8:01 PM
rodwynnejones
rodwynnejones - avatar
0
how can I store non zero elemnts? sorry I’m so new at this.
23rd Jan 2020, 8:04 PM
Shakiba
0
@blackwinter your method requires you to declare a seconds "empty" array of the same size as the first..now if you assign all the non-zeros to this second array, all of the other elements will be assigned a default value of....guess what?....zeros.
23rd Jan 2020, 8:17 PM
rodwynnejones
rodwynnejones - avatar
0
rodwynnejones do you have any other way to do this?
23rd Jan 2020, 8:24 PM
Shakiba