I'm having trouble printing a fibonacci sequence using pointers with malloc to get this output.
now printing with pointers:
0 1 1 2 3 5 8 13 21 34 55 89
Here's my code:
#include <stdio.h>
#include <stdlib.h>
void fib1(int a[]);
void fib2(int* a);
int main() {
int arr[2] = {0,1};
int *pointer;
arr[0]=0;
arr[1]=1;
fib1(arr);
fib2(pointer);
return 0;
}
void fib1(int a[]){
printf("printing with arrays:\n");
for(int i=0; i<6; i++){
printf("%d %d ", a[0],a[1]);
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
void fib2(int * a){
printf("printing with pointers:\n");
for(int i=0; i<6; i++){
printf("%d %d ", *(a+0),*(a+1));
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
#include <stdio.h>
#include <stdlib.h>
void fib1(int a[]);
void fib2(int* a);
int main() {
int arr[2] = {0,1};
int *pointer;
arr[0]=0;
arr[1]=1;
fib1(arr);
//creating the malloc with size 2
pointer=(int *)malloc(2*sizeof(int));
// adding 1st value as 0 and second value as 1
pointer[0]=0;
pointer[1]=1;
fib2(pointer);
return 0;
}
void fib1(int a[]){
printf("printing with arrays:\n");
for(int i=0; i<6; i++){
printf("%d %d ", a[0],a[1]);
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
void fib2(int * a){
printf("printing with pointers:\n");
for(int i=0; i<6; i++){
printf("%d %d ", *(a+0),*(a+1));
a[0] = a[0] + a[1];
a[1] = a[0] + a[1];
}
printf("\n\n");
}
Get Answers For Free
Most questions answered within 1 hours.