Thursday, February 12, 2015

Solution of Quadratic Equation

Here is the code for calculating the root(s) of a quadratic equation.

Code

/* Note: compile with -lm option to link with the math library (for sqrt())
   e.g.: gcc quadratic.c -lm
*/
#include <stdio.h>
#include <math.h>

int main()
{
    int a, b, c, disc;

    printf("Enter the values for a, b, and c: ");
    scanf("%d%d%d", &a, &b, &c);

    disc = (b*b)-(4*a*c); /* discriminant */

    if(disc>0) /* Two real roots */
    {
        printf("The solutions are %f and %f\n", (-b+sqrt(disc))/(2*a), (-b-sqrt(disc))/(2*a));
    }
    else if(disc<0) /* Two imaginary roots */
    {
        printf("The solutions are %d+%f i and %d-%f i\n", -b/2, sqrt(-disc)/(2*a), -b/2, sqrt(-disc)/(2*a));
    }
    else /* Single real root */
    {
        printf("The solution is %f\n", (float)(-b)/(2*a));
    }

    return 0;
}

Output

Enter the values for a, b, and c: 1 -10 34
The solutions are 5+3.000000 i and 5-3.000000 i

Monday, February 9, 2015

Currency Denomination

You will wonder once you realise how powerful this simple code is! Given an amount, this program will print the denomination for it. The reason this code became really compact is, it makes use of array.

Code

#include <stdio.h>

int main()
{
    int currencies[] = {1000, 500, 100, 50, 10, 5, 2, 1};
    long int amount;
    int buf, pos = 0;

    printf("Enter the amount: ");
    scanf("%ld", &amount);

    while(amount > 0)
    {
        buf = amount/currencies[pos];
        if(buf > 0)
            printf("%d X %d\n", currencies[pos], buf);
        amount -= currencies[pos]*buf;
        pos++;
    }

    return 0;
}

Output

Enter the amount: 2313
1000 X 2
100 X 3
10 X 1
2 X 1
1 X 1

Swap Two Numbers Using Pointers

Here is the code for swapping two numbers using a function which is based on pointers. The basic concept used is pass by reference.

Code

#include <stdio.h>

void swap(int *x, int *y)
{
    int tmp;

    tmp  = *y;
    *y   = *x;
    *x   = tmp;
}

int main()
{
    int a, b;

    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);

    printf("\nBefore swapping: a = %d and b = %d\n", a, b);
    swap(&a, &b);
    printf("After swapping:  a = %d and b = %d\n", a, b);

    return 0;
}



Output

Enter two numbers: 10 20

Before swapping: a = 10 and b = 20
After swapping:  a = 20 and b = 10