Pages - Menu

Thursday 1 November 2012

Converting temperature in C

Celsius to Fahrenheit

The following C function receives a temperature in degrees Celsius and returns the equivalent temperature in  Fahrenheit.
/*
 * Description:
 *  Converts temperature from Celsius to Fahrenheit
 * Parameters:
 *  celsiusTemperature - temperature in degrees Celsius to be converted
 * Returns:
 *  fahrenheitTemperature - the equivalent temperature in the Fahrenheit scale
 */
float CelsiusToFahrenheit(float celsiusTemperature)
{
    float fahrenheitTemperature = celsiusTemperature*9/5+32;
    return fahrenheitTemperature;
}

Fahrenheit to Celsius

The following C function receives a temperature in degrees Fahrenheit and returns the equivalent temperature in Celsius.
/*
 * Description:
 *  Converts temperature from Fahrenheit to Celsius
 * Parameters:
 *  fahrenheitTemperature - temperature in degrees Fahrenheit to be converted
 * Returns:
 *  celsiusTemperature - the equivalent temperature in the Celsius scale
 */
float FahrenheitToCelsius(float fahrenheitTemperature)
{
    float celsiusTemperature = (fahrenheitTemperature-32)*5/9;
    return celsiusTemperature;
}

Example:

This C program takes your option and uses one of the functions above in accordance to your choice to convert the given temperature from one scale to the other.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

float CelsiusToFahrenheit(float celsiusTemperature);
float FahrenheitToCelsius(float fahrenheitTemperature);

int main(void)
{
    float celsiusTemperature = 0, fahrenheitTemperature = 0;
    int option = 0, exit = 0;
    while (exit == 0)
    {
        system("cls");
        printf("\n Choose your option: "
               "\n\t[1] Convert Celsius to Fahrenheit"
               "\n\t[2] Convert Fahrenheit to Celsius"
               "\n\t[0] Exit the program\n");
        scanf("%d",&option);
        switch (option)
        {
        case 1:
            printf("\n Enter the temperature in degrees Celsius: ");
            scanf("%f",&celsiusTemperature);
            fahrenheitTemperature = CelsiusToFahrenheit(celsiusTemperature);
            printf(" The equivalent in Fahrenheit is: %.1f",
                   fahrenheitTemperature);
            getch();
            break;
        case 2:
            printf("\n Enter the temperature in degrees Fahrenheit: ");
            scanf("%f",&fahrenheitTemperature);
            celsiusTemperature = FahrenheitToCelsius(fahrenheitTemperature);
            printf(" The equivalent in Celsius is: %.1f",celsiusTemperature);
            getch();
            break;
        case 0:
            exit = 1;
            break;
        default:
            printf("\n Enter again.");
            getch();
            break;
        }
    }
    getch();
    return 0;
}
Output:  

Tuesday 30 October 2012

Divisors in C

A divisor of a integer number is a integer which divides the given number without leaving a remainder.

In computing, finding the reminder of division of a number by another is called a modulo operation. To find the remainder of a divison in C, use the modulus operator %.

The function below checks whether or not the second integer received as argument is among the first number's divisors.
/*
 * Description:
 *  Checks if a number is divisible by another
 * Parameters:
 *  number  - the dividend
 *  divisor - integer to be checked as divisor
 * Returns:
 *  0 - if number is divisible by divisor
 *  1 - if number is not divisible by divisor
 */
int Divisor(int number, int divisor)
{
    int i = 0;
    if (divisor != 0)
    {
        if (number%divisor == 0)
        {
            return 1;
        }
    }
    return 0;
}
Example 1: checking if a number is divisible by another
#include<stdio.h>
#include<conio.h>

int Divisor(int number, int divisor);

int main(void)
{
    int number = 0, divisor = 0, ok = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    printf(" Enter the divisor to be checked: ");
    scanf("%d",&divisor);
    ok = Divisor(number,divisor);
    if (ok == 0)
    {
        printf("\n\t%d is not divisible by %d.",number,divisor);
    }
    else if (ok == 1)
    {
        printf("\n\t%d is divisible by %d.",number,divisor);
    }
    getch();
    return 0;
}
Output:  

Example 2: displaying all the divisors of a given number
#include<stdio.h>
#include<conio.h>

int Divisor(int number, int divisor);

int main(void)
{
    int number = 0, i = 0, ok = 0, counter = 0;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    if (number > 0) //if the dividend is positive
    {
        for (i=1; i<=number; i++)
        {
            ok = Divisor(number,i);
            if (ok == 1)
            {
                if (counter == 0)
                {
                    printf("\n\t%d is divisible by: %d ",number,i);
                    counter++;
                }
                else if (counter > 0)
                {
                    printf("%d ",i);
                }
            }
        }
    }
    else if (number < 0) //if the dividend is negative
    {
        for (i=number; i<=-number; i++)
        {
            ok = Divisor(number,i);
            if (ok == 1)
            {
                if (counter == 0)
                {
                    printf("\n\t%d is divisible by: %d ",number,i);
                    counter++;
                }
                else if (counter > 0)
                {
                    printf("%d ",i);
                }
            }
        }
    }
    getch();
    return 0;
}
Output:  

Example 3: determine the number the divisors of a given number
#include<stdio.h>
#include<conio.h>

int Divisor(int number, int divisor);

int main(void)
{
    int number = 0, i = 0, counter = 0, ok = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    if (number > 0) //if the dividend is positive
    {
        for (i=1; i<=number; i++)
        {
            ok = Divisor(number,i);
            if (ok == 1)
            {
                counter++;
            }
        }
    }
    else if (counter < 0) //if the dividend is negative
    {
        for (i=number; i<=-number; i++)
        {
            ok = Divisor(number,i);
            if (ok == 1)
            {
                counter++;
            }
        }
    }
    printf("\n\t%d has %d divisors.",number,counter);
    getch();
    return 0;
}
Output:  

Friday 26 October 2012

Implementation of a Hangman game in C

The game allows you to choose one of the six categories, then it randomly chooses a word to be guessed. At the end, it displays the selected word, whether you lose the game or win it, as well as a option to start a new game.

The functions used for console graphics have been discussed in a previous article:

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<time.h>
#include"GRAPH_LIB.h"

#define MAX_WORD_LENGTH 255 //the maximum length of a word

/*---------------GLOBALS--------------*/
char categories[6][25]; //categories of words
FILE *file = NULL; //pointer to the file to be opened
char word[MAX_WORD_LENGTH]; //the selected word from the file
int newGame = 1; //variable to decide whether or not to start a new game

/*-------------PROTOTYPES-------------*/
/*
 * Description:
 *  Displays the header
 */
void Header(void);

/*
 * Description:
 *  Opens the file containing the words from a category based on the option parameter
 * Parameters:
 *  option - the selected option from the menu of categories
 */
void DecideFile(int option);

/*
 * Description:
 *  Displays the categories' menu and allows the user to select a category
 */
void Menu(void);

/*
 * Description:
 *  Randomly selects a word from the opened file
 */
void DecideWord(void);

/*
 * Description:
 *  Displays a menu allowing the player to decide whether or not to start a new game
 * Returns:
 *  1 - starting a new game
 *  0 - not starting a new game
 */
int NewGame(void);

/*
 * Description:
 *  Displays a message letting know that you lost the game as well as the word you had to guess.
 */
void LostGame(int wordLength);

/*
 * Description:
 *  Displays the word you had to guess and a message letting you know that you won the game.
 */
void WonGame(int wordLength);

/*
 * Description:
 *  Starts the game and contains the game's logic.
 */
int Gameplay(void);

/*-------------IMPLEMENTATION-------------*/
void Header(void)
{
    ConsoleDimensions(120,50);
    ConsoleColours("gray","white");
    DrawRectangle(0,0,120,7,"dark blue");
    GoTo(56,2);
    Colour("dark blue","gray");
    puts("HANGMAN");
    GoTo(55,3);
    puts("July 2012");
    GoTo(49,4);
    puts("Copyright@INFINITE LOOP");
}

void DecideFile(int option)
{
    switch(option)
    {
    case 0:
        file=fopen("actors.txt","rt");
    case 1:
        file=fopen("animals.txt","rt");
    case 2:
        file=fopen("bands.txt","rt");
    case 3:
        file=fopen("countries.txt","rt");
    case 4:
        file=fopen("films.txt","rt");
    case 5:
        file=fopen("sports.txt","rt");
    default:
        file=fopen("actors.txt","rt");
    }
}

void Menu(void)
{
    int i = 0, j = 0;
    int option = 0;
    char move = 32;
    Header();
    //rectangle at the bottom
    StripesOutline(9,41,100,5,"gray","dark blue");
    DrawRectangle(10,42,100,5,"dark gray");
    GoTo(25,44);
    Colour("dark gray","black");
    printf("Use %c and %c to move through the menu. Press Enter to choose a category.",30,31);
    //initialising the categories
    strcpy(categories[0],"  Actors ");
    strcpy(categories[1]," Animals ");
    strcpy(categories[2],"  Bands  ");
    strcpy(categories[3],"Countries");
    strcpy(categories[4],"  Films  ");
    strcpy(categories[5]," Sports  ");
    //the menu
    StripesOutline(44,17,31,15,"gray","cyan");
    DrawRectangle(45,18,31,15,"cyan");
    while(move != 13)
    {
            for(i=0; i<6; i++)
            {
                GoTo(51,20+i*2);
                for(j=0; j<5; j++)//before printing the category
                {
                    if(option == i)
                    {
                        Colour("magenta","magenta");
                        printf("*");
                    }
                    else
                    {
                        Colour("dark blue","dark blue");
                        printf("*");
                    }
                }
                if(option == i)
                {
                    Colour("magenta","white");
                }
                else
                {
                    Colour("dark blue","gray");
                }
                puts(categories[i]);
                GoTo(56+strlen(categories[i]),20+i*2);
                Colour("dark blue","dark blue");
                for(j=0; j<5; j++)//after printing the category
                {
                    if(option == i)
                    {
                        Colour("magenta","magenta");
                        printf("*");
                    }
                    else
                    {
                        printf("*");
                    }
                }
            }
            move=getch();
            if(move == 0x50)//down arrow
            {
                option++;
                if(option == 6)
                {
                    option = 0;
                }
            }
            if(move == 0x48)//up arrow
            {
                option--;
                if (option == -1)
                {
                    option=5;
                }
            }
    }
    DecideFile(option);//opening the file corresponding to the chosen category
}

void DecideWord(void)
{
    int wordsCount = 0;
    int wordNumber = 0;
    int i=0;
    time_t seconds;
    time(&seconds);
    srand(seconds);
    if(file != NULL)
    {
        while(feof(file) == 0)
        {
            fgets(word,255,file);
            wordsCount++;
        }
        wordNumber = rand() % wordsCount;
        rewind(file);
        while(i <= wordNumber)
        {
            fgets(word,255,file);
            i++;
        }
    }
    if(wordNumber+1 != wordsCount)//otherwise it will contain the new line character - ??
    {
        word[strlen(word)-1] = '\0';
    }
}

int NewGame(void)
{
    int newGame = 0;
    char move = 32;
    StripesRectangle(40,42,40,7,"dark gray","gray");
    GoTo(44,44);
    Colour("neon green","black");
    printf("Do you want to start a new game?");
    while(move != 13)
    {
        GoTo(57,46);
        if(newGame == 1)
        {
            Colour("white","black");
        }
        else
        {
            Colour("neon green","black");
        }
        printf(" YES ");
        GoTo(57,47);
        if(newGame == 0)
        {
            Colour("white","black");
        }
        else
        {
            Colour("neon green","black");
        }
        printf("  NO ");
        move=getch();
        if(move == 0x48)//down arrow
        {
            newGame = 1;
        }
        if(move == 0x50)//up arrow
        {
            newGame = 0;
        }
    }
    return newGame;
}

void LostGame(int wordLength)
{
    int  i = 0;
    system("cls");
    Header();
    StripesOutline(39,18,40,6,"gray","neon green");
    DrawRectangle(40,19,40,6,"dark gray");
    GoTo(55,21);
    Colour("dark gray","black");
    puts("GAME OVER");
    GoTo(54,22);
    puts("#You  lost#");
    DoubleBorderGrid((120-6*wordLength)/2,35,3,3,1,wordLength,"gray","white");
    Colour("gray","cyan");
    for(i=0; i<wordLength; i++)
    {
        GoTo((120-6*wordLength)/2+6*i+2,37);
        printf("%c",word[i]);
    }
}

void WonGame(int wordLength)
{
    int i = 0;
    system("cls");
    Header();
    StripesOutline(39,18,40,6,"gray","neon green");
    DrawRectangle(40,19,40,6,"dark gray");
    GoTo(55,21);
    Colour("dark gray","black");
    printf(" GAME OVER");
    GoTo(55,22);
    printf("#You   won#");
    DoubleBorderGrid((120-6*wordLength)/2,35,3,3,1,wordLength,"gray","white");
    Colour("gray","cyan");
    for(i=0; i<wordLength; i++)
    {
        GoTo((120-6*wordLength)/2+6*i+2,37);
        printf("%c",word[i]);
    }
}

int Gameplay(void)
{
    char *constructing = NULL;
    char alphabet[26];
    char letter;
    int missed=6;
    int i=0;
    int k=0;
    int wordLength=0;
    int letterCode = 0;

    DecideWord();
    wordLength=strlen(word);
    constructing =(char*)malloc(sizeof(char)*wordLength);
    memset(constructing,'*',wordLength);
    memset(alphabet,'0',26);
    constructing[wordLength]='\0';

    Header();

    while( missed != 0)
    {
        system("cls");
        Header();
        DoubleBorderGrid((120-6*wordLength)/2,35,3,3,1,wordLength,"gray","white");
        Colour("gray","cyan");
        for(i=0; i<wordLength; i++)
        {
            GoTo((120-6*wordLength)/2+6*i+2,37);
            printf("%c",constructing[i]);
        }
        StripesOutline(39,18,40,6,"gray","white");
        DrawRectangle(40,19,40,6,"cyan");
        GoTo(47,21);
        Colour("cyan","white");
        printf("Remaining wrong guesses: %d",missed);
        GoTo(51,22);
        printf("Enter your guess: ");
        fflush(stdin);
        scanf("%c",&letter);
        letter = toupper(letter);
        letterCode = letter;
        k=0;
        for(i=0; i<wordLength; i++)
        {
            if(word[i] == letter)
            {
                constructing[i]=letter;
                k++;
            }
        }
        if(k == 0 && alphabet[letterCode - 65] == '0')
        {
            missed--;
            alphabet[letterCode - 65] = '1';
        }
        if((strcmp(constructing,word) == 0) && (missed != 0))//the player has won the game
        {
            WonGame(wordLength);
            newGame=NewGame();
            break;
        }
        if(missed == 0)//the player has lost the game
        {
            LostGame(wordLength);
            newGame=NewGame();
        }
    }
    return newGame;
}

void Launcher(void)
{
    system("title http://i-nfiniteloop.blogspot.com Hangman");
    while(newGame != 0)
    {
        Menu();
        system("cls");
        newGame = Gameplay(newGame);
    }
}

int main(void)
{
    Launcher();
    return 0;
}


Screenshots:









Monday 15 October 2012

Checking if a number is prime or not in C

A number is a prime number if it has no positive divisors except for 1 and itself. 

The function below evaluates whether the number received as argument in the function call is a prime number or not.

#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int number = 0, prime = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    prime = Prime(number);
    if (prime == 0)
    {
        printf("\n\t\tThis number is not prime.");
    }
    else if (prime == 1)
    {
        printf("\n\t\tThis number is prime.");
    }
    getch();
    return 0;
} 
Example1: checking if a given number is prime or not
int main(void)
{
    int number = 0, prime = -1;
    printf("\n Enter the number: ");
    scanf("%d",&number);
    prime = Prime(number);
    if (prime == 0)
    {
        printf("\n\t\tThis number is not prime.");
    }
    else if (prime == 1)
    {
        printf("\n\t\tThis number is prime.");
    }
    getch();
    return 0;
} 
Output:  

Example2: displaying the first n prime numbers
#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int n = 0, counter = 0, i = 1, prime = -1;
    printf("\n Enter how many prime numbers to be displayed: ");
    scanf("%d",&n);
    printf("\n\n\tThe first %d prime numbers are: ",n);
    while (counter < n)
    {
        prime = Prime(i);
        if (prime == 1)
        {
            printf("%d ",i);
            counter++;
        }
        i++;
    }
    getch();
    return 0;
}
Output:   

Example3: displaying all the prime numbers in a given range
#include<stdio.h>
#include<conio.h>

int Prime(int number);

int main(void)
{
    int a = 0, b = 0, i = 0, prime = -1, ok = 0;
    printf("\n Enter the minimum range: ");
    scanf("%d",&a);
    printf(" Enter the maximum range: ");
    scanf("%d",&b);
    for (i=a; i<=b; i++)
    {
        prime=Prime(i);
        if (prime == 1)
        {
            if (ok == 0)
            {
                printf("\n\tThe prime numbers in the given range are: ");
            }
            printf("%d ",i);
            ok++;
        }
    }
    if (ok == 0)
    {
        printf("\n\tThere are no prime numbers in the given range.");
    }
    getch();
    return 0;
} 
Output:   

Sunday 14 October 2012

Solving a quadric ecuation in C

This function computes the two roots of a quadric ecuation.

In order to work easily with a complex number, I defined a structure consisting of two doubles, r being for the real part of a complex number and i for the imaginary part.
typedef struct
{
   double r;
   double i;
} double_c;

/*
 * Description:
 *  Finds the two roots of a quadric ecuation
 * Parameters:
 *  a   - the first coefficient of the ecuation
 *  b   - the second coefficient of the ecuation
 *  c   - the third coefficient of the ecuation
 *  root1 - the first root of the ecuation
 *  root2 - the second root of the ecuation
 */
void QuadricEcuation(double a, double b, double c, double_c *root1, double_c *root2)
{
    double discriminant = 0;
    discriminant = b*b-4*a*c;
    if ((discriminant == 0) && (a != 0)) //the roots are equal
    {
        (*root1).r = -b/2*a;
        (*root1).i = 0;
        (*root2).r = (*root1).r;
        (*root2).i = (*root1).i;
    }
    else if ((discriminant > 0) && (a != 0)) //the roots are real numbers
    {
        (*root1).r = (-b+sqrt(discriminant))/(2*a);
        (*root1).i = 0;
        (*root2).r= (-b-sqrt(discriminant))/(2*a);
        (*root2).i = 0;
    }
    else if (a != 0)//the roots are complex numbers
    {
        (*root1).r = -b/(2*a);
        (*root1).i = sqrt(-discriminant)/(2*a);
        (*root2).r = -b/(2*a);
        (*root2).i = -sqrt(-discriminant)/(2*a);
    }
}

Example:

#include<stdio.h>
#include<conio.h>
#include<math.h>

void QuadricEcuation(double a, double b, double c, double_c *root1, double_c *root2);

int main(void)
{
    double a = 0, b = 0, c = 0;
    double_c root1, root2;
    printf("Enter the three coefficients of the quadric ecuation:\n");
    scanf("%lf",&a);
    scanf("%lf",&b);
    scanf("%lf",&c);
    QuadricEcuation(a,b,c,&root1,&root2);
    printf("\t\tThe roots are:\n");
    printf("\t\t\t%.3f+%.3fi and %.3f+%.3fi",root1.r,root1.i,root2.r,root2.i);
    getch();
    return 0;
} 
Output:  

Friday 12 October 2012

Maximum and minimum of three numbers using the ternary operator

Maximum


The following function finds and returns the largest of the three numbers received as arguments in the function call using the ternary operator.
/*
 * Description:
 *  Finds the largest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  maximum - the largest number out of the three
 */
int Maximum(int a, int b, int c)
{
    int maximum = (((a > b) && (a > c)) ? a : (b > c) ? b : c);
    return maximum;
}

Minimum


The following function finds and returns the smallest of the three numbers received as arguments in the function call using the ternary operator.
/*
 * Description:
 *  Finds the smallest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  minimum - the smallest number out of the three
 */
int Minimum(int a, int b, int c)
{
    int minimum = (((a < b) && (a < c)) ? a : (b < c) ? b : c);
    return minimum;
}

Example:

#include<stdio.h>
#include<conio.h>

int Maximum(int a, int b, int c);
int Minimum(int a, int b, int c);

int main(void)
{
    int a = 0, b = 0, c = 0;
    int maximum = 0, minimum = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    printf(" Enter the third number: ");
    scanf("%d",&c);
    maximum = Maximum(a,b,c);
    printf("\n\t\t\tThe largest number is: %d",maximum);
    minimum = Minimum(a,b,c);
    printf("\n\t\t\tThe smallest number is: %d",minimum);
    getch();
    return 0;
} 
Output: 

For more ways to find the maximum and minimum of three numbers, see these two articles: one, two.

Maximum and minimum of three numbers using two IF statements

Maximum


The following function finds and returns the largest of the three numbers received as arguments in the function call using two IF statements.
/*
 * Description:
 *  Finds the largest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  maximum - the largest number out of the three
 */
int Maximum(int a, int b, int c)
{
    int maximum = 0;
    if (a > b) // the first number is larger than the second one
    {
        if (a > c) // the first number is also larger than the third 
            one
        {
            maximum = a;
        }
        else//the first number is smaller than the third one
        {
            maximum = c;
        }
    }
    else//the first number is smaller than the second one
    {
        if (b > c) //the second number is larger than the third one
        {
            maximum = b;
        }
        else//the second number is smaller than the third one
        {
            maximum = c;
        }
    }
    return maximum;
}

Minimum


The following function finds and returns the smallest of the three numbers received as arguments in the function call using two IF statements.
/*
 * Description:
 *  Finds the smallest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  minimum - the smallest number out of the three
 */
int Minimum(int a, int b, int c)
{
    int minimum = 0;
    if (a < b) //the first number is smaller than the second one
    {
        if (a < c) //the first number is also smaller than the third 
            one
        {
            minimum = a;
        }
        else//the first number is larger than the third one
        {
            minimum = c;
        }
    }
    else//the first number is larger than the second one
    {
        if (b < c) //the second number is smaller than the third one
        {
            minimum = b;
        }
        else//the second number is larger than the third one
        {
            minimum = c;
        }
    }
    return minimum;
}

Example:

#include<stdio.h>
#include<conio.h>

int Maximum(int a, int b, int c);
int Minimum(int a, int b, int c);

int main(void)
{
    int a = 0, b = 0, c = 0;
    int maximum = 0, minimum = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    printf(" Enter the third number: ");
    scanf("%d",&c);
    maximum = Maximum(a,b,c);
    printf("\n\t\t\tThe largest number is: %d",maximum);
    minimum = Minimum(a,b,c);
    printf("\n\t\t\tThe smallest number is: %d",minimum);
    getch();
    return 0;
}
Output:


For more ways to find the maximum and minimum of three numbers, see these two articles: one, two.

Maximum and minimum of three numbers using nested IF statements

Maximum

The following function finds and returns the largest of the three numbers received as arguments in the function call using nested IF statements.
/*
 * Description:
 *  Finds the largest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  maximum - the largest number out of the three
 */
int Maximum(int a, int b, int c)
{
    int maximum = 0;
    if (a > b) // the first number is larger than the second one
    {
        if (a > c) // the first number is also larger than the third 
            one
        {
            maximum = a;
        }
        else//the first number is smaller than the third one
        {
            maximum = c;
        }
    }
    else//the first number is smaller than the second one
    {
        if (b > c) //the second number is larger than the third one
        {
            maximum = b;
        }
        else//the second number is smaller than the third one
        {
            maximum = c;
        }
    }
    return maximum;
}

Minimum

The following function finds and returns the smallest of the three numbers received as arguments in the function call using nested IF statements.
/*
 * Description:
 *  Finds the smallest of three numbers using nested if statements
 * Parameters:
 *  a - the first number out of the three
 *  b - the second number out of the three
 *  c - the third number out of the three
 * Returns:
 *  minimum - the smallest number out of the three
 */
int Minimum(int a, int b, int c)
{
    int minimum = 0;
    if (a < b) //the first number is smaller than the second one
    {
        if (a < c) //the first number is also smaller than the third 
            one
        {
            minimum = a;
        }
        else//the first number is larger than the third one
        {
            minimum = c;
        }
    }
    else//the first number is larger than the second one
    {
        if (b < c) //the second number is smaller than the third one
        {
            minimum = b;
        }
        else//the second number is larger than the third one
        {
            minimum = c;
        }
    }
    return minimum;
}

Example:

#include<stdio.h>
#include<conio.h>

int Maximum(int a, int b, int c);
int Minimum(int a, int b, int c);

int main(void)
{
    int a = 0, b = 0, c = 0;
    int maximum = 0, minimum = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    printf(" Enter the third number: ");
    scanf("%d",&c);
    maximum = Maximum(a,b,c);
    printf("\n\t\t\tThe largest number is: %d",maximum);
    minimum = Minimum(a,b,c);
    printf("\n\t\t\tThe smallest number is: %d",minimum);
    getch();
    return 0;
} 
Output:


For more ways to find the maximum and minimum of three numbers, see these two articles: one, two.

Thursday 11 October 2012

Basic MATLAB commands

My previous article was about defining scalar variables and evaluating arithmetical expressions in MATLAB.

Now, we're going to practice that and I will show you some basic commands.

Let's say we want to keep track of what we do in this session. For this, we have the diary command.
>> diary

This function will create a text file named diary that you can open later with any text editor.

If you want to give the file a name of your choise, use
>> diary FileName

(MATLAB automatically colours the file name in magenta).

More information about this command can be found by typing 
>> help diary

To see the current directory, where this file has been saved, use the the cd command.

You can change the current directory by specifing the path between apostrophes.
>>cd 'D:/'

Let's make the following four variables: a=2.5×1023, b=2+3i (i being the imaginary number), c=ej2Ï€/3, d=√36.
>> a=2.5*10^23, b=2+3*i
a =
  2.5000e+023
b =
  2.0000 + 3.0000i

In this case, the e notation is used for a very large number.

Notice that to enter multiple statements at once you can use commas.

For defining the c and d variable, we'll need some help from MATLAB and we'll have to search for the exponential function, for the pi constant and for a function that computes the square root of a number. 
>> lookfor exponential
Lookfor searches in the description of each function for a match, while help searches a function with the exact same name.
>> c=exp(j*2*pi/3); d=sqrt(36)
d =
  6

As you can see, semi-colons also allow placing several statements on one line, but, unlike commas, they will supress the output. 

For a list of the variables in the current workspace type:
>> who
Your variable names are:
a b c d

To see even more details about the variables, including size, class and attributes, use whos.

Remember that at the beginning of this session, you started a diary. Now, since the article is coming to an end, we should stop recording. For this, enter
>> diary off

 To view the diary file use
>> type('FileName')

 To remove all the variables from memory, MATLAB has the clear command.
>> clear

If you want to clear the Command Window, type
>> clc


Wednesday 10 October 2012

Defining vectors in MATLAB. Vector commands and built-in functions in MATLAB

This article will show you how to define and manipulate vectors in MATLAB using built-in functions.

A vector is a special case of a matrix. The elements of a vector must be enclosed in square brackets.

A row vector is a 1xn matrix. The entries of a row vector can be delimited by either spaces or commas. Below you have two vectors defined in both ways.
>> Rvec1=[1 2 3 4 5]
Rvec1 =
     1     2     3     4     5

>> Rvec2=[3.14,15,9,26]
Rvec2 =
     3.1400    15.0000    9.0000     26.0000

A column vector is a nx1 matrix. The components of a column vector are separated by a semi-colon.
>> Cvec1=[1;2;3;4;5]
Cvec1 =
     1
     2
     3
     4
     5

You can easily change the value of a element using MATLAB's indexing commands by typing the following in the command line:
>> Rvec1(1)=10
Rvec1 =
    10    2     3     4      5

As you can see, the first component of the vector has now the value 10.

Accessing multiple elements can be done as follows:
>> Rvec1([1 3 5])
ans =
    10    3    5

The snippet above lets you access the first, third and fifth element of the vector. You can change more than 1 element like this:
>> Rvec1([1 2])=[7 8]
Rvec1 =
    7    8    3    4    5

That has given another value to the first and second element.

Now, let's extract all the entries of the vector from the second to the last. This can be simply done by typing in:
>> Rvec1([2:end])
ans =
     8     3     4     5

If you need a vector with equally spaced elements, this can be easily done using MATLAB's construct star:increment:finish. If you don't mention an increment, it's assumed to be 1.
>> Rvec3=1:10
Rvec3 =
     1    2    3    4    5    6    7    8    9    10

Further, I will be describing some MATLAB built-in functions that you can use when working with vectors.

The number of elements in a vector is known as the length of a vector.
>> length(Rvec1)
ans =
     5

To generate a specific number of points between two given values, use linspace:
>> linspace(1,2,3)
ans =
    1.0000      1.5000      2.0000

For a logarithmically spaced vector, use logspace:
>> logspace(0,1,5)
ans =
    1.0000    1.7783    3.1623    5.6234    10.0000

To initialise a vector having n elements with 0, use zeros.
>> zeros(1,3)
ans =
    0    0    0

There is a similar function that will initialise all the elements of a vector with 1: ones.
>> ones(3,1)
ans =
     1
     1
     1

Next, I will be working only with  Rvec1  and Cvec1 previously defined, so you might want to clear any other variables existing now in the Workspace.
For that, do the following:

>> clear('Rvec2','Rvec3')

You can notice that those two variables have now been deleted from your Workspace.

The  sort command sorts the elements of the vector is ascending or descending order.
>> sort(Rvec1,'ascend')
ans =
    3    4    5    7    8

>> sort(Cvec1,'descend')
ans =
    5
    4
    3
    2
    1

The mode parameter is optional and is assumed by MATLAB to be  ascend if left blank.

To find the largest or the smallest component, use max, respectively min.
>> max(Cvec1)
ans =
     5

>> min(Rvec1)
ans =
     3

To sum all the elements of a vector, MATLAB has a very suggestively named function: sum
>> sum(Rvec1)
ans =
    27

To compute the product of the elements of a vector, use prod:
>> prod(Cvec1)
ans =
   120

Most of the commands can also be used for matrices since a vector is a matrix that has only one row or column. More details and examples about working with matrices will be found in another post.

For the last section of this article, I will be talking briefly about character arrays in MATLAB.

You can create a string by enclosing a sequence of letters/numbers/special characters in single quotation marks. Here's an example:
>> str1='Vintage'
str1 =
Vintage

To convert characters to their ASCII code or to find their numerical equivalent, use unicode2native:
>> str2=unicode2native(str1)
str2 =
     86     105     110     116     97     103     101

To convert a integer vector to characters use native2unicode or the char function:
>> native2unicode(str2)
ans =
Vintage

>> char(str2)
ans =
Vintage

To determine whether the input is a char array or not, use  ischar. This functions will return 1 if the argument is a string and 0 otherwise.
>> ischar(str1)
ans =
     1

To check if a character is a letter, use isletter. This MATLAB function will return 1 if the character is a letter of the alphabet and 0 otherwise.
>> isletter('*')
ans =
     0

The isspace functions behaves similar and is used to verify spaces in a string.

To compare two strings, use one of the following functions: strcmp (determines if the two input strings are identical), strncmp (determines if the first n characters of the strings are identical), strcmpi, strncmpi. The last two ignore case.
>> strcmp(str1,'vintage')
ans =
     0

>> strcmpi(str1,'vintage')
ans =
     1

Also, all the relational operators (==, ~=, >, >=, <, <=) can be used to compare arrays with equal dimensions.

To horizontally concatenate two or more strings, you can use the strcat function.
>> s1=strcat(str1,'Coding')
s1 =
VintageCoding

For a vertical concatenation, MATLAB has the strvcat function that will return a column vector containing string elements.
>> strvcat(str1,'Coding')
ans =
Vintage
Coding

You can search any string for any occurrence of another string by making use of the findstr function. This will return the starting index of each appearance of the shorter string in the longer one. This search is case sensitive. 
>> findstr('i', 'Vintage Coding')
ans =
    2 12

For a search where the order of the input character arrays is important, use strfind.

Remember that for more details about each of these functions, you can see the help MATLAB provides.

For vector operations in MATLAB, see my next article.

Monday 8 October 2012

Case conversion using bitwise operators

For a better understanding of this article, you might want to read first:

Lowercase to uppercase
By looking at the ASCII code chart, you can see that the uppercase letters have values 32 less than the ones of the lowercase letters. This means that to convert a string to uppercase, it is enough to set the sixth bit to 0. 
The C function below changes all the letters of the string received as argument to uppercase characters.
/*
 * Description:
 *  Converts all the letters of a string to uppercase using bitwise operations
 * Parameters:
 *  string - the string to be converted to uppercase
 * Returns:
 *  converted - the string converted to uppercase
 */
char *ToUppercase(char *string)
{
    char *converted = NULL;
    int  i = 0;
    converted = (char*)malloc(sizeof(char) * strlen(string) + 1);
    for(i=0; i<strlen(string); i++)
    {
        if(string[i] >='a' && string[i] <='z')
        {
            converted[i] = (char) (string[i] & 65503);//65 503 (decimal) = 1111 1111 1101 1111 (binary)
        }
        else
        {
            converted[i] = string[i];
        }
    }
    converted[i] = '\0';
    return converted;
}
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

char *ToUppercase(char *string);

int main(void)
{
    char s[] = "VINTAGE CODING";
    char *conv = NULL;
    printf("\n The string before lowercase conversion: %s",s);
    conv = ToLowercase(s);
    printf("\n\n\tThe string after lowercase conversion: %s",conv);
    getch();
    return 0;
}
Output: 

Uppercase to lowercase
For a conversion to lowercase of a string, you have to set the sixth bit to 1. The C function below changes all the letters of the string received as argument to lowercase characters.
/*
 * Description:
 *  Converts all the letters of a string to lowercase using bitwise operations
 * Parameters:
 *  string - the string to be converted to lowercase
 * Returns:
 *  converted - the string converted to lowercase
 */
char *ToLowercase(char *string)
{
    char *converted = NULL;
    int i = 0;
    converted = (char*)malloc(sizeof(char) * strlen(string) + 1);
    for(i=0; i<strlen(string); i++)
    {
        if(string[i] >= 'A' && string[i] <= 'Z')
        {
            converted[i] = (char) (string[i] | 32);//32 (decimal) = 0000 0000 0010 0000 (binary)
        }
        else
        {
            converted[i] = string[i];
        }
    }
    converted[i] = '\0';
    return converted;
}
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

char *ToLowercase(char *string);

int main(void)
{
    char s[] = "VINTAGE CODING";
    char *conv = NULL;
    printf("\n The string before lowercase conversion: %s",s);
    conv = ToLowercase(s);
    printf("\n\n\tThe string after lowercase conversion: %s",conv);
    getch();
    return 0;
}
Output:  

Binary to decimal and decimal to binary base conversion using bitwise operators in C

The six operators that C provides are shown in the table below:
Operator
Action
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR (XOR)
<< 
Shift left
>> 
Shift right
~
One's complement (NOT)
The bitwise AND, OR and NOT have the same truth tables as their logical equivalents, except that they work bit by bit. The outcome of an XOR operation is true if only one of the operands is true and false otherwise.
The bit-shift operators << and >> move all the bits of the variable to the left or right, as specified, the number of positions shifted being given by the right operand, which must be a positive integer. A shift is not a rotate, so the bits shifted do not come back at the other end, but are lost.
Bitwise operations may be applied only to integral operands like the standard char, short, int, and long data types, signed or unsigned.

For the truth table of the logical operators, read this article: 
Printing the truth table of the logical operators in C#                                  

Decimal to binary radix conversion
The following C function converts an integer from base 10 to binary. The first element of the bin array represents the sign bit.
#define MAX 17

/*
 * Description:
 *  Converts an integer from base 10 to base 2
 * Parameters:
 *  dec - the integer to be converted
 *  bin - pointer to the array that will contain the integer converted in binary
 * Returns:
 *  bin - array containing the binary equivalent of the integer to be converted
 */
int *DecimalToBinary(int dec, int *bin)
{
    int i = MAX;
    if(dec < 0)
    {
        dec = -dec;
        bin[0] = 1;
    }
    else
    {
        bin[0] = 0;
    }
    for(; i>=0; i--)
    {
        bin[MAX-i+1] = (dec>>i) & 1;
    }
    return bin;
}
Example:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(void)
{
    int dec = 0, *bin = NULL, i = 0;
    bin = (int*)malloc(sizeof(int)*MAX);
    printf("\n Enter the number in decimal: ");
    scanf("%d",&dec);
    printf("\n\tThe number in binary: ");
    if(dec >= -100)
    {
        bin = DecimalToBinary(dec,bin);
        for(; bin[i] == 0 || bin[i] == 1; i++)
        {
            printf("%d",bin[i]);
        }
    }
    getch();
    return 0;
}
Output:


Binary to decimal radix conversion
The following C function converts an integer from base 2 to decimal. The first element of the bin array represents the sign bit.
#define MAX 17

/*
 * Description:
 *  Converts an integer from base 2 to base 10
 * Parameters:
 *  bin - array containing the integer in binary
 * Returns:
 *  decimal - the equivalent integer in base 10
 */
int BinaryToDecimal(int bin[])
{
    int i = 1, decimal = 0;
    for(; bin[i] == 0 || bin[i] == 1; i++)
    {
        decimal = (decimal<<1) | bin[i];
    }
    if(bin[0] == 1)
    {
        decimal = -decimal;
    }
    return decimal;
}
Example:
#include<stdio.h>
#include<conio.h>

int BinaryToDecimal(int bin[]);

int main(void)
{
    int bin[MAX], dec = 0, b = 0, i = 0;
    printf("\n Enter the number in binary (to stop reading, enter a number other than 0 or 1:\n");
    do
    {
        scanf("%d",&b);
        if(b == 0 || b == 1)
        {
            bin[i++] = b;
        }
    }while(b == 0 || b == 1);
    dec = BinaryToDecimal(bin);
    printf("\n\tThe number in decimal is: %d",dec);
    getch();
    return 0;
}
Output: