I'm working with Kochan's Programming in C. I am working in Visual Studio 2008. When I try to build the program I get

Error 2 error C2143: syntax error : missing ';' before 'type' c:\users\michael\documents\visual studio 2008\projects\cpractice\cpractice\char.c 15 CPractice

But as far as I'm aware there is no syntax error. It seems the issue is declaring the array after the printf and scanf functions have been called. If I put

unsigned long long int Fibonacci[5];

before the function calls, it works fine. Put it after, error.

#include<stdio.h>

int main (void)
{
	int i, numFibs;
	

	printf("How many Fibonacci numbers do you want (between 1 and 75)? ");
	scanf("%i", &numFibs);

	if (numFibs < 1 || numFibs > 75) {
		printf("Bad number, sorry!\n");
		return 1;
	}
	unsigned long long int Fibonacci[numFibs];

	Fibonacci[0] = 0;
	Fibonacci[1] = 1;

	for (i=2; i<numFibs; ++i)
		Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

	for (i=0; i<numFibs; ++i)
		printf("%llu ", Fibonacci[i]);

	printf("\n");

	return 0;
}
Re: Simple C question. Fibonacci sequence 80 80

> before the function calls, it works fine. Put it after, error.
That's because your C doesn't allow mixing declarations and statements.

It's allowed in C99, but you don't have a C99 compiler.

You will have to use malloc.

Re: Simple C question. Fibonacci sequence 80 80

Hi
malloc is the best practice to do programmings like Fibonacci and all
all the best
Happy Programing

Re: Simple C question. Fibonacci sequence 80 80

Try using my code:

#include <stdio.h>

int main()
{
unsigned int n;
int k, l;
int p = 0;
k = 1;
l = 0;
scanf("%d", &n);
printf("1\n");
while((k<=n) && (l<=n))
{
  if(p % 2 == 0)
  {
  l = k + l;
    if(l <= n)
    {
    printf("%d\n", l);
    }
  else
  k = k + l;
    if (k <= n)
    {
    printf("%d\n", k);
    }
  }
    p++;
}
system("PAUSE");
}

n is the same as your numFib

Re: Simple C question. Fibonacci sequence 80 80

Hi
malloc is the best practice to do programmings like Fibonacci

Why?

Re: Simple C question. Fibonacci sequence 80 80

Why?

Because at first we can declare something like:
int *a;

and then

scanf("%d",&n);
a=malloc(sizeof(int[n]));

then we wont require value of 'n' prior to the array declaration.

Re: Simple C question. Fibonacci sequence 80 80

Why not just int a[100]; Or, knowing the limitation of int just declare the array as int a[41]; and save the time and processing to input a value and call malloc() ?

Re: Simple C question. Fibonacci sequence 80 80


Or, knowing the limitation of int

What is this limitation ?

Re: Simple C question. Fibonacci sequence 80 80

unsigned int: 2 ^32 - 1

Be a part of the DaniWeb community

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