Friday, November 28, 2014

C useful pro



Find the roots of a quadratic equation

#include
#include
#include
#include
void main()
{
float a,b,c,x1,x2,disc;
clrscr();
printf("Enter the co-efficients\n");
scanf("%f%f%f",&a,&b,&c);
disc=b*b-4*a*c;
if(disc>0)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("The roots are distinct\n");
exit(0);
}
if(disc==0)
{
x1=x2=-b/(2*a);
printf("The roots are equal\n");
printf("x1=%f\nx2=%f\n",x1,x2);
exit(0);
}
x1=-b/(2*a);
x2=sqrt(fabs(disc))/(2*a);
printf("The roots are complex\n");
printf("The first root=%f+i%f\n",x1,x2);
printf("The second root=%f-i%f\n",x1,x2);
getch();
}

Find the factorial of a number

#include
#include
int main()
{
int i=1,f=1,num;
printf("\nEnter a number:");
scanf("%d",&num);
while(i<=num)
{
f=f*i;
i++;
}
printf("\nFactorial of %d is:%d",num,f);
return 0;
}

Reverse the words in a sentence in place

#include
#include
void rev(char *l, char *r);
int main(int argc, char *argv[])
{
char buf[] = "the world will go on forever";
char *end, *x, *y;
for(end=buf; *end; end++);
rev(buf,end-1);
x = buf-1;
y = buf;
while(x++ < end)
{
if(*x == '' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
printf("%s\n",buf);
return(0);
}
void rev(char *l,char *r)
{
char t;
while(l {
t = *l;
*l++ = *r;
*r-- = t;
}
}

Print all permutations of a given string

# include
# include
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j));
}
}
}
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
getchar();
return 0;
}

No comments:

Post a Comment