Simple C programs

(1) Nth Fibonacci number using recursion

int main() {

int n;

scanf(“%d”, &n);

printf(“Nth fibonnaci number = %d”, fibonnaci(n));

}

int fibonnaci(int N) {

if (N==0) return 0;

else if (N==1) return 1;

else return (fibonnaci(n-1)+fibonnaci(n-2));

}

(2) Write a C function which returns true if the input number is power of 2.

int Powerof2(int N) {

return ((N>0) &&(! (N&(N-1))));

}

(3) Write a C function to find the number of bits set in a given number

int Numofones(int N) {

int count = 0;

while(N!=0) {

N = N&(N-1);

count+=1;

}

}

What is the complexity? Is there a simpler logic? or can this logic be more optimized?

(4) Write a c program to reverse a string with out using any additional memory (Reverse in place)

int main () {

char array1[100];

gets(array1);

// gets can read sentence (which may contain spaces), printf can read only one string

strrevx(array1);

puts(array1);

return 0;

}

void strrevx(char* start) {

char* last = start; // start and end at same place

char temp;

while (last!=’\0′) {

last++; // Trace back to end of the string

}

last- -; // point to the location before end of string

while (start<last) { temp = *start; *start++ = *last; *last- – = temp; } }

(5) Implement you own sizeof operator in C and try some examples

#define size_of_data(x) ((char*)(&x+1)-(char*)(&x))

int main () {

int num1;

struct struct_name {

int value1;

struct struct_name* p;

} instance1;

union union_name {

int value2;

char arr1[4];

} instance2;

printf(“%d %d %d”,size_of_data(num1),size_of_data(instance1),size_of_data(instance2));

}

output: 4 8 4

(6) How to find the endianess of a system

int main () {

unsigned int i = 0x00000001;  // same as writing 1

char* p = (char*)&i;

if (*P) { printf(“little endian”);}

else {printf(“Big Endian”);}

return 0; }

In little-endian systems, the lower value (LSB Byte) is stored in lower address

littleendian1

In Big-endian systems, the higher value (MSB byte) is stored in lower address

bigendian1

Visually remember:

eggs

Leave a comment