heres my for loopheres the errorCode:for(int i = 2; i < x; i++) { //code here }
Code:error: ‘for’ loop initial declaration used outside C99 mode
heres my for loopheres the errorCode:for(int i = 2; i < x; i++) { //code here }
Code:error: ‘for’ loop initial declaration used outside C99 mode
Don't declare the variable in the loop, declare it before the loop.
You can't declare variables within the parenthesis following the for statement by C90 standards. I think C99 allows this. Rewriting it like this will work:
PHP Code:
int x;
for (x = 0; x < y; x++){
// code here
}
Programming is an art. Learn it. Live it. Love it.
and why am i getting floating point exceptions in here?
while were here...does vim have auto indenting?PHP Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isPrime( int x );
int main()
{
int x;
printf("enter a number: \n", x);
scanf("%d", &x);
if (isPrime(x) == true) printf("is prime \n");
if (isPrime(x) == false) printf("is not primeprime \n");
return 0;
}
bool isPrime(int x)
{
int i;
if (x < 2)
{
return false;
}
else
{
for(i = 0; i < x; i++)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
}
You are computing x % 0 when i is 0, which is not allowed--it is like dividing by 0. Change the starting value of i in the loop to be 2. Not 1, because x % 1 is always 0.
There are faster ways to determine if a number is prime, but that should fix your immediate problem.
First of all, you're getting a floating point exception at
You can use the GNU DeBugger (GDB) to easily find the lines that are making your program crash, along with tons of other valuable information.PHP Code:
if (x % i == 0)
You get it because it performs the operation (int) % 0. Your for loop should start with 2. 0 will raise floating point exceptions and 1 will return everything as composite.
There are an infinite number of primes below the number two. That code makes your program return incorrect solutions. Perhaps you mean return true;. All numbers below two are prime, not composite.PHP Code:
if (x < 2)
{
return false;
}
... This is a fairly obvious mistakePHP Code:
printf("enter a number: \n", x);
scanf("%d", &x);
You should also look into the Sieve of Eratosthenes, it's not very complex, but even when you get your algorithm to work it will be very slow. It's easy to optimize it using elements of some well-established sieves and algorithms.
And yes, vim has autoindenting. It's an option you can set in your ~/.vimrc or enable realtime.
Last edited by Phenax; November 10th, 2008 at 03:38 AM.
now about that indenting thing...is there auto indenting in vim or are there lightweight editors with it?
thanks...i have to stop coding past 9 pm...
Bookmarks