Sunday, August 19, 2012

Integer Rounding in ANSI C

1.Unsigned Integers

When two unsigned integers are divided, the result will be rounded down.
result = numerator / denominator;
To round up a result you must apply the following idiom:
result = (numerator + denominator - 1) / denominator;
Example:
#include<stdio.h>

int main(void)
{
    unsigned int numerator   = 50;
    unsigned int denominator = 25;
    unsigned int upResult;
    unsigned int downResult;
    double fResult;
    int i;

    for(i = 0; i < 25; i++)
    {
        fResult = (double)(numerator)/(double)(denominator);
        upResult = (numerator + denominator - 1)/denominator;
        downResult = numerator/denominator;
        printf("Numerator %3u||Denominator %3u||Result %3.2f||"
               "Round up %3u||Round down %3u\n",
               numerator, denominator, fResult, upResult, downResult);
        numerator++;
    }
    return 0;
}
/*Output:
Numerator  50||Denominator  25||Result 2.00||Round up   2||Round down   2
Numerator  51||Denominator  25||Result 2.04||Round up   3||Round down   2
Numerator  52||Denominator  25||Result 2.08||Round up   3||Round down   2
Numerator  53||Denominator  25||Result 2.12||Round up   3||Round down   2
Numerator  54||Denominator  25||Result 2.16||Round up   3||Round down   2
Numerator  55||Denominator  25||Result 2.20||Round up   3||Round down   2
Numerator  56||Denominator  25||Result 2.24||Round up   3||Round down   2
Numerator  57||Denominator  25||Result 2.28||Round up   3||Round down   2
Numerator  58||Denominator  25||Result 2.32||Round up   3||Round down   2
Numerator  59||Denominator  25||Result 2.36||Round up   3||Round down   2
Numerator  60||Denominator  25||Result 2.40||Round up   3||Round down   2
Numerator  61||Denominator  25||Result 2.44||Round up   3||Round down   2
Numerator  62||Denominator  25||Result 2.48||Round up   3||Round down   2
Numerator  63||Denominator  25||Result 2.52||Round up   3||Round down   2
Numerator  64||Denominator  25||Result 2.56||Round up   3||Round down   2
Numerator  65||Denominator  25||Result 2.60||Round up   3||Round down   2
Numerator  66||Denominator  25||Result 2.64||Round up   3||Round down   2
Numerator  67||Denominator  25||Result 2.68||Round up   3||Round down   2
Numerator  68||Denominator  25||Result 2.72||Round up   3||Round down   2
Numerator  69||Denominator  25||Result 2.76||Round up   3||Round down   2
Numerator  70||Denominator  25||Result 2.80||Round up   3||Round down   2
Numerator  71||Denominator  25||Result 2.84||Round up   3||Round down   2
Numerator  72||Denominator  25||Result 2.88||Round up   3||Round down   2
Numerator  73||Denominator  25||Result 2.92||Round up   3||Round down   2
Numerator  74||Denominator  25||Result 2.96||Round up   3||Round down   2
*/
To round to the nearest integer you have 2 methods:
Method 1:
iResult1 = (unsigned int) ( (double)(numerator) / (double)(denominator) + 0.5);
Method 2:
iResult2 = (numerator + denominator / 2) / denominator;
Observation: The second method is preferred to the first method because is faster and doesn't use floating-point division.  Also, this method is preferred if you work with embedded systems.

Example:
#include<stdio.h>

int main(void)
{
    unsigned int numerator   = 50;
    unsigned int denominator = 25;
    unsigned int iResult1;
    unsigned int iResult2;
    double fResult;
    int i;

    for(i = 0; i < 25; i++)
    {
        fResult = (double)(numerator)/(double)(denominator);
        iResult1 = (int) ( (double)(numerator) / (double)(denominator) + 0.5);
        iResult2 = (numerator + denominator/2) / denominator;
        printf("Numerator %3u||Denominator %3u||Result %3.2f||"
               "Nearest_1 %3u||Nearest_2 %3u\n",
               numerator, denominator, fResult, iResult1, iResult2);
        numerator++;
    }
    return 0;
}
/*Output:
Numerator  50||Denominator  25||Result 2.00||Nearest_1   2||Nearest_2   2
Numerator  51||Denominator  25||Result 2.04||Nearest_1   2||Nearest_2   2
Numerator  52||Denominator  25||Result 2.08||Nearest_1   2||Nearest_2   2
Numerator  53||Denominator  25||Result 2.12||Nearest_1   2||Nearest_2   2
Numerator  54||Denominator  25||Result 2.16||Nearest_1   2||Nearest_2   2
Numerator  55||Denominator  25||Result 2.20||Nearest_1   2||Nearest_2   2
Numerator  56||Denominator  25||Result 2.24||Nearest_1   2||Nearest_2   2
Numerator  57||Denominator  25||Result 2.28||Nearest_1   2||Nearest_2   2
Numerator  58||Denominator  25||Result 2.32||Nearest_1   2||Nearest_2   2
Numerator  59||Denominator  25||Result 2.36||Nearest_1   2||Nearest_2   2
Numerator  60||Denominator  25||Result 2.40||Nearest_1   2||Nearest_2   2
Numerator  61||Denominator  25||Result 2.44||Nearest_1   2||Nearest_2   2
Numerator  62||Denominator  25||Result 2.48||Nearest_1   2||Nearest_2   2
Numerator  63||Denominator  25||Result 2.52||Nearest_1   3||Nearest_2   3
Numerator  64||Denominator  25||Result 2.56||Nearest_1   3||Nearest_2   3
Numerator  65||Denominator  25||Result 2.60||Nearest_1   3||Nearest_2   3
Numerator  66||Denominator  25||Result 2.64||Nearest_1   3||Nearest_2   3
Numerator  67||Denominator  25||Result 2.68||Nearest_1   3||Nearest_2   3
Numerator  68||Denominator  25||Result 2.72||Nearest_1   3||Nearest_2   3
Numerator  69||Denominator  25||Result 2.76||Nearest_1   3||Nearest_2   3
Numerator  70||Denominator  25||Result 2.80||Nearest_1   3||Nearest_2   3
Numerator  71||Denominator  25||Result 2.84||Nearest_1   3||Nearest_2   3
Numerator  72||Denominator  25||Result 2.88||Nearest_1   3||Nearest_2   3
Numerator  73||Denominator  25||Result 2.92||Nearest_1   3||Nearest_2   3
Numerator  74||Denominator  25||Result 2.96||Nearest_1   3||Nearest_2   3
*/
2.Signed Integers

The formulas described above cannot apply to signed integers when the denominator and numerator are of different signs (one is positive and the other one is negative or vice-versa). For computing the nearest integer after division you can use the following functions:
/*
 * Description:
 *  Returns the rounded result of the division
 * Parameters:
 *  numerator - the numerator
 *  denominator - the denominator
 * Returns:
 *  The nearest integer of the result
 */
int Round_Division1(int numerator, int denominator)
{
    int result;

    if( ( (numerator > 0) && (denominator < 0) ) ||
        ( (numerator < 0) && (denominator > 0) ) )
    {
        result = (int) ( (double)(numerator) / (double)(denominator) + 0.5);
    }
    else
    {
        result = (int) ( (double)(numerator) / (double)(denominator) - 0.5);
    }
    return result;
}
/*
 * Description:
 *  Returns the rounded result of the division
 * Parameters:
 *  numerator - the numerator
 *  denominator - the denominator
 * Returns:
 *  The nearest integer of the result
 */
int Round_Division2(int numerator, int denominator)
{
    int result;

    if( ( (numerator > 0) && (denominator < 0) ) ||
        ( (numerator < 0) && (denominator > 0) ) )
    {
        result = ( numerator - (denominator/2) ) / denominator;
    }
    else
    {
        result = ( numerator + (denominator/2 )) / denominator;
    }
    return result;
}
Example:
#include<stdio.h>

int Round_Division1(int numerator, int denominator);
int Round_Division2(int numerator, int denominator);

int main(void)
{
    int numerator   = -50;
    int denominator = 25;
    int iResult1;
    int iResult2;
    double fResult;
    int i;

    for(i = 0; i < 25; i++)
    {
        fResult = (double)(numerator)/(double)(denominator);
        iResult1 = Round_Division1(numerator,denominator);
        iResult2 = Round_Division2(numerator,denominator);
        printf("Numerator %3d||Denominator %3d||Result %3.2f||"
                "Nearest_1 %3d||Nearest_2 %3d\n",
                numerator, denominator, fResult, iResult1, iResult2);
        numerator++;
    }
    return 0;
}
/*Output:
Numerator -50||Denominator  25||Result -2.00||Nearest_1  -2||Nearest_2  -2
Numerator -49||Denominator  25||Result -1.96||Nearest_1  -2||Nearest_2  -2
Numerator -48||Denominator  25||Result -1.92||Nearest_1  -2||Nearest_2  -2
Numerator -47||Denominator  25||Result -1.88||Nearest_1  -2||Nearest_2  -2
Numerator -46||Denominator  25||Result -1.84||Nearest_1  -2||Nearest_2  -2
Numerator -45||Denominator  25||Result -1.80||Nearest_1  -2||Nearest_2  -2
Numerator -44||Denominator  25||Result -1.76||Nearest_1  -2||Nearest_2  -2
Numerator -43||Denominator  25||Result -1.72||Nearest_1  -2||Nearest_2  -2
Numerator -42||Denominator  25||Result -1.68||Nearest_1  -2||Nearest_2  -2
Numerator -41||Denominator  25||Result -1.64||Nearest_1  -2||Nearest_2  -2
Numerator -40||Denominator  25||Result -1.60||Nearest_1  -2||Nearest_2  -2
Numerator -39||Denominator  25||Result -1.56||Nearest_1  -2||Nearest_2  -2
Numerator -38||Denominator  25||Result -1.52||Nearest_1  -2||Nearest_2  -2
Numerator -37||Denominator  25||Result -1.48||Nearest_1  -1||Nearest_2  -1
Numerator -36||Denominator  25||Result -1.44||Nearest_1  -1||Nearest_2  -1
Numerator -35||Denominator  25||Result -1.40||Nearest_1  -1||Nearest_2  -1
Numerator -34||Denominator  25||Result -1.36||Nearest_1  -1||Nearest_2  -1
Numerator -33||Denominator  25||Result -1.32||Nearest_1  -1||Nearest_2  -1
Numerator -32||Denominator  25||Result -1.28||Nearest_1  -1||Nearest_2  -1
Numerator -31||Denominator  25||Result -1.24||Nearest_1  -1||Nearest_2  -1
Numerator -30||Denominator  25||Result -1.20||Nearest_1  -1||Nearest_2  -1
Numerator -29||Denominator  25||Result -1.16||Nearest_1  -1||Nearest_2  -1
Numerator -28||Denominator  25||Result -1.12||Nearest_1  -1||Nearest_2  -1
Numerator -27||Denominator  25||Result -1.08||Nearest_1  -1||Nearest_2  -1
Numerator -26||Denominator  25||Result -1.04||Nearest_1  -1||Nearest_2  -1
*/

Creating a MessageBox / Message Dialog in Java Swing

To create a dialog in Swing, you will need to use the JOptionPane class.

If you want to trigger a message dialog, you will need to use the static method:
showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)

1.The Parent Component

Defines the component (usually a JFrame or a JPanel) that will be the parent of the dialog. The coordinates of the parent will be used for the placement of the dialog box (usually the dialog box will to the middle of the component). If this parameter is null the dialog will pop-up in the center of the screen.

Frame Parent example:
package javaexample;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DialogExample
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Sample frame");
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JOptionPane.showMessageDialog(frame, "Sample dialog box");
    }
}
The dialog box will pop-up in the center of the frame
Null Parent example:
package javaexample;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class DialogExample
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Sample frame");
        frame.setSize(400, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JOptionPane.showMessageDialog(null, "Sample dialog box");
    }
}
If the parentComponent parameter is null, the dialog box will pop-up to the center of the screen.
2.The Message

The message is  usually a string constant and represents the text contained in the body.

If message is an array, it will be interpreted as a series of messages (the interpretation is recursive - each object will be interpreted according to its type).  If message is a component, the component will be displayed in the dialog.

Message example:
package javaexample;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class DialogExample
{
    public static void main(String[] args)
    {
        Object[] objects = {UIManager.getIcon("OptionPane.questionIcon"),
                            "This", 
                            "is", 
                            "the", 
                            "new", 
                            new JButton("Hit")};
        JOptionPane.showMessageDialog(null, objects, 
                                     "This is the title",
                                      JOptionPane.PLAIN_MESSAGE);
    }
}
Message Example
3.The Message Type

The messageType defines the style of message. The available options are:
ERROR_MESSAGE
INFORMATION_MESSAGE
WARNING_MESSAGE
QUESTION_MESSAGE
PLAIN_MESSAGE

Message example:
package javaexample;

import javax.swing.JOptionPane;

public class DialogExample
{
    public static void main(String[] args)
    {
        new Thread()
        {
            @Override
            public void run()
            {
                JOptionPane.showMessageDialog(null, "Error message", 
                                              "This is the title",
                                              JOptionPane.ERROR_MESSAGE);
            }
        }.start();
        new Thread()
        {
            @Override
            public void run()
            {
                JOptionPane.showMessageDialog(null, "Information message", 
                                              "This is the title",
                                              JOptionPane.INFORMATION_MESSAGE);
            }
        }.start();
        new Thread()
        {
            @Override
            public void run()
            {
                JOptionPane.showMessageDialog(null, "Warning message", 
                                              "This is the title",
                                              JOptionPane.WARNING_MESSAGE);
            }
        }.start();
        new Thread()
        {
            @Override
            public void run()
            {
                JOptionPane.showMessageDialog(null, "Question message", 
                                              "This is the title",
                                              JOptionPane.QUESTION_MESSAGE);
            }
        }.start();
        new Thread()
        {
            @Override
            public void run()
            {
                JOptionPane.showMessageDialog(null, "Plain message", 
                                              "This is the title",
                                              JOptionPane.PLAIN_MESSAGE);
            }
        }.start();
    }
}
The program above will generate 5 message dialogs
4.The Icon

You can place a decorative icon in the dialog box. Usually a default value is determined by the messageType parameter.
package javaexample;

import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class DialogExample
{
    public static void main(String[] args)
    {
        JOptionPane.showMessageDialog(null, "This is the text body", 
                                     "This is the title",
                                      JOptionPane.PLAIN_MESSAGE,
                                      UIManager.getIcon("Tree.collapsedIcon"));
    }
}
Icon example

Installing and Configuring JavaDoc for Netbeans in Ubuntu

If you encounter such an error, you probably don't have JavaDoc installed or you don't have it configured correctly.
The JavaDoc error
1.Installing JavaDoc

You can install it using command-line or a package manager.

To install it command-line open a terminal and type:
sudo apt-get install openjdk-6-doc
If you want to install it using Ubuntu Software Center, open it and search for openjdk-6-doc and press install:
Installing JavaDoc using the Ubuntu Software Center
2. Configuring JavaDoc

If the previous step didn't solve your problem, open Netbeans and:
1)Open Tools -> Java Platform
2)Go to the JavaDoc tab and add the following path /usr/lib/jvm/default-java/docs
Adding the JavaDoc path
Now when you select a Java method you should its documentation:
Seeing the JavaDoc

Saturday, August 18, 2012

Removing Shortcuts From the Gnome Applications Menu Manually

If you installed a program without using the Ubuntu Software Center and there is no uninstaller (or you just deleted the folder), the shortcut to your removed application may still remain in the Application Menu.

If you try to remove it using Alacarte, you may be surprised to see that your shortcut doesn't appear there. If you find it in Alacarte, read this.

This happened to me when I accidentally deleted the Netbeans folder. The shortcut to Netbeans remained in the Gnome Application menu, but it didn't appear in Alacarte.

After searching a while for a solution, I finally found it - shortcuts that do not appear in Alacarte can be found at:
/home/yourUsername/.local/share/applications/

Your shortcuts will look like:
/home/dystopiancode/.local/share/applications/netbeans-7.1.2.desktop

So, if delete them here, they will disappear from the Gnome Application menu.

Friday, August 17, 2012

Euclid's GCD Algorithm in ANSI C

In mathematics, Euclid's algorithm is a simple yet efficient method for computing the greatest common divisor of two positive integers.

There are 3 possible implementation for Euclid's algorithm:
1. Division-Based Euclid
/*
 * Description:
 *  Returns the greatest common denominator of a and b using the
 *  Euclid's algorithm division-based.
 * Parameters:
 *  a,b - two positive integers
 * Returns:
 *  the greatest common denominator
 */
int Euclid_Gcd_Division(int a, int b)
{
    int temp;
    while(b!=0)
    {
        temp = b;
        b = a % b;
        a = temp;
    }
    return abs(a);
}
Here's numeric example on how the algorithm works:
Phase a b temp
Initialization 32 15 Undefined
Step 1 15 2 15
Step 2 2 1 2
Step 3 1 0 1
In Step 3, b becomes equal to 0 and the while loop is exited. The result will be the content of a.

2.Subtraction-based Euclid
/*
 * Description:
 *  Returns the greatest common denominator of a and b using the
 *  Euclid's algorithm subtraction-based.
 * Parameters:
 *  a,b - two positive integers
 * Returns:
 *  the greatest common denominator
 */
int Euclid_Gcd_Subtraction(int a, int b)
{
    a = abs(a);
    b = abs(b);
    if (a != 0)
    {
        while (b != 0)
        {
            if (a > b)
            {
                a = a - b;
            }
            else
            {
                b = b - a;
            }
        }
    }
    return a;
}
Here's a numeric example on how the algorithm works:
Phase a b Observation
Input -32 15
Initialization 32 15 a>b
Step 1 17 15 a>b
Step 2 2 15 a<b
Step 3 2 13 a<b
Step 4 2 11 a<b
Step 5 2 9 a<b
Step 6 2 7 a<b
Step 7 2 5 a<b
Step 8 2 3 a<b
Step 9 2 1 a>b
Step 10 1 1 a>b
Step 11 1 0 b>=a (else branch)
In Step 11, b becomes equal to 0 and the while loop is exited. The result will be the content of a.

3.Recursion-based Euclid
/*
 * Description:
 *  Returns the greatest common denominator of a and b using the
 *  Euclid's algorithm recursion-based.
 * Parameters:
 *  a,b - two positive integers
 * Returns:
 *  the greatest common denominator
 */
int Euclid_Gcd_Recursion(int a, int b)
{
    int result;
    if (b == 0)
    {
        result = a;
    }
    else
    {
        result = Euclid_Gcd_Recursion(b, a % b);
    }
    return abs(result);
}
The algorithm is the same as the division-based Euclid algorithm. The difference is that this is algorithm is recursive, while the division-based Euclid is iterative.
4.Example
#include<stdio.h>
#include<stdlib.h>

int Euclid_Gcd_Division(int a, int b);
int Euclid_Gcd_Subtraction(int a, int b);
int Euclid_Gcd_Recursion(int a, int b);

int main(void)
{
    int a = 580;
    int b = -320;
    printf("Euclid division based   : %d\n"
           "Euclid subtraction based: %d\n"
           "Euclid recursion based  : %d\n",
            Euclid_Gcd_Division(a,b),
            Euclid_Gcd_Subtraction(a,b),
            Euclid_Gcd_Recursion(a,b));
    return 0;
}

Generic Bitcount Algorithm in ANSI C

The purpose of the Bitcount algorithm is to return the number of bits set to 1 in a memory block.

A simple implementation of the Bitcount algorithm would be:
/*
 * Description:
 *  The function returns the number of bits set the 1 in a integer
 * Parameters:
 *  data - the integer who will be verified
 * Returns:
 *  The number of bits set to 1
 */
int SimpleBitCount(unsigned long data)
{
    /*Calculates the number of bits in a unsigned integer*/
    int size = sizeof(data) * 8;
    int counter = 0;
    /*Sets the first bit of the mask*/
    unsigned long mask = 0x0001U;
    int i;
    for(i = 0; i < size; i++)
    {
        /*Checks if an 1 was encountered*/
        if( (mask & data) !=0)
        {
            counter++;
        }
        /*Sets the next bit of the mask, clears the bit before*/
        mask<<=1;
    }
    return counter;
}
The main disadvantage of this implementation is that the data must be a integer or convertible to an integer.
Example:
#include<stdio.h>

int SimpleBitCount(unsigned long data);

int main(void)
{
    unsigned long v1 = 1539;

    long v1_ones   = SimpleBitCount(v1);
    long v1_zeroes = (sizeof(unsigned long)*8) - v1_ones;

    printf("Size %d bits\nOnes: %ld bits\nZeroes: %ld bits",
            sizeof(unsigned long)*8, v1_ones, v1_zeroes);

    return 0;
}
/*Output:
Size 32 bits
Ones: 4 bits
Zeroes: 28 bits
 */
To eliminate the the disadvantage mentioned before we need to make the sent data generic using a void pointer. Since, we couldn't possibly know the size of the sent data we must send the size of the data as a parameter.
/*
 * Description:
 *  The function returns the number of bits set the 1 in a memory block
 * Parameters:
 *  data - a generic pointer to the memory block
 *  bytes - the size of the memory block in bytes
 * Returns:
 *  The number of bits set to 1 in the memory block
 */
long GenericBitCount(void* data, size_t bytes)
{
    unsigned char* iterator = NULL;
    unsigned char  mask;
    unsigned int i, j;
    long counter = 0;

    /*Positions the iterator at the beginning of the memory block*/
    iterator = data;
    /*Iterates through all the bytes in the memory block*/
    for (i = 0; i < bytes; i++)
    {
        /*Reinitializes the mask for checking the first bit*/
        mask = 1;
        /*Iterates through all the bits of a byte from the memory block*/
        for (j = 0; j < 8; j++)
        {
            /*Checks if an 1 was encountered*/
            if ( ( (*iterator) & mask ) !=0 )
            {
                counter++;
            }
            /*Modifies the mask so the next bit from the byte can be checked*/
            mask <<= 1;
        }
        /*Moves the the next byte*/
        iterator = iterator + 1;
    }
    return counter;
}
Example:
#include<stdio.h>
#include<string.h>

typedef struct
{
    char firstByte;
    char secondByte;
}SampleStruct;

long GenericBitCount(void* data, size_t bytes);

int main(void)
{
    unsigned long v1 = 1539;
    char v2[] = "The bird is the word";
    SampleStruct v3 = {0xFF, 0xFF};

    long v1_ones   = GenericBitCount(&v1,sizeof(unsigned long));
    long v1_zeroes = (sizeof(unsigned long)*8) - v1_ones;

    long v2_ones   = GenericBitCount(&v2,sizeof(char) * strlen(v2));
    long v2_zeroes = (sizeof(char) * strlen(v2)*8) - v2_ones;

    long v3_ones   = GenericBitCount(&v3,sizeof(SampleStruct));
    long v3_zeroes = (sizeof(SampleStruct)) * 8 - v3_ones;

    printf("v1 : Size %5d bits Ones: %5ld bits Zeroes: %5ld bits\n"
           "v2 : Size %5d bits Ones: %5ld bits Zeroes: %5ld bits\n"
           "v3 : Size %5d bits Ones: %5ld bits Zeroes: %5ld bits\n",
           sizeof(unsigned long)*8, v1_ones, v1_zeroes,
           sizeof(char)*strlen(v2)*8, v2_ones, v2_zeroes,
           sizeof(SampleStruct)*8, v3_ones, v3_zeroes );

    return 0;
}
/*Output:
v1 : Size    32 bits Ones:     4 bits Zeroes:    28 bits
v2 : Size   160 bits Ones:    67 bits Zeroes:    93 bits
v3 : Size    16 bits Ones:    16 bits Zeroes:     0 bits
 */
As you observed in the example above, the generic bitcount algorithm can any type of data as opposite to the simple bitcount algorithm who can only work with integers.

Using Enumerations in ANSI C

In ANSI C, a enumeration is a collection of integer constants which share something in common.  The enumeration is somewhat of an analogy to a set. Also, enumerations are a better alternative than a group of macrodefinitions.

They can be declared as:
#include<stdio.h>

enum Color
{
   RED ,
   GREEN ,
   BLUE ,
};

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output:
RED = 0
GREEN = 1
BLUE = 2
*/
The constant RED will be initialized by default with 0, GREEN will be initialized with RED+1 (1) and BLUE will be initialized with (GREEN+1).
Using macrodefinitions, the program above would've looked like this:
#include<stdio.h>

#define RED   0
#define GREEN 1
#define BLUE  2

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output:
RED = 0
GREEN = 1
BLUE = 2
*/
Alternatively, if you initialize the enumeration in this way:
#include<stdio.h>

enum Color
{
   RED = 5,
   GREEN,
   BLUE,
};

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output:
RED = 5
GREEN = 6
BLUE = 7
*/
The constant RED will be initialized with 5, GREEN will be initialized with RED+1 (6)  and BLUE will be initialized with GREEN+1 (7).
TIPYou can can also initialize all members of the enumeration with non-default values:
#include<stdio.h>

enum Color
{
   RED = 5,
   GREEN = 7,
   BLUE = 3,
};

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output:
RED = 5
GREEN = 7
BLUE = 3
*/
TIPIf you don't initialize the first member of the enumeration, he will be equal to 0 by default even if you initialize other members:
#include<stdio.h>

enum Color
{
   RED ,
   GREEN ,
   BLUE =7,
};

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output:
RED = 0
GREEN = 1
BLUE = 7
*/
If you want to declare a Color variable you will have to put the keyword enum in front of it:
#include<stdio.h>

enum Color
{
   RED ,
   GREEN ,
   BLUE =7,
};

int main(void)
{
   enum Color myColor = RED;
   switch(myColor)
   {
      case RED:
           puts("My color is red");
           break;
      case GREEN:
           puts("My color is green");
           break;
      case BLUE:
           puts("My color is blue");
           break;
   }
   return 0;
}
/*Output:
My color is red
*/
Alternatively, if you want a shorter declaration you could use typedef:
#include<stdio.h>

enum Color
{
   RED ,
   GREEN ,
   BLUE =7,
};

typedef enum Color eColor;

int main(void)
{
   eColor myColor = RED;
   switch(myColor)
   {
      case RED:
           puts("My color is red");
           break;
      case GREEN:
           puts("My color is green");
           break;
      case BLUE:
           puts("My color is blue");
           break;
   }
   return 0;
}
/*Output:
My color is red
*/
TIPA shorter version of the declaration above is:
#include<stdio.h>

typedef enum
{
   RED ,
   GREEN ,
   BLUE =7,
}eColor;

int main(void)
{
   eColor myColor = RED;
   switch(myColor)
   {
      case RED:
           puts("My color is red");
           break;
      case GREEN:
           puts("My color is green");
           break;
      case BLUE:
           puts("My color is blue");
           break;
   }
   return 0;
}
/*Output:
My color is red
*/
TIPAlso, multiple members of an enumeration can have the same constant value:
#include<stdio.h>

typedef enum
{
   RED    = 0,
   GREEN  = 1,
   BLUE    =1,
}eColor;

int main(void)
{
   puts("This WILL NOT trigger an error");
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output
This WILL NOT trigger an error
RED = 0
GREEN = 1
BLUE = 1
*/
TIPA debugger may be able to print values of enumeration variables in their symbolic form.

PITFALLA common error that you may encounter while working with enumeration is the enumerator redeclaration as in the example below.
#include<stdio.h>

typedef enum
{
   RED    = 0,
   GREEN  = 1,
   BLUE    =1,
}CarColor;

typedef enum
{
    RED,        //RED is redeclarated
    YELLOW,
    MAGENDA
}WallColor;

int main(void)
{
   puts("This WILL NOT trigger an error");
   printf("RED = %d\nGREEN = %d\nBLUE = %d",RED,GREEN,BLUE);
   return 0;
}
/*Output
../main.c:20:5: error: redeclaration of enumerator ‘RED’
*/
TIPThe easiest way to solve such an issue is to adopt the following notation for enumerators: EnumName_EnumeratorDescription.
#include<stdio.h>

typedef enum
{
   CARCOLOR_RED    = 0,
   CARCOLOR_GREEN  = 1,
   CARCOLOR_BLUE   = 1,
}CarColor;

typedef enum
{
   WALLCOLOR_RED,        
   WALLCOLOR_YELLOW,
   WALLCOLOR_MAGENTA
}WallColor;

int main(void)
{
   printf("RED = %d\nGREEN = %d\nBLUE = %d",
           CARCOLOR_RED,CARCOLOR_GREEN,CARCOLOR_BLUE);
   return 0;
}
/*Output
RED = 0
GREEN = 1
BLUE = 1
*/
In conclusion, enumerations provide a convenient way to associate constant values with names as a more elegant alternative to multiple #define.

Question: What other pitfalls regarding enums do you know?

References:
http://tigcc.ticalc.org/doc/keywords.html#enum
http://en.wikipedia.org/wiki/Enumerated_type#C_and_syntactically_similar_languages
http://cplus.about.com/od/introductiontoprogramming/p/enumeration.htm
http://msdn.microsoft.com/en-us/library/whbyts4t.aspx

Wednesday, August 15, 2012

Basic Pointer Operations in ANSI C

Pointers are variables that hold a memory address. Usually that memory address is the first memory address of another variable or a dynamically allocated block. The type of the pointer indicates to what kind of variable it points to.
Example:
    /*A pointer to a int variable*/
    int   *myPointer;
    /*A pointer to a char variable*/
    char  *myCharPointer;
    /*A pointer to a double variable*/
    double *myDoublePointer;
    /*A pointer to a time_t struct*/
    time_t *myTime_tPointer;
Observation:
The size of a pointer is not correlated with the type of the pointer. All pointers have the same size and that size depends on your platform (more exactly your memory space). So, if your memory space is [0x00000000, 0xFFFFFFFF], the size of your pointers will be 4 bytes.
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    /*A pointer to a int variable*/
    int   *myPointer;
    /*A pointer to a char variable*/
    char  *myCharPointer;
    /*A pointer to a double variable*/
    double *myDoublePointer;
    /*A pointer to a time_t struct*/
    time_t *myTime_tPointer;

    printf("Size of an int pointer     : %d\n"
           "Size of an char pointer    : %d\n"
           "Size of an double pointer  : %d\n"
           "Size of an time_t pointer  : %d\n",
           sizeof(myPointer),
           sizeof(myCharPointer),
           sizeof(myDoublePointer),
           sizeof(myTime_tPointer));

    return 0;
}
/*Output:
Size of an int pointer     : 4
Size of an char pointer    : 4
Size of an double pointer  : 4
Size of an time_t pointer  : 4
 */
The main pointer operations are referencing and dereferencing and both have operators in ANSI C.

The referencing operator & is used for retrieving the memory address of a non-pointer variable, while the dereferencing operator * is used for retrieving the value that a pointer points to. 
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    int myVariable = 3;
    int anotherVariable;
    /*A pointer is usually initialized to NULL. This means
     that pointer will not point to anything for now*/
    int *myPointer = NULL;

    /*This operation is called referencing. This means that the
    pointer will now point to the value of myVariable*/
    myPointer = &myVariable;

    /*This operation is called dereferencing. This means that
    a variable will take the value of the pointer*/
    anotherVariable = *myPointer;

    printf("The value of myVariable       : %d\n"
           "The address of myVariable     : %p\n"
           "The value of myPointer        : %d\n"
           "The address of myPointer      : %p\n"
           "The value of another variable : %d\n"
           "The address of anotherVariable: %p\n",
           myVariable,
           &myVariable,
           *myPointer,
           myPointer,
           anotherVariable,
           &anotherVariable);
    return 0;
}
/*Output:
The value of myVariable       : 3
The address of myVariable     : 0xbfb5e874
The value of myPointer        : 3
The address of myPointer      : 0xbfb5e874
The value of another variable : 3
The address of anotherVariable: 0xbfb5e878
 */
Observation: If not initialized with NULL or a valid memory address, a pointer will point to a random address. If you will try to access it, you may trigger a segmentation fault and your program will crash.

Assuming we have a variable v and a pointer p, we can establish empirically the following equivalencies:
v is the same as *p (Both indicate a value)
&v is the same as p (Both indicate to a memory address)
Going back to the example with the size of the pointers, we can now use the dereferencing to indicate the size of the types that the pointer points to:
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    /*A pointer to a int variable*/
    int   *myPointer;
    /*A pointer to a char variable*/
    char  *myCharPointer;
    /*A pointer to a double variable*/
    double *myDoublePointer;
    /*A pointer to a time_t struct*/
    time_t *myTime_tPointer;

    printf("Size of myPointer's type        : %d\n"
            "Size of myCharPointer's type    : %d\n"
            "Size of myDoublePointer's type  : %d\n"
            "Size of myTime_tPointer's type  : %d\n",
            sizeof(*myPointer),
            sizeof(*myCharPointer),
            sizeof(*myDoublePointer),
            sizeof(*myTime_tPointer));

    return 0;
}
/*Output:
Size of myPointer's type        : 4
Size of myCharPointer's type    : 1
Size of myDoublePointer's type  : 8
Size of myTime_tPointer's type  : 4
 */


Call by Value and Call by Reference in ANSI C.

In ANSI C, variables can be referred directly or indirectly depending on the context.

A variable who is referred indirectly is a variable who is called-by-value. This means that when you pass the variable to a function, a hard copy of the variable will be created and used in that function. Any modifications that occur to the variable while in the function will not happen to the original variable (only the copy will be modified).

A variable who is referred directly is a variable who is called-by-reference. This means that you will send the actual variable to the function using a pointer. Any modifications that occur in the functions will affect the original variable.

Example:
#include<stdio.h>

void CallByValue(int value)
{
    value++;
    printf("Call by value in function     : %d\n",value);
}

void CallByReference(int *value)
{
    (*value)++;
    printf("Call be reference in function : %d\n",*value);
}

int main(int argc, char** argv)
{
    int i = 3;
    printf("Initial value                 : %d\n",i);
    CallByValue(i);
    printf("After call-by-value           : %d\n",i);
    CallByReference(&i);
    printf("After call-by-reference       : %d\n",i);
    return 0;
}
/*Output:
Initial value                 : 3
Call by value in function     : 4
After call-by-value           : 3
Call be reference in function : 4
After call-by-reference       : 4
 */
Observation:
The call by reference mechanism can also be used when you have a large variable to pass. This is especially useful when you work with low-memory systems. If you are not planning to modify the variable you should pass the parameter as a constant:

Example:
void CallByReference(const int *value)
{
    /*The line below would cause a compiler error because the
     value to which the pointer points is indicated as constant*/
    /*(*value)++;*/
    printf("Call be reference in function: %d\n",*value);
}

Saturday, August 11, 2012

Creating a Dynamic Matrix in ANSI C

The memory of a dynamic matrix can be allocated at run time as opposite to the static matrices (who are allocated at compile-time).

The allocation algorithm is based on the function void* malloc(size_t size). The first thing that must be done is to allocate the space for the entire matrix. After that, each row from the matrix must be allocated separately.
/*
 * Description:
 *  Allocates dinamically memory for a rows x columns matrix
 * Parameters:
 *  matrix  - a pointer to the matrix which will be allocated
 *  rows    - the number of rows
 *  columns - the number of columns
 * Returns:
 *  matrix - a pointer to the allocated matrix
 */
int** Matrix_Alloc(int** matrix, int rows, int columns)
{
    int i;
    matrix=malloc(sizeof(int)*rows*columns);
    if(matrix!=NULL)
    {
        /*Allocating space for each row*/
        for(i=0; i<rows;i++)
        {
            matrix[i] = malloc(sizeof(int)*columns);
            if(matrix[i]==NULL)
            {
                return NULL;
            }
        }
    }
    return matrix;
}
The deallocation algorithm is based on the function void free(void* address) and is pretty much the opposite of the allocation algorithm, First the rows of the matrix will be deallocated and then the matrix itself.
/*
 * Description:
 *  Frees a dynamically allocated matrix
 * Parameters:
 *  matrix  - a pointer to an allocated matrix
 *  rows    - the number of rows
 *  columns - the number of columns
 * Returns:
 *  Nothing
 */
void Matrix_Free(int** matrix, int rows)
{
    int i;
    for(i = 0; i < rows; i++)
    {
        free(matrix[i]);
    }
    free(matrix);
}
Here's an example on how to use the functions:
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

int** Matrix_Alloc(int** matrix, int rows, int columns);
void Matrix_Free(int** matrix, int rows);

void Matrix_Print(int** matrix, int rows, int columns)
{
    int i,j;
    for(i=0; i<rows;i++)
    {
        for(j=0; j<columns; j++)
        {
            printf("%d ",matrix[i][j]);
        }
        putchar('\n');
    }
}

int main(void)
{
    int **matrix = NULL;
    int i, j;

    /*Allocating the matrix*/
    matrix = Matrix_Alloc(matrix, 3, 3);

    /*Assigning values to the matrix*/
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            matrix[i][j] = (i+j);
        }
    }

    /*Printing the results*/
    Matrix_Print(matrix,3,3);

    /*Freeing the memory*/
    Matrix_Free(matrix,3);
    puts("Memory freed");

    return 0;
}
/*Output
0 1 2 
1 2 3 
2 3 4 
Memory freed
*/
In the example above we used a primitive data type. If we would had use a structure, each element of the matrix would had to be allocated/freed as well.

Conditional Inclusion in ANSI C

Let us assume that you have a program that will run on multiple platforms. For each platform you have an API which defines the functions that you will call in your program.

Example Scenario:
Your platforms are Windows, Unix, BSD and Mac. The headers for the platform specific operations are:
-Windows: windows_api.h
-Unix: unix_api.h
-BSD: bsd_api.h
-Mac: mac_api.h

Here's an example on how to implement conditional inclusion for this case:
#define PLATFORM_WINDOWS 0
#define PLATFORM_UNIX    1
#define PLATFROM_BSD     2
#define PLATFORM_MAC     3

/*Defines the system as UNIX*/
#define SYSTEM PLATFORM_UNIX

#if SYSTEM == PLATFORM_WINDOWS
    /*Uses the Windows platform API*/
    #include"windows_api.h"
    #define Shutdown()         WinQuit();
    #define ShowMessage(s)     WinShowMsg(s)
#elif SYSTEM == PLATFORM_UNIX
    /*Uses the Unix platform API*/
    #include"unix_api.h"
    #define Shutdown()         XQuit();
    #define ShowMessage(s)     XShowMsg();
#elif SYSTEM == PLATFORM_BSD
    /*Uses the BSD platform API*/
    #include"bsd_api.h"
    #define Shutdown()         BsdQuit();
    #define ShowMessage(s)     BsdShowMsg();
#elif SYSTEM == PLATFROM_MAC
    /*Uses the MAC platform API*/
    #include"mac_api.h"
    #define Shutdown()         MacQuit();
    #define ShowMessage(s)     MacShowMsg();
#else
    /*Triggers a compilation error*/
    #error Unknown platform
#endif

int main(void)
{
    /*The functions will use the UNIX API*/
    ShowMessage("Hello world!");
    ShutDown();
    return 0;
}

Avoiding Multiple Header Inclusion in ANSI C

Let us assume that you have 2 header files a.h and b.h and one source file main.c.

The files are in following relation:
Double-inclusion scenario
Let assume that this is the initial content of the files:
The content of b.h:
/*b.h*/
typedef enum
{
    val1 = 1,
    val2,
    val3
}EValues;
The content of a.h:
/*a.h*/
#include"b.h"

const int resource2 = val1+val2;
The content of main.c:
/*main.c*/
#include"a.h"
#include"b.h"
#include<stdio.h>

int main(void)
{
    printf("val1: %d\nval2: %d\nResource %d",val1,val2,resource2);
    return 0;
}
If you try to build the program you will encounter redeclaration errors:
../b.h:13:5: error: redeclaration of enumerator ‘val1’
../b.h:13:5: note: previous definition of ‘val1’ was here
../b.h:14:5: error: redeclaration of enumerator ‘val2’
../b.h:14:5: note: previous definition of ‘val2’ was here
../b.h:15:5: error: redeclaration of enumerator ‘val3’
../b.h:15:5: note: previous definition of ‘val3’ was here
../b.h:16:2: error: conflicting types for ‘EValues’
../b.h:16:2: note: previous declaration of ‘EValues’ was here
The solution for this problem is to use include guards.
#ifndef _HEADER_IDENTIFIER_
#define _HEADER_IDENTIFIER_

/*Header code*/

#endif
In order to make the program work corectly you will have to add an include guard to a.h and b.h:
The content of b.h:
/*b.h*/
#ifndef _B_H_
#define _B_H_

typedef enum
{
    val1 = 1,
    val2,
    val3
}EValues;

#endif
The content of a.h:
/*a.h*/
#ifndef _A_H_
#define _A_H_

#include"b.h"

const int resource2 = val1+val2;

#endif
The content of main.c:
/*main.c*/
#include"a.h"
#include"b.h"
#include<stdio.h>

int main(void)
{
    printf("val1: %d\nval2: %d\nResource %d",val1,val2,resource2);
    return 0;
}
/*Output
val1: 1
val2: 2
Resource 3
 */

The Literal Suffixes and Prefixes of ANSI C

In order to improve the readability of your code , you can declare constant literal values using suffixes.

Also, if you want to initialize integers in other radix than decimal, you can use prefixes. Characters can be as well declared using the octal, decimal and hexadecimal.

Here are some examples:
/*-----------------------------------------------
Integer constants
-----------------------------------------------*/
//A signed integer has no suffix
#define CI_1            (3);
//An unsigned integer has the u or U suffix
#define CUI_1           (3U);
//A long integer has the l or L suffix
#define CLI_1           (3L);
//A long integer has the ul or UL suffix
#define CLUI_1          (3UL);
/*-----------------------------------------------
Real constants
-----------------------------------------------*/
//A float has the f suffix
#define CF_1            (3.0F);
//A double has no suffix
#define CD_1            (3.0);
//A long double has l or L suffix
#define CLD_1           (3.0L);
/*Suffixes can also be added when you operate
  with the scientific notation*/
#define CF_2            (10e-1F);
#define CLD_2           (10e-1L);
/*-----------------------------------------------
Radix-based integer constants
-----------------------------------------------*/
//An octal-radix integer requires the 0 prefix
#define CIO_1           (037);
//A hexadecimal-radix requires the 0x prefix
#define CIH_1           (0x37);
/*The unsigned and long suffixes can be also applied to
  octal and hexadecimal*/
#define CUIO_1          (037U)
#define CLIO_1          (0x37U)
/*-----------------------------------------------
Character constants
-----------------------------------------------*/
//Declaring a character constant
#define CC_1            ('a')
//Defining the character constant using its ASCII code in octal
#define CC_2            ('\141')
//Defining the character constant using its ASCII code in hexadecimal
#define CC_3            ('\x61')
//Defining the character constant using its ASCII code in decimal
#define CC_4            (97)
/*-----------------------------------------------
String constants
-----------------------------------------------*/
//Declaring a string constant
#define CS_1            ("Constant string")
//You can initialize it using multiple smaller strings
#define CS_2            ("Constant " "string")
//You can also initialize it using multiple rows
#define CS_3            ("Constant \
                         string")
There is also a set of predefined character constants, in chapter 6 from the Formatted Strings article.

Question: Do you use constant/rvalue literals in your code?

References:

Monday, August 6, 2012

Reversing a String in ANSI C

If you're not familiar with how strings are represented in ANSI C, you should read this first:

We shall reverse the string in situ, without using an additional string. The implementation for this function is:
/**
 * Description:
 *  Reverses the received string.
 * Parameters:
 *  string - a pointer to the string who will be reversed
 * Returns:
 *  A pointer to the reversed string.
 * Postconditions:
 *  The "original" string who is sent will be reversed.
 */
char* String_Reverse(char *string)
{
   size_t last;
   int i;
   char swap;

   if(string!=NULL)
   {
      /*Computes the location of the last character*/
      last = strlen(string)-1;
      /*Itterates through the first half of the string*/
      for(i=0; i<(last/2); i++)
      {
         /*Swaps the first character with the last and so on*/
         swap = string[i];
         string[i] = string[last-i-1];
         string[last-i-1] = swap;
      }
   } 

 return string;
}
Here's an example on how to use the function:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char* String_Reverse(char *string);

int main(void)
{
   char string[] = "The simple pleasures are the last refuge of complex men";
   printf("Original string: %s\n", string);
   String_Reverse(string);
   printf("Reversed string: %s\n", string);
   return 0;
}
/*Output:
Original string: The simple pleasures are the last refuge of complex men
Reversed string: nem xelpmoc fo egufer tsal eht era serusaelp elpmis ehT
 */

Saturday, August 4, 2012

Other Matrix Operations in NMat

In order to understand this article, you should read the following articles first:

NMat provides several other operations for matrix calculus, such as:
-Finding the minimum/maximum element of a matrix
-Computing the sum/product of all elements of a matrix
-Extracting rows and columns from a matrix into a submatrix
-Computing the arithmetic, geometric and harmonic mean of all elements of a matrix

The prototypes for the functions implementing these operations are:
/*
 * Description:
 *  Finds the minimum element of the matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The minimum element. If an error happened it will return REAL_MAX
 */
real NMatrix_MinElement(const NMatrix* mat);
/*
 * Description:
 *  Finds the maximum element of the matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The maximum element. If an error happened it will return REAL_MIN
 */
real NMatrix_MaxElement(const NMatrix* mat);
/*
 * Description:
 *  Sums up all the elements of the matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The sum of all the elements. If an error happened it will return NAN
 */
real NMatrix_ElementSum(const NMatrix* mat);
/*
 * Description:
 *  Computes the product of all elements in the matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The product of all elements in the matrix. If an error happened it will
 *  return NAN.
 */
real NMatrix_ElementProduct(const NMatrix* mat);
/*
 * Description:
 *  Computes the number of elements in the matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The number of elements in the matrix. If an error happened it will
 *  return -1.
 */
integer NMatrix_ElementCount(const NMatrix* mat);
/*
 * Description:
 *  Creates a submatrix of the current matrix
 * Parameters:
 *  mat   - a pointer to the matrix
 *  startRow,endRow - the row delimiters
 *  startColumn, endColumn - the column delimiters
 * Returns:
 *  The specified submatrix. If an error happened it will return NULL.
 */
NMatrix* NMatrix_Submatrix(const NMatrix* mat,
      integer startRow, integer endRow,
      integer startColumn, integer endColumn);
/*
 * Description:
 *  Computes the arithmetic mean of all elements
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The arithmetic mean. If an error happened it will return NAN.
 */
real NMatrix_ArithmeticMean(const NMatrix* mat);
/*
 * Description:
 *  Computes the harmonic mean of all elements
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The harmonic mean. If an error happened it will return NAN.
 */
real NMatrix_HarmonicMean(const NMatrix* mat);
/*
 * Description:
 *  Computes the geometric mean of all elements
 * Parameters:
 *  mat   - a pointer to the matrix
 * Returns:
 *  The geometric mean. If an error happened it will return NAN.
 */
real NMatrix_GeometricMean(const NMatrix* mat);
Example:
#include<stdio.h>
#include"NMatrix.h"

void PrintMatrix(const NMatrix* mat)
{
   integer i, j;
   for (i = 0; i < mat->rows; ++i)
   {
      for (j = 0; j < mat->columns; ++j)
      {
         printf("%+f ", mat->data[i][j]);
      }
      putchar('\n');
   }
}

int main(void)
{
   NMatrix *mat = NULL;
   NMatrix *smat1 = NULL, *smat2=NULL;
   integer i,j;

   mat = NMatrix_Create(3,3);
   for(i=0; i<mat->rows; i++)
   {
      for(j=0; j<mat->columns; j++)
      {
         mat->data[i][j] = (real)(i+j+1);
      }
   }

   puts("The matrix: ");
   PrintMatrix(mat);

   printf("The smallest element is                :%f \n",
          NMatrix_MinElement(mat));
   printf("The largest element is                 :%f \n",
          NMatrix_MaxElement(mat));
   printf("The sum of all elements is             :%f \n",
          NMatrix_ElementSum(mat));
   printf("The product of all elements is         :%f \n",
          NMatrix_ElementProduct(mat));
   printf("The total number of elements is        :%d \n",
          NMatrix_ElementCount(mat));
   printf("The arithmetic mean of all elements is :%f \n",
          NMatrix_ArithmeticMean(mat));
   printf("The geometric mean of all elements is  :%f \n",
          NMatrix_GeometricMean(mat));
   printf("The harmonic mean of all elements is   :%f \n",
          NMatrix_HarmonicMean(mat));

   /*Will be a column vector containing column 1*/
   smat1 = NMatrix_Submatrix(mat,0,2,1,1);
   /*Will be a row vector containing only row 0*/
   smat2 = NMatrix_Submatrix(mat,0,0,0,2);

   puts("Submatrix 1: ");
   PrintMatrix(smat1);

   puts("Submatrix 2: ");
   PrintMatrix(smat2);
   return 0;
}
/*Output:
The matrix:
+1.000000 +2.000000 +3.000000
+2.000000 +3.000000 +4.000000
+3.000000 +4.000000 +5.000000
The smallest element is                :1.000000
The largest element is                 :5.000000
The sum of all elements is             :27.000000
The product of all elements is         :8640.000000
The total number of elements is        :9
The arithmetic mean of all elements is :3.000000
The geometric mean of all elements is  :2.432432
The harmonic mean of all elements is   :2.737729
The matrix:
+2.000000
+3.000000
+4.000000
The matrix:
+1.000000 +2.000000 +3.000000
 */

The NMat Library

NMat is a ANSI C library that provides an API for matrix operations.

The current operations implemented by NMatlib are:
Operation Description
Create Creates a NMatrix object
Destroy Destroys a NMatrix object
Clone Creates a hard copy of an existent NMatrix object
Sum Computes the sum of two matrices
Scalar Multiplication Multiplies the matrix with a scalar
Product Computes the product of two matrices
Secondary Diagonal Returns the secondary diagonal of a matrix
Primary Diagonal Returns the primary diagonal of a matrix
Minor Returns the minor of a matrix
Determinant Computes the determinant of a matrix
Transpose Computes the transpose of a matrix
Adjugate Computes the adjugate of a matrix
Inverse Computes the inverse of a matrix
Minimum Element Returns the smallest element of a matrix
Maximum Element Returns the largest element of a matrix
Sum of all elements Returns the sum of all elements
Product of all Elements Returns the product of all elements
Number of Elements Returns the total number of elements that exist in a matrix
Submatrix Returns a submatrix specified by a start/end column/row
Arithmetic Mean Returns the arithmetic mean of all elements from a matrix
Harmonic Mean Returns the harmonic mean of all elements from a matrix
Geometric Mean Returns the geometric mean of all elements from a matrix

The NMatrix structure is implemented as:
typedef double real;
typedef int integer;

typedef struct
{
   real** data;
   integer rows;
   integer columns;
}NMatrix;
The numeric matrix structure will contain information about the number of rows, columns and an dynamic 2D array to hold the data.

The prototypes for the functions are:
Operation Prototype
Create NMatrix* NMatrix_Create(integer rows, integer columns);
Destroy NMatrix* NMatrix_Destroy(NMatrix *matrix);
Clone NMatrix* NMatrix_Clone(const NMatrix *source);
Sum NMatrix* NMatrix_Sum(const NMatrix* mat1,const NMatrix* mat2);
Scalar Multiplication NMatrix* NMatrix_MultiplyWithScalar(const NMatrix* mat, real value);
Product NMatrix* NMatrix_Product(const NMatrix* mat1,const NMatrix* mat2);
Secondary Diagonal NMatrix* NMatrix_GetSecondaryDiagonal(NMatrix* mat);
Primary Diagonal NMatrix* NMatrix_GetPrimaryDiagonal(NMatrix *mat);
Minor NMatrix* NMatrix_Minor(const NMatrix *mat,
integer row, integer column,
Integer order);
Determinant real NMatrix_Determinant(const NMatrix *mat, integer order);
Transpose NMatrix* NMatrix_Transpose(const NMatrix* mat);
Adjugate NMatrix* NMatrix_Adjugate(const NMatrix* mat);
Inverse NMatrix* NMatrix_Inverse(const NMatrix* mat);
Minimum Element real NMatrix_MinElement(const NMatrix* mat);
Maximum Element real NMatrix_MaxElement(const NMatrix* mat);
Sum of all elements real NMatrix_ElementSum(const NMatrix* mat);
Product of all Elements real NMatrix_ElementProduct(const NMatrix* mat);
Number of Elements integer NMatrix_ElementCount(const NMatrix* mat);
Submatrix NMatrix* NMatrix_Submatrix(const NMatrix* mat,
integer startRow, integer endRow,
Integer startColumn, integer endColumn);
Arithmetic Mean real NMatrix_ArithmeticMean(const NMatrix* mat);
Harmonic Mean real NMatrix_HarmonicMean(const NMatrix* mat);
Geometric Mean real NMatrix_GeometricMean(const NMatrix* mat);


Related Posts Plugin for WordPress, Blogger...