I write the code as my knowledge but i didnt get the correct ouput.i provide my code below
#include <stdio.h>
int main() {
int i, j, isPrime, n, a[1000], k;
// Input array limit
printf("Enter array limit: ");
scanf("%d", &n);
// Input array elements
printf("Enter array elements:n");
for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
// Loop through the array
for(i = 0; i < n; i++;) {
// Check if current element is prime
if (a[i] < 2) {
isPrime = 0; // Numbers less than 2 are not prime
} else {
isPrime = 1; // Assume the number is prime
for (j = 2; j * j <= a[i]; j++) {
if (a[i] % j == 0) {
isPrime = 0; // Found a divisor, not a prime number
break;
}
}
}
// Print the current number based on prime status
if (isPrime) {
printf("%d ", a[i]);
} else {
printf("%d ", a[i]);
// Skip the next two elements by shifting the array
for (k = i + 1; k < n - 2; k++) {
a[k] = a[k + 2];
}
n -= 2; // Reduce array size by 2
i--; // Recheck the current position
}
}
return 0;
}
when i run this code i didnt get the correct output.
eg:-
if I enter array limit 9 and print 1-9 i got the output as 1 1 1 1 1 .
Can u please help me to solve this problem
I want a solution for my problem.
Misthah Kp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
Firstly I would like to say that you should probably learn gdb in order to solve simpler things such as this
It seems you also have some small errors within your code:
-
You have a semicolon in your for loop which you don’t need, it should look like the following:
for(i = 0; i < n; i++)
-
You need to change your logic to actually accept 1 as not being prime
a[i] < 2
tonum <= 1
-
Instead of shifting the array, you should probably index the elements to skip around
-
Use a
while
loop instead of afor
loop -
remove
i--
as its leading to the output just being 1
Hopefully this helps a little, but just know that learning to use a debugger and also how to simply google could have probably fixed this issue.
— Andrew
Mandrew002 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.