AD1

Monday, 13 March 2017

Reverse bits of Byte

write a C function to reverse the bits of a Byte as example if we have variable unsigned char x=0x07=0b00000111 as input parameter after reversing its bits it would return 11100000

solution 


#include <stdio.h>
unsigned char reverse (unsigned char inbyte)
{
unsigned char outbyte=0;
for(int i=0;i<=7;i++)
{
if(inbyte&(1<<i))
{
outbyte|=1<<(7-i);
}
else
{
continue;
}
}
return outbyte;
}
int main(int argc, char** argv) {
unsigned char x=1;
unsigned char revx=reverse(x);
printf("%d\n",revx);
return (EXIT_SUCCESS);
}
view raw rev.c hosted with ❤ by GitHub

Tuesday, 7 March 2017

Palindrome String

Write a C code to check a String is palindrome or not , Some palindrome strings examples are "a", dad", "radar", "madam", "abcba" etc.

solution
#include <stdio.h>
#include <string.h>
int main()
{
// a program to check a string is palindrome or not
char string[20];
printf("Enter the string\n");
gets(string);
unsigned int i=0;
unsigned int j=strlen(string)-1;
unsigned int flag=0;
while(i!=j)
{
if(string[i]==string[j]){i++,j--;continue;}
else {flag=1;break;}
}
if(flag==0){printf("string is palindrome\n");}
else if(flag==1){printf("string is not palindrome\n");}
return 0;
}
view raw palin.c hosted with ❤ by GitHub



Monday, 6 March 2017

From decimal to binary

Write a C program to convert an integer from decimal to binary , using logical bitwise operators

solution
#include <stdio.h>
int main()
{
unsigned int x;
printf("enter any positive integer\n");
fflush(stdout);
scanf("%d",&x);
//sizeof(int)=4 byte on my machine
for(int i=0;i<=31;i++)
{
if(x&(0x8000>>i)){printf("%d",1);}
else {printf("%d",0);}
}
return 0;
}
view raw dtob.c hosted with ❤ by GitHub



Thursday, 2 March 2017

what is the output

what is the output of this C code 
#include <stdio.h>
union temp
{
int a;
char c;
};
int main()
{
union temp t={66,'A'};// initialize the union members
printf("%d\t%c\n",t.a,t.c);
printf("%d\n",sizeof(t));
return 0;
}
view raw union.c hosted with ❤ by GitHub
output:
66    B
4
Explanation:
union temp t={66,'A'};
this statement will initialize only the first member of the union x with 66 and the compiler will ignore the second value 'A', as one element is sufficient to initialize all union members as they share the same memory locations
sizeof(t) =4 size of largest element in memory location



Wednesday, 1 March 2017

what is the output of this C code

#include <stdio.h>
struct point
{
int x;
int y;
};
struct notpoint
{
int x;
int y;
};
int main()
{
struct point p1={10,20};
struct point p2={-10,-20};
p1=p2;
printf("%d\t%d",p1.x,p1.y);
struct notpoint p3={100,200};
p3=p1;
printf("%d\t%d",p3.x,p3.y);
if(p3>p2)
{
printf("hello\n");
}
else
{
printf("C programming\n");
}
return 0;
}
view raw s.c hosted with ❤ by GitHub
output :
compilation error in line 19 , as you can not assign two structures of different types
also there is a compilation error in line 21 as rational operators can not be applied on structures