Hey everyone, I'm trying to get this code to work...

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

int allPrimes(int n) 
{
	int kiloN = n*1000;
	int count = 0;
	int i;
	for(i = 2; i <= kiloN; i++) 
	{
		boolean hasfactor = false;
		int j = 2;
		while(j<i and !hasfactor) 
		{
			if(i%j=0) 
			{
				hasfactor = true;
			}
			if(hasfactor) 
			{
				printf(i);
				count++;
			}
		}
	}
	printf("Count: %d",count);
	return count;
}

Errors keep popping up.

Any help?

Recommended Answers

All 5 Replies

while(j<i and !hasfactor)

In C there's not an operator and, the proper operator is &&

if(i%j=0)

That's an assignment, watch your = symbols. For equal to you need two ==

printf(i);

That's incorrect as well. printf("%d", i); is the proper syntax.

while(j<i and !hasfactor)

In C there's not an operator and, the proper operator is &&

if(i%j=0)

That's an assignment, watch your = symbols. For equal to you need two ==

printf(i);

That's incorrect as well. printf("%d", i); is the proper syntax.

Thanks, I fixed up my code and it looks like this now:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

int allPrimes(int n) 
{
	int kiloN = n*1000;
	int count = 0;
	int i;
	for(i = 2; i <= kiloN; i++) 
	{
		boolean hasfactor = false;
		int j = 2;
		while(j<i && !hasfactor) 
		{
			if(i%j==0) 
			{
				hasfactor = true;
			}
			if(hasfactor) 
			{
				printf("%d", i);
				count++;
			}
		}
	}
	printf("Count: %d",count);
	return count;
}

But it still keeps coming up with errors:

a1q8.c:29: warning: file does not end in newline
a1q8.c: In function `allPrimes':
a1q8.c:12: `boolean' undeclared (first use in this function)
a1q8.c:12: (Each undeclared identifier is reported only once
a1q8.c:12: for each function it appears in.)
a1q8.c:12: parse error before `hasfactor'
a1q8.c:14: `hasfactor' undeclared (first use in this function)

All of those errors are related to the same problem.
There is not a boolean type defined anywhere in stdbool.h . However there is a bool type.

All of those errors are related to the same problem.
There is not a boolean type defined anywhere in stdbool.h . However there is a bool type.

Ok, thanks so much!

Also, I was wondering how I would be able to ask the user to input a number (n).

This is my first time using C.

Also, I was wondering how I would be able to ask the user to input a number (n).

This is my first time using C.

Glad you asked. This is the right time then, to learn properly.
Read an Integer from the User

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.