- 2069 Chaitra · 6 marks
Count prime and composite until -1
Short answer
Read numbers until -1. For each n>1, test primality by checking divisors up to sqrt(n); increment prime or composite accordingly. Ignore 0,1.
Write a program to read the number until -1 is encountered. Also count the number of prime number and composite numbers entered by the user.
Read numbers until -1. A prime number is greater than 1 and has no divisor other than 1 and itself; a composite number is greater than 1 and has other divisors. To test a number, check divisibility by 2, 3, ... up to √n (i * i <= n). The numbers 0 and 1 are neither prime nor composite, so they are not counted.
#include <stdio.h>
int main(void)
{
int n, i, isprime, prime = 0, comp = 0;
printf("Enter numbers (-1 to stop):\n");
scanf("%d", &n);
while (n != -1)
{
if (n > 1)
{
isprime = 1;
for (i = 2; i * i <= n; i++)
if (n % i == 0)
{
isprime = 0;
break;
}
if (isprime) prime++;
else comp++;
}
scanf("%d", &n);
}
printf("Prime numbers = %d\nComposite numbers = %d\n", prime, comp);
return 0;
}
Output for the input 2, 9, 13, 1, 20, 7, -1:
Enter numbers (-1 to stop):
Prime numbers = 3
Composite numbers = 2
Primes: 2, 13, 7. Composite: 9, 20. The number 1 is neither.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Count even and odd until -1 · Computer Programming, chapter 5
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Sum of digits until single digit · Computer Programming, chapter 5 · asked 2×
- nth Fibonacci term prime check · Computer Programming, chapter 6
- Odd and even numbers to separate files · Computer Programming, chapter 10 · asked 2×
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- Count number of 1s in ROM data · Embedded System, chapter 9 · asked 2×
- Count number of 0s in ROM data · Embedded System, chapter 9 · asked 2×
- Prime number checking processor · Embedded System, chapter 2