This is Corinne. I want to put the prime numbers in the b array and get it back to zero when it's not a prime number. I think I made the wrong code for the few, but what's the problem?
#include<stdio.h>
#include<string.h>
int main() {
int n, j, i, a[20] = { 0 }, s[20] = { 0 }, b[20] = { 0 }, cnt = 0;
scanf_s("%d", &n);
for (i = 0;i < n;i++) {
scanf_s("%d", &a[i]);
}
for (i = 0;i < n;i++) {
for (j = 1;j < a[i];j++) {
if (a[i] % j == 0) {
cnt++;
}
}
if (cnt == 1) {
b[i] = a[i];
}
for (i = 0;i < n;i++) {
printf("%d ", b[i]);
}
return 0;
}// Enter code here
This is because there is no part that initializes cnt
to zero while looping.
Please refer to the code below.
#include<stdio.h>
#include<string.h>
int main()
{
int n = 0, cnt = 0;
int a[20] = { 0 }, b[20] = { 0 };
scanf_s("%d", &n);
for (int i = 0; i < n; i++)
scanf_s("%d", &a[i]);
for (int i = 0; i < n; i++)
{
cnt = 0;
for (int j = 1; j < a[i]; j++)
{
if (a[i] % j == 0)
cnt++;
}
if (cnt == 1)
b[i] = a[i];
}
for (int i = 0; i < n; i++)
printf("%d ", b[i]);
return 0;
}
© 2024 OneMinuteCode. All rights reserved.