Exercise 2

2s complement of a number is obtained by scanning it from right to left and complementing all the bits after the first appearance of a 1. Thus 2s complement of 11100 is 00100. Write a C program to find the 2s complement of a binary number.



SOURCE CODE:


/*Program to find 2's complement of a given binary number.*/

#include<stdio.h>
#include<conio.h>
void main()
{
 int a[10],b[10],i,j,n;
 clrscr();
 printf("\nEnter number of bits::\n");
 scanf("%d",&n);
 printf("\nEnter %d bits::\n",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 for(i=n-1,j=0;i>=0;i--,j++)
 {
  if(a[i]!=1)
   b[j]=a[i];
  else
  {
   b[j]=a[i];
   i--;
   j++;
   for(;i>=0;i--,j++)
   {
    if(a[i]==1)
     b[j]=0;
    else
     b[j]=1;
   }
  }
 }
 printf("\nTwo's complement of given binary number is::\n");
 for(j=n-1;j>=0;j--)
  printf("%d",b[j]);

}

OUTPUT:









Write a C program to find the roots of a quadratic equation.

SOURCE CODE:

/*Program to find roots of given quadratic equation.*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
 double a,b,c,d,r1,r2,real,imag;
 clrscr();
 printf("\nEnter a,b and c values:\n");
 scanf("%lf%lf%lf",&a,&b,&c);
 d=(b*b)-(4*a*c);
 if(d>0)
 {
  r1=(-b+sqrt(d))/(2*a);
  r2=(-b-sqrt(d))/(2*a);
  printf("\nRoots are:\n r1=%.2lf\tr2=%.2lf",r1,r2);
 }
 else
 if(d==0)
 {
  r1=(-b)/(2*a);
  r2=(-b)/(2*a);
  printf("\nRoots are:\n r1=%.2lf\tr2=%.2lf",r1,r2);
 }
 else
 {
  real=(-b)/(2*a);
  imag=(sqrt(d))/(2*a);
  printf("\nRoots are:\n r1=%.2lf+i%.2lf\tr2=%.2lf-i%.2lf",real,imag,real,imag);
 }
}

OUTPUT:











Write a C program, which takes two integer operands and one operator form the user, performs the operation and then prints the result. (Consider the operators +,-,*, /, % and use Switch Statement)

SOURCE CODE:

/*Program to perform arthmetic operation between two numbers.*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int a,b;
 char op;
 clrscr();
 printf("\nEnter a and b values:\n");
 scanf("%d%d",&a,&b);
 printf("\nEnter operator:\n");
 op=getche();
 switch(op)
 {
  case '+':printf("\na+b=%d",a+b);
  break;
  case '-':printf("\na-b=%d",a-b);
  break;
  case '*':printf("\na*b=%d",a*b);
  break;
  case '/':printf("\na/b=%d",a/b);
  break;
  case '%':printf("\na%%b=%d",a%b);
  break;
  default:printf("\nWrong Arthmetic Operator.");
 }
}

OUTPUT: