we have been asked to write a program to generate fibonacci series as our homework.
so i wrote a program that generates the first n fibonacci numbers .here is my frist code that dosent work properly
# include <stdio.h>
void main()
{
int a = -1, b = 1, c = 0, i, n, sum = 0 ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nThefibonacci series is : \n\n") ;
for(i = 1 ; i <= n ; i++)
{
c = a + b ;
printf("%d \t", c) ;
b=c;
a=b;
}
}
so i tried various combinations and i found out that my code would work well if i interchanged the 12th and 13th lines. i.e
# include <stdio.h>
void main()
{
int a = -1, b = 1, c = 0, i, n, sum = 0 ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("\nThefibonacci series is : \n\n") ;
for(i = 1 ; i <= n ; i++)
{
c = a + b ;
printf("%d \t", c) ;
a=b;
b=c;
}
}
It is the same logic right.
why does the first code give me wrong output?
what are segmentation faults?(my compiler frequently tells me that there are segmentation faults in my code)
P.S-i am a begginer.Just three weeks into c language and we are learning about loops.
Lines are executed in order, so in the first example
bbecomescbeforeabecomesb, in effect you are assigningcto bothaandbcreating some kind of exponential series (but of zeroes) instead of the fibonacci sequence.A segmentation fault means that your program is accessing memory somewhere where it is not allowed to access memory, usually because you are dereferencing an invalid pointer or accessing an array out of bounds.