Pass some elements of array to other | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pass some elements of array to other

I have an array containing multiple numbers, now I have to extract only prime numbers and save them in other array...can anyone tell how to pass prime numbers in other array? #include <iostream> using namespace std; bool isprime(int vs) { if (vs < 2) { return false; } for (int d = 2; ; d++) { if (vs % d == 0) { return false; } else { return true; } } } int main() { const int capacity = 10; int arr[capacity]; int prime[capacity]; cout << "enter array:\n"; for (int i = 0; i < capacity; i++) { int counter = 0; cin >> arr[i]; if (isprime(arr[i])) { prime[counter] = arr[i]; cout << arr[i] << " is prime" << endl; counter++; } } for (int counter = 0; counter < capacity; counter++) { cout << prime[counter] << endl; } }

15th Mar 2021, 2:09 PM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar
4 Answers
+ 1
Intialize a new array with size same as array of numbers. Take a variable say counter and assign it a value of 0. Loop over the array to find prime numbers and assign new_array the number like, new_array[counter]=number; //increment the counter by 1 counter++;
15th Mar 2021, 2:16 PM
Abhay
Abhay - avatar
+ 1
Martin Taylor thanks...you are pretty awesome in coding, I am in 2nd semester of CS, but still struggling with how to make logics, but hope it will come around with practice
16th Mar 2021, 3:53 AM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar
+ 1
Martin Taylor your loop in prime function is very complex
16th Mar 2021, 5:55 AM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar
0
Look at code...not working your idea
15th Mar 2021, 2:51 PM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar