<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C codechamp</title>
	<atom:link href="http://www.ccodechamp.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ccodechamp.com</link>
	<description>Portal to learn C programming Language like champs!</description>
	<lastBuildDate>Wed, 27 Feb 2013 18:12:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>C programming video tutorial 2 &#124; Introduction to Programming Languages</title>
		<link>http://www.ccodechamp.com/c-programming-video-tutorial-2-introduction-to-programming-languages/</link>
		<comments>http://www.ccodechamp.com/c-programming-video-tutorial-2-introduction-to-programming-languages/#comments</comments>
		<pubDate>Sun, 24 Feb 2013 08:08:26 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Tutorial]]></category>
		<category><![CDATA[C video Tutorials]]></category>
		<category><![CDATA[Programming Tips]]></category>
		<category><![CDATA[Best C video tutorials]]></category>
		<category><![CDATA[C language video tutorials]]></category>
		<category><![CDATA[C programming video tutorial]]></category>
		<category><![CDATA[C video tutorial of Introduction to programming languages]]></category>
		<category><![CDATA[C video tutorials]]></category>
		<category><![CDATA[Introduction to C video tutorial]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=530</guid>
		<description><![CDATA[<p>Hey friends, C code champ has came up with a concept of sharing best C  programming video tutorials available on internet. This video tutorial is made by Mr Phil Hameed, a software engineer having 15 years of exhaustive experience in C and C++ programming language. This is first of the series of tutorials covering the </p><p>The post <a href="http://www.ccodechamp.com/c-programming-video-tutorial-2-introduction-to-programming-languages/">C programming video tutorial 2 | Introduction to Programming Languages</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p>Hey friends, C code champ has came up with a concept of sharing <strong>best C  programming video tutorials</strong> available on internet. This video tutorial is made by Mr Phil Hameed, a software engineer having 15 years of exhaustive experience in <strong>C and C++ programming language</strong>. This is first of the series of tutorials covering the entire course of <strong>Programming In C Language</strong>. This tutorial basically gets you started by downloading and installing a FREE C/C++ compiler and Integrated Development Environment (IDE) called Dev-C++. This environment will be used in all the subsequent classes in this course. Let enjoy the C programming video tutorial 2 | Introduction to Programming Languages.</p>
<p>This tutorial gives an introduction to different types of programming languages. It also covers the definition of Compilers, Interpretors, Assemblers etc. It also creates the very first C Program thereby showing the structure of a simple C Program. This tutorial is one of the sequence of C Programming Tutorials. Please make sure you watch the videos that come before this and also the ones that come after this one.</p>
<div class="video-shortcode"><iframe title="YouTube video player" width="600" height="350" src="http://www.youtube.com/embed/dr0jRN2fg9I" frameborder="0" allowfullscreen></iframe></div>
<p>We hope you all have enjoyed the video tutorial . If you have any queries ask us in form of comments. Thanks for watching !</p>
<p>The post <a href="http://www.ccodechamp.com/c-programming-video-tutorial-2-introduction-to-programming-languages/">C programming video tutorial 2 | Introduction to Programming Languages</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-programming-video-tutorial-2-introduction-to-programming-languages/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C Program of Multilayer Perceptron Net using Backpropagation</title>
		<link>http://www.ccodechamp.com/c-program-of-multilayer-perceptron-net-using-backpropagation/</link>
		<comments>http://www.ccodechamp.com/c-program-of-multilayer-perceptron-net-using-backpropagation/#comments</comments>
		<pubDate>Sun, 24 Feb 2013 07:51:31 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C Code Champ]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Neural Networks]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[C Code of Multilayer Perceptron Net]]></category>
		<category><![CDATA[C code of Multilayer perceptron using Backpropagation]]></category>
		<category><![CDATA[C Program of Multilayer Perceptron Net using Backpropagation]]></category>
		<category><![CDATA[C program of Multilayer Perceptron Neural Networks]]></category>
		<category><![CDATA[C program of Multiplayer Perceptron]]></category>
		<category><![CDATA[C program to implement Multilayer perceptron]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[Neural networks in C]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=528</guid>
		<description><![CDATA[<p>C Program of Multilayer Perceptron Net using Backpropagation : A multilayer perceptron (MLP) is a feedforward artificial neural network model that maps sets of input data onto a set of appropriate output. An MLP consists of multiple layers of nodes in a directed graph, with each layer fully connected to the next one. Except for </p><p>The post <a href="http://www.ccodechamp.com/c-program-of-multilayer-perceptron-net-using-backpropagation/">C Program of Multilayer Perceptron Net using Backpropagation</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C Program of Multilayer Perceptron Net using Backpropagation</strong> : A <b>multilayer perceptron</b> (MLP) is a feedforward artificial neural network model that maps sets of input data onto a set of appropriate output. An MLP consists of multiple layers of nodes in a directed graph, with each layer fully connected to the next one. Except for the input nodes, each node is a neuron (or processing element) with a nonlinear activation function. MLP utilizes a supervised learning technique called backpropagation for training the network. MLP is a modification of the standard linear perceptron and can distinguish data that is not linearly separable.</p>
<h2>Learning through backpropagation :</h2>
<p>Learning occurs in the perceptron by changing connection weights after each piece of data is processed, based on the amount of error in the output compared to the expected result. This is an example of supervised learning, and is carried out through backpropagation, a generalization of the least mean squares algorithm in the linear perceptron.</p>
<p>We represent the error in output node <img alt="j" src="http://upload.wikimedia.org/math/3/6/3/363b122c528f54df4a0446b6bab05515.png" /> in the <img alt="n" src="http://upload.wikimedia.org/math/7/b/8/7b8b965ad4bca0e41ab51de7b31363a1.png" />th data point by <img alt="e_j(n)=d_j(n)-y_j(n)" src="http://upload.wikimedia.org/math/5/5/4/554e91b8c65b42cd8e3ecfa5666a23d8.png" />, where <img alt="d" src="http://upload.wikimedia.org/math/8/2/7/8277e0910d750195b448797616e091ad.png" /> is the target value and <img alt="y" src="http://upload.wikimedia.org/math/4/1/5/415290769594460e2e485922904f345d.png" /> is the value produced by the perceptron. We then make corrections to the weights of the nodes based on those corrections which minimize the error in the entire output, given by</p>
<dl>
<dd><img alt="\mathcal{E}(n)=\frac{1}{2}\sum_j e_j^2(n)" src="http://upload.wikimedia.org/math/8/9/a/89a36f69b62d2242d40f5a72734cc544.png" />.</dd>
</dl>
<p>Using gradient descent, we find our change in each weight to be</p>
<dl>
<dd><img alt="\Delta w_{ji} (n) = -\eta\frac{\partial\mathcal{E}(n)}{\partial v_j(n)} y_i(n)" src="http://upload.wikimedia.org/math/9/3/f/93f46061b00beb0c67853bc2be7e5694.png" /></dd>
</dl>
<p>where <img alt="y_i" src="http://upload.wikimedia.org/math/1/8/d/18daef71b5d25ce76b8628a81e4fc76b.png" /> is the output of the previous neuron and <img alt="\eta" src="http://upload.wikimedia.org/math/7/1/7/7174cbd6aeaaa56e37102b72386bb2b9.png" /> is the <i>learning rate</i>, which is carefully selected to ensure that the weights converge to a response fast enough, without producing oscillations. In programming applications, this parameter typically ranges from 0.2 to 0.8.</p>
<p>The derivative to be calculated depends on the induced local field <img alt="v_j" src="http://upload.wikimedia.org/math/2/7/5/275dc431f9270317c68595220d6b8730.png" />, which itself varies. It is easy to prove that for an output node this derivative can be simplified to</p>
<dl>
<dd><img alt="-\frac{\partial\mathcal{E}(n)}{\partial v_j(n)} = e_j(n)\phi^\prime (v_j(n))" src="http://upload.wikimedia.org/math/9/3/3/933f3e7385ffbc16da6da6418d2084b4.png" /></dd>
</dl>
<p>where <img alt="\phi^\prime" src="http://upload.wikimedia.org/math/b/b/c/bbc59d45b3a6e9f771911be80e671bf0.png" /> is the derivative of the activation function described above, which itself does not vary. The analysis is more difficult for the change in weights to a hidden node, but it can be shown that the relevant derivative is</p>
<dl>
<dd><img alt="-\frac{\partial\mathcal{E}(n)}{\partial v_j(n)} = \phi^\prime (v_j(n))\sum_k -\frac{\partial\mathcal{E}(n)}{\partial v_k(n)} w_{kj}(n)" src="http://upload.wikimedia.org/math/c/1/d/c1d22e328f389a19bd3908cbfe155add.png" />.</dd>
</dl>
<p>This depends on the change in weights of the <img alt="k" src="http://upload.wikimedia.org/math/8/c/e/8ce4b16b22b58894aa86c421e8759df3.png" />th nodes, which represent the output layer. So to change the hidden layer weights, we must first change the output layer weights according to the derivative of the activation function, and so this algorithm represents a <i>backpropagation of the activation function</i>.</p>
<p>Now let us see how we can implement above logic using C programming skills. First of all basic information about functions that we will use in the C program of Multilayer Perceptron Net using Backpropagation.</p>
<h2>Functions used in Multilayer Perceptron C Program  :</h2>
<blockquote><p><strong>void createNet( int noOfLayers, int *noOfNeurons, int *noOfInputs, char *axonFamilies, double *actFuncFlatnesses, int initWeights )</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt; </strong>Creates the net using given parameters where</p>
<ul>
<li><strong>noOfLayers:</strong> Total no. of layers, excluding input layer.</li>
<li><strong>noOfNeurons:</strong> No. of neurons for each layer.</li>
<li><strong>noOfInputs:</strong> No. of inputs for each layer.</li>
<li><strong>axonFamilies:</strong> Transfer function. Can be &#8216;g&#8217; (logistic), &#8216;t&#8217; (tanh) or &#8216;l&#8217; (linear) ; for each layer.</li>
<li><strong>actFuncFlatness:</strong> Flatness of the transfer functions for each layer.</li>
<li><strong>initWeights:</strong> &#8217;1&#8242; will initialize weights with random values, &#8217;0&#8242; will not. You should use &#8217;1&#8242; for practical use.</li>
</ul>
<p><strong>void feedNetInputs(double *inputs)</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt;  </strong>Feeds the net with given input values</p>
<p>void updateNetOutput( )<br />
<strong>-&gt;++&#8212;&gt;&gt;&gt; </strong>Updates the output of the NETWORK</p>
<p><strong>void trainNet ( double learningRate, double momentumRate, int batch, double *outputTargets )</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt; </strong>Trains the net where</p>
<ul>
<li><strong>learningRate:</strong> Should be between 0.0 and 1.0 (both excluded)</li>
<li><strong>momentumRate:</strong> Should be between 0.0 and 1.0 (both excluded)</li>
<li><strong>batch:</strong> Tells the function whether this will be a batch (1) or incremental (0) training.</li>
<li><strong>outputTargets:</strong> Output</li>
</ul>
<p><strong>void applyBatchCumulations( double learningRate, double momentumRate )</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt;  </strong>Calculates batch cumulations and updates weights accordingly. The net must be trained more than one time in batch mode before using this function where</p>
<ul>
<li><strong>learningRate:</strong> Should be between 0.0 and 1.0 (both excluded)</li>
<li><strong>momentumRate:</strong> Should be between 0.0 and 1.0 (both excluded)</li>
</ul>
<p><strong>double *getOutputs()</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt;  </strong>The one that should be used for obtaining the net&#8217;s outputs.</p>
<p><strong>int loadNet(char *path)</strong><br />
<strong>-&gt;++&#8212;&gt;&gt;&gt; </strong>Returns 0 if the operation is successful, 1 if not.</p></blockquote>
<p><strong> int main() :</strong><br />
You can code whatever you wish to implement using Multilayer Perceptron Net. In this you will write what you want to teach to Computer using Neural Network . We have taken a simple example  which  Create a Multilayer Perceptron net with two hidden layers. It takes two inputs, passes them through two hidden layers with 5 and 3 neurons, and an output layer with two neurons. Hidden layers use logistic activation, output layer uses tanh function, We try to train the net so that it learns how to sum two input values and output the sin() and cos() values of that sum; like   y0 = sin( x0 + x1 )    y1 = cos( x0 + x1 )  ; even though we know that it&#8217;s silly and practically useless to do so, when it&#8217;s far easier to calculate them using existing C libraries, We use batch training, with 100,000 total loops, each using random inputs between -1 and 1; applying batch changes and updating weights every 100 loops, Apply a test with 40 sets of inputs generated randomly again and show the results.<br />
Lets see C program of Multilayer Perceptron Net using backpropagation. I used Dev C++ to Execute this code. When you use Turbo C++ you might need to include malloc.h header directive.</p>
<h1>C program of Multilayer Perceptron using Backpropagation Neural Networks :</h1>
<pre class="brush:cpp">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;math.h&gt;
#include &lt;time.h&gt;

#define MAX_NO_OF_LAYERS 3
#define MAX_NO_OF_INPUTS 2
#define MAX_NO_OF_NEURONS 10
#define MAX_NO_OF_WEIGHTS 31
#define MAX_NO_OF_OUTPUTS 2

void createNet( int, int *, int *, char *, double *, int );
void feedNetInputs(double *);
void updateNetOutput(void);
double *getOutputs();
void trainNet ( double, double, int, double * );
void applyBatchCumulations( double, double );
int loadNet(char *);
int saveNet(char *);
double getRand();

struct neuron{
    double *output;
    double threshold;
    double oldThreshold;
    double batchCumulThresholdChange;
    char axonFamily;
    double *weights;
    double *oldWeights;
    double *netBatchCumulWeightChanges;
    int noOfInputs;
    double *inputs;
    double actFuncFlatness;
    double *error;
};

struct layer {
    int noOfNeurons;
    struct neuron * neurons;
};

static struct neuralNet {
    int noOfInputs;
    double *inputs;
    double *outputs;
    int noOfLayers;
    struct layer *layers;
    int noOfBatchChanges;
} theNet;

double getRand() {

    return (( (double)rand() * 2 ) / ( (double)RAND_MAX + 1 ) ) - 1;

}

static struct neuron netNeurons[MAX_NO_OF_NEURONS];
static double netInputs[MAX_NO_OF_INPUTS];
static double netNeuronOutputs[MAX_NO_OF_NEURONS];
static double netErrors[MAX_NO_OF_NEURONS];
static struct layer netLayers[MAX_NO_OF_LAYERS];
static double netWeights[MAX_NO_OF_WEIGHTS];
static double netOldWeights[MAX_NO_OF_WEIGHTS];
static double netBatchCumulWeightChanges[MAX_NO_OF_WEIGHTS];

void createNet( int noOfLayers, int *noOfNeurons, int *noOfInputs, char *axonFamilies, double *actFuncFlatnesses, int initWeights ) {

    int i, j, counter, counter2, counter3, counter4;
    int totalNoOfNeurons, totalNoOfWeights;

    theNet.layers = netLayers;
    theNet.noOfLayers = noOfLayers;
    theNet.noOfInputs = noOfInputs[0];
    theNet.inputs = netInputs;

    totalNoOfNeurons = 0;
    for(i = 0; i &lt; theNet.noOfLayers; i++) {
        totalNoOfNeurons += noOfNeurons[i];
    }
    for(i = 0; i &lt; totalNoOfNeurons; i++) { netNeuronOutputs[i] = 0; }

    totalNoOfWeights = 0;
    for(i = 0; i &lt; theNet.noOfLayers; i++) {
        totalNoOfWeights += noOfInputs[i] * noOfNeurons[i];
    }

    counter = counter2 = counter3 = counter4 = 0;
    for(i = 0; i &lt; theNet.noOfLayers; i++) {
        for(j = 0; j &lt; noOfNeurons[i]; j++) {
            if(i == theNet.noOfLayers-1 &amp;&amp; j == 0) { // beginning of the output layer
                theNet.outputs = &amp;netNeuronOutputs[counter];
            }
            netNeurons[counter].output = &amp;netNeuronOutputs[counter];
            netNeurons[counter].noOfInputs = noOfInputs[i];
            netNeurons[counter].weights = &amp;netWeights[counter2];
            netNeurons[counter].netBatchCumulWeightChanges = &amp;netBatchCumulWeightChanges[counter2];
            netNeurons[counter].oldWeights = &amp;netOldWeights[counter2];
            netNeurons[counter].axonFamily = axonFamilies[i];
            netNeurons[counter].actFuncFlatness = actFuncFlatnesses[i];
            if ( i == 0) {
                netNeurons[counter].inputs = netInputs;
            }
            else {
                netNeurons[counter].inputs = &amp;netNeuronOutputs[counter3];
            }
            netNeurons[counter].error = &amp;netErrors[counter];
            counter2 += noOfInputs[i];
            counter++;
        }
        netLayers[i].noOfNeurons = noOfNeurons[i];
        netLayers[i].neurons = &amp;netNeurons[counter4];
        if(i &gt; 0) {
            counter3 += noOfNeurons[i-1];
        }
        counter4 += noOfNeurons[i];
    }

    // initialize weights and thresholds
     if ( initWeights == 1 ) {
        for( i = 0; i &lt; totalNoOfNeurons; i++) { netNeurons[i].threshold = getRand(); }
        for( i = 0; i &lt; totalNoOfWeights; i++) { netWeights[i] = getRand(); }
        for( i = 0; i &lt; totalNoOfWeights; i++) { netOldWeights[i] = netWeights[i]; }
        for( i = 0; i &lt; totalNoOfNeurons; i++) { netNeurons[i].oldThreshold = netNeurons[i].threshold; }
    }

    // initialize batch values
    for( i = 0; i &lt; totalNoOfNeurons; i++) { netNeurons[i].batchCumulThresholdChange = 0; }
    for( i = 0; i &lt; totalNoOfWeights; i++) { netBatchCumulWeightChanges[i] = 0; }
    theNet.noOfBatchChanges = 0;

}

void feedNetInputs(double *inputs) {
     int i;
     for ( i = 0; i &lt; theNet.noOfInputs; i++ ) {
        netInputs[i] = inputs[i];
     }
}

static void updateNeuronOutput(struct neuron * myNeuron) {

    double activation = 0;
    int i;

    for ( i = 0; i &lt; myNeuron-&gt;noOfInputs; i++) {
        activation += myNeuron-&gt;inputs[i] * myNeuron-&gt;weights[i];
    }
    activation += -1 * myNeuron-&gt;threshold;
    double temp;
    switch (myNeuron-&gt;axonFamily) {
        case 'g': // logistic
            temp = -activation / myNeuron-&gt;actFuncFlatness;
            /* avoid overflow */
            if ( temp &gt; 45 ) {
                *(myNeuron-&gt;output) = 0;
            }
            else if ( temp &lt; -45 ) {
                *(myNeuron-&gt;output) = 1;
            }
            else {
                *(myNeuron-&gt;output) = 1.0 / ( 1 + exp( temp ));
            }
            break;
        case 't': // tanh
            temp = -activation / myNeuron-&gt;actFuncFlatness;
            /* avoid overflow */
            if ( temp &gt; 45 ) {
                *(myNeuron-&gt;output) = -1;
            }
            else if ( temp &lt; -45 ) {
                *(myNeuron-&gt;output) = 1;
            }
            else {
                *(myNeuron-&gt;output) = ( 2.0 / ( 1 + exp( temp ) ) ) - 1;
            }
            break;
        case 'l': // linear
            *(myNeuron-&gt;output) = activation;
            break;
        default:
            break;
    }

}

void updateNetOutput( ) {

    int i, j;

    for(i = 0; i &lt; theNet.noOfLayers; i++) {
        for( j = 0; j &lt; theNet.layers[i].noOfNeurons; j++) {
            updateNeuronOutput(&amp;(theNet.layers[i].neurons[j]));
        }
    }

}

static double derivative (struct neuron * myNeuron) {

    double temp;
    switch (myNeuron-&gt;axonFamily) {
        case 'g': // logistic
            temp = ( *(myNeuron-&gt;output) * ( 1.0 - *(myNeuron-&gt;output) ) ) / myNeuron-&gt;actFuncFlatness; break;
        case 't': // tanh
            temp = ( 1 - pow( *(myNeuron-&gt;output) , 2 ) ) / ( 2.0 * myNeuron-&gt;actFuncFlatness ); break;
        case 'l': // linear
            temp = 1; break;
        default:
            temp = 0; break;
    }
    return temp;

}

// learningRate and momentumRate will have no effect if batch mode is 'on'
void trainNet ( double learningRate, double momentumRate, int batch, double *outputTargets ) {

    int i,j,k;
    double temp;
    struct layer *currLayer, *nextLayer;

     // calculate errors
    for(i = theNet.noOfLayers - 1; i &gt;= 0; i--) {
        currLayer = &amp;theNet.layers[i];
        if ( i == theNet.noOfLayers - 1 ) { // output layer
            for ( j = 0; j &lt; currLayer-&gt;noOfNeurons; j++ ) {
                *(currLayer-&gt;neurons[j].error) = derivative(&amp;currLayer-&gt;neurons[j]) * ( outputTargets[j] - *(currLayer-&gt;neurons[j].output));
            }
        }
        else { // other layers
            nextLayer = &amp;theNet.layers[i+1];
            for ( j = 0; j &lt; currLayer-&gt;noOfNeurons; j++ ) {
                temp = 0;
                for ( k = 0; k &lt; nextLayer-&gt;noOfNeurons; k++ ) {
                    temp += *(nextLayer-&gt;neurons[k].error) * nextLayer-&gt;neurons[k].weights[j];
                }
                *(currLayer-&gt;neurons[j].error) = derivative(&amp;currLayer-&gt;neurons[j]) * temp;
            }
        }
    }

    // update weights n thresholds
    double tempWeight;
    for(i = theNet.noOfLayers - 1; i &gt;= 0; i--) {
        currLayer = &amp;theNet.layers[i];
        for ( j = 0; j &lt; currLayer-&gt;noOfNeurons; j++ ) {

            // thresholds
            if ( batch == 1 ) {
                    currLayer-&gt;neurons[j].batchCumulThresholdChange += *(currLayer-&gt;neurons[j].error) * -1;
            }
            else {
                tempWeight = currLayer-&gt;neurons[j].threshold;
                currLayer-&gt;neurons[j].threshold += ( learningRate * *(currLayer-&gt;neurons[j].error) * -1 ) + ( momentumRate * ( currLayer-&gt;neurons[j].threshold - currLayer-&gt;neurons[j].oldThreshold ) );
                currLayer-&gt;neurons[j].oldThreshold = tempWeight;
            }

            // weights
            if ( batch == 1 ) {
                for( k = 0; k &lt; currLayer-&gt;neurons[j].noOfInputs; k++ ) {
                    currLayer-&gt;neurons[j].netBatchCumulWeightChanges[k] +=  *(currLayer-&gt;neurons[j].error) * currLayer-&gt;neurons[j].inputs[k];
                }
            }
            else {
                for( k = 0; k &lt; currLayer-&gt;neurons[j].noOfInputs; k++ ) {
                    tempWeight = currLayer-&gt;neurons[j].weights[k];
                    currLayer-&gt;neurons[j].weights[k] += ( learningRate * *(currLayer-&gt;neurons[j].error) * currLayer-&gt;neurons[j].inputs[k] ) + ( momentumRate * ( currLayer-&gt;neurons[j].weights[k] - currLayer-&gt;neurons[j].oldWeights[k] ) );
                    currLayer-&gt;neurons[j].oldWeights[k] = tempWeight;
                }
            }

        }
    }

    if(batch == 1) {
        theNet.noOfBatchChanges++;
    }

}

void applyBatchCumulations( double learningRate, double momentumRate ) {

    int i,j,k;
    struct layer *currLayer;
    double tempWeight;

    for(i = theNet.noOfLayers - 1; i &gt;= 0; i--) {
        currLayer = &amp;theNet.layers[i];
        for ( j = 0; j &lt; currLayer-&gt;noOfNeurons; j++ ) {
            // thresholds
            tempWeight = currLayer-&gt;neurons[j].threshold;
            currLayer-&gt;neurons[j].threshold += ( learningRate * ( currLayer-&gt;neurons[j].batchCumulThresholdChange / theNet.noOfBatchChanges ) ) + ( momentumRate * ( currLayer-&gt;neurons[j].threshold - currLayer-&gt;neurons[j].oldThreshold ) );
            currLayer-&gt;neurons[j].oldThreshold = tempWeight;
            currLayer-&gt;neurons[j].batchCumulThresholdChange = 0;
            // weights
            for( k = 0; k &lt; currLayer-&gt;neurons[j].noOfInputs; k++ ) {
                tempWeight = currLayer-&gt;neurons[j].weights[k];
                currLayer-&gt;neurons[j].weights[k] += ( learningRate * ( currLayer-&gt;neurons[j].netBatchCumulWeightChanges[k] / theNet.noOfBatchChanges ) ) + ( momentumRate * ( currLayer-&gt;neurons[j].weights[k] - currLayer-&gt;neurons[j].oldWeights[k] ) );
                currLayer-&gt;neurons[j].oldWeights[k] = tempWeight;
                currLayer-&gt;neurons[j].netBatchCumulWeightChanges[k] = 0;
            }
        }
    }

    theNet.noOfBatchChanges = 0;

}

double *getOutputs() {

    return theNet.outputs;

}

int loadNet(char *path) {

    int tempInt; double tempDouble; char tempChar;
    int i, j, k;

    int noOfLayers;
    int noOfNeurons[MAX_NO_OF_LAYERS];
    int noOfInputs[MAX_NO_OF_LAYERS];
    char axonFamilies[MAX_NO_OF_LAYERS];
    double actFuncFlatnesses[MAX_NO_OF_LAYERS];

    FILE *inFile;

    if(!(inFile = fopen(path, "rb")))
    return 1;

    fread(&amp;tempInt,sizeof(int),1,inFile);
    noOfLayers = tempInt;

    for(i = 0; i &lt; noOfLayers; i++) {

        fread(&amp;tempInt,sizeof(int),1,inFile);
        noOfNeurons[i] = tempInt;

        fread(&amp;tempInt,sizeof(int),1,inFile);
        noOfInputs[i] = tempInt;

        fread(&amp;tempChar,sizeof(char),1,inFile);
        axonFamilies[i] = tempChar;

        fread(&amp;tempDouble,sizeof(double),1,inFile);
        actFuncFlatnesses[i] = tempDouble;

    }

    createNet(noOfLayers, noOfNeurons, noOfInputs, axonFamilies, actFuncFlatnesses, 0);

    // now the weights
    for(i = 0; i &lt; noOfLayers; i++) {
        for (j = 0; j &lt; noOfNeurons[i]; j++) {
            fread(&amp;tempDouble,sizeof(double),1,inFile);
            theNet.layers[i].neurons[j].threshold = tempDouble;
            for ( k = 0; k &lt; noOfInputs[i]; k++ ) {
                fread(&amp;tempDouble,sizeof(double),1,inFile);
                theNet.layers[i].neurons[j].weights[k] = tempDouble;
            }
        }
    }

    fclose(inFile);

    return 0;

}

int main() {

    double inputs[MAX_NO_OF_INPUTS];
    double outputTargets[MAX_NO_OF_OUTPUTS];

    /* determine layer paramaters */
    int noOfLayers = 3; // input layer excluded
    int noOfNeurons[] = {5,3,2};
    int noOfInputs[] = {2,5,3};
    char axonFamilies[] = {'g','g','t'};
    double actFuncFlatnesses[] = {1,1,1};

    createNet(noOfLayers, noOfNeurons, noOfInputs, axonFamilies, actFuncFlatnesses, 1);

    /* train it using batch method */
    int i;
    double tempTotal;
    int counter = 0;
    for(i = 0; i &lt; 100000; i++) {
        inputs[0] = getRand();
        inputs[1] = getRand();
        tempTotal = inputs[0] + inputs[1];
        feedNetInputs(inputs);
        updateNetOutput();
        outputTargets[0] = (double)sin(tempTotal);
        outputTargets[1] = (double)cos(tempTotal);
        /* train using batch training ( don't update weights, just cumulate them ) */
        trainNet(0, 0, 1, outputTargets);
        counter++;
        /* apply batch changes after 1000 loops use .8 learning rate and .8 momentum */
        if(counter == 100) { applyBatchCumulations(.8,.8); counter = 0;}
    }

    /* test it */
    double *outputs;
    printf("Sin Target \t Output \t Cos Target \t Output\n");
    printf("---------- \t -------- \t ---------- \t --------\n");
    for(i = 0; i &lt; 50; i++) {
        inputs[0] = getRand();
        inputs[1] = getRand();
        tempTotal = inputs[0] + inputs[1];
        feedNetInputs(inputs);
        updateNetOutput();
        outputs = getOutputs();
        printf( "%f \t %f \t %f \t %f \n", sin(tempTotal), outputs[0], cos(tempTotal), outputs[1]);
    }
    getch();
    return 0;

}</pre>
<p>&nbsp;</p>
<p><strong>Output of the Program :</strong></p>
<p>Sin Target       Output          Cos Target      Output<br />
&#8212;&#8212;&#8212;-       &#8212;&#8212;&#8211;        &#8212;&#8212;&#8212;-      &#8212;&#8212;&#8211;<br />
-0.282596        -0.251506       0.959239        0.926403<br />
0.987397         0.929951        0.158263        0.134966<br />
-0.742784        -0.767919       0.669531        0.702895<br />
0.963356         0.951930        -0.268225       -0.092782<br />
-0.910491        -0.891614       0.413529        0.392311<br />
-0.446427        -0.435320       0.894820        0.894715<br />
-0.781594        -0.803610       0.623788        0.646886<br />
0.290957         0.265966        0.956736        0.930159<br />
-0.809212        -0.825646       0.587516        0.602877<br />
-0.736788        -0.761619       0.676123        0.711298<br />
-0.998244        -0.947075       -0.059235       -0.001200<br />
0.387922         0.371767        0.921692        0.915250<br />
0.994482         0.934887        0.104905        0.091594<br />
0.755998         0.785001        0.654574        0.683916<br />
-0.188741        -0.161969       0.982027        0.937597<br />
-0.493026        -0.488288       0.870015        0.882922<br />
-0.440519        -0.424683       0.897743        0.899018<br />
-0.852693        -0.855158       0.522413        0.527307<br />
-0.140706        -0.128390       0.990051        0.940160<br />
0.189161         0.167637        0.981946        0.938250<br />
0.996926         0.936743        0.078345        0.074192<br />
-0.424008        -0.411728       0.905658        0.902929<br />
0.653792         0.669850        0.756674        0.806735<br />
0.003967         -0.012354       0.999992        0.944188<br />
0.170850         0.132011        0.985297        0.940968<br />
-0.417585        -0.398821       0.908638        0.903615<br />
0.001099         0.006551        0.999999        0.943892<br />
0.306393         0.282745        0.951905        0.928428<br />
-0.995529        -0.938210       0.094459        0.087609<br />
-0.299005        -0.266307       0.954252        0.925483<br />
-0.041004        -0.027936       0.999159        0.942476<br />
0.809427         0.827636        0.587220        0.601242<br />
0.474114         0.471661        0.880463        0.893326<br />
0.621403         0.638472        0.783491        0.827109<br />
0.097623         0.087701        0.995224        0.941710<br />
0.220047         0.196894        0.975489        0.936800<br />
-0.520229        -0.522084       0.854027        0.870829<br />
0.865589         0.866682        0.500755        0.487957<br />
-0.582818        -0.594292       0.812603        0.843467<br />
-0.996864        -0.940069       0.079136        0.070250<br />
0.118071         0.094599        0.993005        0.942999<br />
0.481941         0.472472        0.876204        0.893215<br />
-0.119829        -0.107898       0.992795        0.941339<br />
-0.682174        -0.706359       0.731189        0.770417<br />
-0.022764        -0.028302       0.999741        0.944128<br />
-0.977695        -0.927944       0.210029        0.174750<br />
-0.022764        -0.026860       0.999741        0.944174<br />
0.998870         0.938790        0.047524        0.053881<br />
0.205854         0.179691        0.978583        0.938419<br />
-0.660372        -0.684212       0.750939        0.788505</p>
<p>We hope you all have enjoyed the C program of Multilayer Perceptron using Backpropagation Neural Networks. If you have any issue with the program or logic ask us in form of comment.</p>
<p>References :</p>
<p>1. <a title="Wikipedia Multilayer Perceptron" href="http://en.wikipedia.org/wiki/Multilayer_perceptron" target="_blank">Wikipedia</a> ( Read for more details about Multilayer Perceptron and learning technique and activation function)</p>
<p>2. Ncorpus</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-of-multilayer-perceptron-net-using-backpropagation/">C Program of Multilayer Perceptron Net using Backpropagation</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-of-multilayer-perceptron-net-using-backpropagation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C Program to print strings in alphabetical order</title>
		<link>http://www.ccodechamp.com/c-program-to-print-strings-in-alphabetical-order/</link>
		<comments>http://www.ccodechamp.com/c-program-to-print-strings-in-alphabetical-order/#comments</comments>
		<pubDate>Sun, 24 Feb 2013 06:54:08 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[Strings]]></category>
		<category><![CDATA[C code to sort strings into albhabetical order]]></category>
		<category><![CDATA[C Program to print strings in alphabetical order]]></category>
		<category><![CDATA[C Program to print strings in alphabetical order using Arrays]]></category>
		<category><![CDATA[C program to Print strings into Lexicographical Order using arrays]]></category>
		<category><![CDATA[C Program to sort strings in alphabetical order using Arrays]]></category>
		<category><![CDATA[C program to sort strings in Lexicograhical order]]></category>
		<category><![CDATA[C programs]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=526</guid>
		<description><![CDATA[<p>C Program to print strings in alphabetical order or Lexicographical order : As we all know there are several ways to sort strings alphabetically but using arrays is the easiest.  Ordering Strings into alphabetical form is also referred as Lexicographical ordering of strings. Today we will learn how to sort or print strings in alphabetical </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-print-strings-in-alphabetical-order/">C Program to print strings in alphabetical order</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C Program to print strings in alphabetical order or Lexicographical order</strong> : As we all know there are several ways to sort strings alphabetically but using arrays is the easiest.  Ordering Strings into alphabetical form is also referred as Lexicographical ordering of strings. Today we will learn how to sort or print strings in alphabetical order using C programming.  Actually its quite easy stuff, simply apply the bubble sort algorithm on strings i.e. compare two adjacent strings and swap strings accordingly based on order you want.</p>
<p>Simple Logic of Sorting Strings in Alphabetical Order or Lexicographical order is below :</p>
<blockquote><p>for (i=0;i&lt;m;i++)<br />
for (j=i+1;j&lt;m+1;j++)<br />
{<br />
if (strcmp(a[i],a[j])&gt;0)<br />
{<br />
strcpy(temp,a[i]);<br />
strcpy(a[i],a[j]);<br />
strcpy(a[j],temp);<br />
}<br />
}</p></blockquote>
<p>Now let us see how to write a C Program to print strings in alphabetical order.</p>
<h1>C program to Print Strings in Alphabetical Order :</h1>
<pre class="brush:cpp">#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;conio.h&gt;
int main()
{
char a[50][50],temp[100];
int i,j,m,n;
printf("Enter the number of elements you wish to order : ");
scanf("%d",&amp;m);
printf("\nEnter the names :\n");
for (i=0;i&lt;m+1;i++)
gets(a[i]);
for (i=0;i&lt;m;i++)
for (j=i+1;j&lt;m+1;j++)
{
if (strcmp(a[i],a[j])&gt;0)
{
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
printf("\n\nSorted strings are : ");
for (i=0;i&lt;m+1;i++)
puts (a[i]);
getch();
}</pre>
<p><strong> Output of the Program</strong> :</p>
<p>Enter the number of elements you wish to order : 4</p>
<p>Enter the names :<br />
Lokesh Singh<br />
Rahul Sinha<br />
Rahul Gupta<br />
Ajay Singh</p>
<p>Sorted strings are :<br />
Ajay Singh<br />
Lokesh Singh<br />
Rahul Gupta<br />
Rahul Sinha</p>
<p>We hope you all have enjoyed the C program of Printing Strings into Lexicographical order or Alphabetical order. If you have any doubts or issues ask us in form of comments.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-print-strings-in-alphabetical-order/">C Program to print strings in alphabetical order</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-print-strings-in-alphabetical-order/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C Program to Concatenate two Strings using Arrays</title>
		<link>http://www.ccodechamp.com/c-program-to-concatenate-two-strings-using-arrays/</link>
		<comments>http://www.ccodechamp.com/c-program-to-concatenate-two-strings-using-arrays/#comments</comments>
		<pubDate>Sun, 24 Feb 2013 06:28:07 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[Strings]]></category>
		<category><![CDATA[C code to concatenate strings without using Strcat]]></category>
		<category><![CDATA[C code to concatenate two strings using arrays]]></category>
		<category><![CDATA[C Program to Concatenate two Strings]]></category>
		<category><![CDATA[C Program to Concatenate two Strings using Arrays]]></category>
		<category><![CDATA[C programs]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=524</guid>
		<description><![CDATA[<p>C Program to Concatenate two Strings using Arrays : There are lot of ways of concatenating strings in C programming, also there is standard function in C &#8220;strcat&#8221; to concatenate the strings. But how to concatenate strings without using standard String function. Today we will learn how to concatenate two strings using arrays. Actually concept </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-concatenate-two-strings-using-arrays/">C Program to Concatenate two Strings using Arrays</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C Program to Concatenate two Strings using Arrays</strong> : There are lot of ways of concatenating strings in C programming, also there is standard function in C<strong> &#8220;strcat&#8221;</strong> to concatenate the strings. But how to concatenate strings without using standard String function. Today we will learn how to concatenate two strings using arrays. Actually concept is quite easy, we just need to declare three string arrays, first two for taking input from user and third one to store concatenated string.</p>
<p>Logic to concatenate two strings : Say str1[50] and str2[50] are two input string arrays and str[100] will store concatenated string. Now we will store str1[50] into str[100] until null string &#8216;\0&#8242; is encountered and then from next location start storing str2[50] until null string &#8216;\0&#8242; is encountered.</p>
<p>Now let us see how to write a C program to concatenate two strings using Arrays.</p>
<h1>C Program to Concatenate two Strings using arrays :</h1>
<pre class="brush:cpp">#include&lt;stdio.h&gt;
#include&lt;string.h&gt;
#include&lt;conio.h&gt;
int main()
{
char str1[50],str2[50],str[100];
int i=0,j=0,k=0;
printf ("Enter first string : ");
gets (str1);
printf ("\n\nEnter second string : ");
gets (str2);
while (str1[i]!='\0')
{
str[k++]=str1[i++];
}
while (str2[j]!='\0')
{
str[k++]=str2[j++];
}
str[k]='\0';
printf("\n\nThe concatenated string is : ");
puts (str);
getch();
}</pre>
<p><strong> Output of the program :</strong></p>
<p>Enter first string : Lokesh is owner of</p>
<p>Enter second string : Ccodechamp</p>
<p>The concatenated string is : Lokesh is owner of Ccodechamp</p>
<p>We hope you all have enjoyed the C program to Concatenate two strings using arrays. If you have any doubt ask us in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-concatenate-two-strings-using-arrays/">C Program to Concatenate two Strings using Arrays</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-concatenate-two-strings-using-arrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C program of Transpose of Matrix &#124; Matrix Programs in C</title>
		<link>http://www.ccodechamp.com/c-program-of-transpose-of-matrix-matrix-programs-in-c/</link>
		<comments>http://www.ccodechamp.com/c-program-of-transpose-of-matrix-matrix-programs-in-c/#comments</comments>
		<pubDate>Sat, 23 Feb 2013 10:29:41 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[C Code Champ]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Matrix]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[C code to implement transpose of Matrix]]></category>
		<category><![CDATA[C Code to Transpose Matix]]></category>
		<category><![CDATA[C program of Transpose of Matrix]]></category>
		<category><![CDATA[C program to Calculate transpose of matrix]]></category>
		<category><![CDATA[C program to find Transpose of matrix]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[Matrix Porgrams in C]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=523</guid>
		<description><![CDATA[<p>C program of Transpose of Matrix : Transpose of Matrix is one of the most important operations on Matrices and quite easy one too.  Transpose of Matrix means exchanging all rows of Matrix with columns of Matrix and vice versa.  Consider an Example, say i have a matrix A defined below : A     = 1      </p><p>The post <a href="http://www.ccodechamp.com/c-program-of-transpose-of-matrix-matrix-programs-in-c/">C program of Transpose of Matrix | Matrix Programs in C</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C program of Transpose of Matrix</strong> : Transpose of Matrix is one of the most important operations on Matrices and quite easy one too.  Transpose of Matrix means exchanging all rows of Matrix with columns of Matrix and vice versa.  Consider an Example, say i have a matrix A defined below :</p>
<blockquote><p>A     =</p>
<p>1      2     3</p>
<p>4      5     6</p></blockquote>
<p>Now Transpose of Matrix A   will be,A<sup>T  </sup>=</p>
<div>
<blockquote><p>1     4</p>
<p>2     5</p>
<p>3       6</p></blockquote>
<p>Now lets see how to write a C program to transpose a matrix. As we know we only need to interchange the rows and columns of Matrices to obtain the transpose, so its quite easy operation. Below i have created a simple C program which will transpose of Given Matrix. It accepts number of Rows and columns and its elements as input and generates output Transpose matrix.</p>
<h1>C program of Transpose of Matrix :</h1>
<pre class="brush:cpp">#include &lt;stdio.h&gt;
#include &lt;conio.h&gt; 
int main()
{
   int m, n, c, d, matrix[10][10], transpose[10][10];

   printf("Enter number of rows and columns of matrix :- ");
   scanf("%d%d",&amp;m,&amp;n);
   printf("\nEnter the elements of [%d x %d] matrix :- \n",m,n);
 /*Get Elements of matrix*/
   for( c = 0 ; c &lt; m ; c++ )
   {
      for( d = 0 ; d &lt; n ; d++ )
      {
         scanf("%d",&amp;matrix[c][d]);
      }
   }
 /*Printing Entered Matrix*/
  printf("\nEntered Matrix is :- \n");
  for( c = 0 ; c &lt; m ; c++ )
   {
      for( d = 0 ; d &lt; n ; d++ )
      {
         printf("%d\t",matrix[c][d]);
      }
      printf("\n"); 
   }
 /*Transpose Matrix */  
   for( c = 0 ; c &lt; m ; c++ )
   {
      for( d = 0 ; d &lt; n ; d++ )
      {
         transpose[d][c] = matrix[c][d];
      }
   }
 /* Printing Transpose Matrix*/
   printf("\n\n\nTranspose of entered matrix :-\n");

   for( c = 0 ; c &lt; n ; c++ )
   {
      for( d = 0 ; d &lt; m ; d++ )
      {
         printf("%d\t",transpose[c][d]);
      }  
      printf("\n");
   }
   getch();
   return 0;
}</pre>
<p><strong>Output of Program :</strong></p>
<p>Enter number of rows and columns of matrix :- 2 3</p>
<p>Enter the elements of [2 x 3] matrix :-<br />
1<br />
2<br />
3<br />
4<br />
5<br />
6</p>
<p>Entered Matrix is :-<br />
1       2       3<br />
4       5       6</p>
<p>Transpose of entered matrix :-<br />
1       4<br />
2       5<br />
3       6</p>
<p>If you have any doubts or queries ask me in form of comments.</p>
</div>
<p>The post <a href="http://www.ccodechamp.com/c-program-of-transpose-of-matrix-matrix-programs-in-c/">C program of Transpose of Matrix | Matrix Programs in C</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-of-transpose-of-matrix-matrix-programs-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C Program of Huffman coding using Greedy Algorithm Approach</title>
		<link>http://www.ccodechamp.com/c-program-of-huffman-coding-using-greedy-algorithm-approach/</link>
		<comments>http://www.ccodechamp.com/c-program-of-huffman-coding-using-greedy-algorithm-approach/#comments</comments>
		<pubDate>Wed, 20 Feb 2013 06:43:43 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C Code Champ]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Graph Algorithms]]></category>
		<category><![CDATA[Linked Lists]]></category>
		<category><![CDATA[Minimum Spanning Tree]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[C code of Huffman coding]]></category>
		<category><![CDATA[C Code of Huffman coding using Greedy Algorithm]]></category>
		<category><![CDATA[C Program of Huffman coding]]></category>
		<category><![CDATA[C Program of Huffman coding using Greedy Algorithm]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[Greedy Algorithms in C]]></category>
		<category><![CDATA[Huffman Data Compression Algorithm in C]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=520</guid>
		<description><![CDATA[<p>C Program of Huffman coding using Greedy Algorithm Approach : This code is not written by me. I found a great article on Geeks for Geeks and thought it worth sharing. Still if you have any doubts ask me in form of comments. Basic of Huffman Coding : Huffman coding is a lossless data compression </p><p>The post <a href="http://www.ccodechamp.com/c-program-of-huffman-coding-using-greedy-algorithm-approach/">C Program of Huffman coding using Greedy Algorithm Approach</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C Program of Huffman coding using Greedy Algorithm Approach</strong> : This code is not written by me. I found a great article on Geeks for Geeks and thought it worth sharing. Still if you have any doubts ask me in form of comments.</p>
<h2><strong>Basic of Huffman Coding : </strong></h2>
<p><strong>Huffman coding</strong> is a lossless data compression algorithm. The idea is to assign variable-legth codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code.<br />
The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not prefix of code assigned to any other character. This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bit stream.<br />
Let us understand prefix codes with a counter example. Let there be four characters a, b, c and d, and their corresponding variable length codes be 00, 01, 0 and 1. This coding leads to ambiguity because code assigned to c is prefix of codes assigned to a and b. If the compressed bit stream is 0001, the de-compressed output may be “cccd” or “ccb” or “acd” or “ab”.</p>
<p>There are mainly two major parts in Huffman Coding<br />
<strong>1)</strong> Build a Huffman Tree from input characters.<br />
<strong>2)</strong> Traverse the Huffman Tree and assign codes to characters.</p>
<p><strong><em>Steps to build Huffman Tree</em></strong><br />
Input is array of unique characters along with their frequency of occurrences and output is Huffman Tree.</p>
<p><strong>1.</strong> Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)</p>
<p><strong>2.</strong> Extract two nodes with the minimum frequency from the min heap.</p>
<p><strong>3.</strong> Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap.</p>
<p><strong>4.</strong> Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.</p>
<p>Let us understand the algorithm with an example:</p>
<pre>character   Frequency
    a	        5
    b           9
    c           12
    d           13
    e           16
    f           45</pre>
<p><strong>Step 1.</strong> Build a min heap that contains 6 nodes where each node represents root of a tree with single node.</p>
<p><strong>Step 2</strong> Extract two minimum frequency nodes from min heap. Add a new internal node with frequency 5 + 9 = 14.<br />
<a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-1.jpeg"><img class="aligncenter" title="fig-1" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-1-300x129.jpeg" width="200" height="82" /></a><br />
Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each, and one heap node is root of tree with 3 elements</p>
<pre>character           Frequency
       c               12
       d               13
 Internal Node         14
       e               16
       f                45
<strong>
Step 3:</strong> Extract two minimum frequency nodes from heap. Add a new internal node with frequency 12 + 13 = 25
<a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-2.jpg"><img class="aligncenter" title="fig-2" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-2-300x132.jpg" width="200" height="82" />
</a>

Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each, and two heap nodes are root of tree with more than one nodes.</pre>
<pre>character           Frequency
Internal Node          14
       e               16
Internal Node          25
       f               45
<strong>
Step 4:</strong> Extract two minimum frequency nodes. Add a new internal node with frequency 14 + 16 = 30

<a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-3.jpg"><img class="aligncenter" title="fig-3" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-3-300x162.jpg" width="260" height="135" /></a>
Now min heap contains 3 nodes.</pre>
<pre>character          Frequency
Internal Node         25
Internal Node         30
      f               45 

<strong>Step 5:</strong> Extract two minimum frequency nodes. Add a new internal node with frequency 25 + 30 = 55

<a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-4.jpg"><img class="aligncenter" title="fig-4" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-4-300x121.jpg" width="300" height="121" /></a>
Now min heap contains 2 nodes.</pre>
<pre>character     Frequency
       f         45
Internal Node    55

<strong>Step 6:</strong> Extract two minimum frequency nodes. Add a new internal node with frequency 45 + 55 = 100

<a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-5.jpg"><img class="aligncenter" title="fig-5" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-5-300x167.jpg" width="340" height="186" /></a>
Now min heap contains only one node.</pre>
<pre>character      Frequency
Internal Node    100</pre>
<p>Since the heap contains only one node, the algorithm stops here.</p>
<p><strong><em>Steps to print codes from Huffman Tree:</em></strong><br />
Traverse the tree formed starting from the root. Maintain an auxiliary array. While moving to the left child, write 0 to the array. While moving to the right child, write 1 to the array. Print the array when a leaf node is encountered.</p>
<p style="text-align: center;"><a href="http://www.geeksforgeeks.org/wp-content/uploads/fig-6.jpg"><img class="aligncenter" title="fig-6" alt="" src="http://www.geeksforgeeks.org/wp-content/uploads/fig-6-300x167.jpg" width="300" height="167" /></a><br />
The codes are as follows:</p>
<pre>character   code-word
    f          0
    c          100
    d          101
    a          1100
    b          1101
    e          111</pre>
<h1>C Program of Huffman coding using Greedy Algorithm Approach :</h1>
<pre class="brush:cpp">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

// This constant can be avoided by explicitly calculating height of Huffman Tree
#define MAX_TREE_HT 100

// A Huffman tree node
struct MinHeapNode
{
    char data;  // One of the input characters
    unsigned freq;  // Frequency of the character
    struct MinHeapNode *left, *right; // Left and right child of this node
};

// A Min Heap:  Collection of min heap (or Hufmman tree) nodes
struct MinHeap
{
    unsigned size;    // Current size of min heap
    unsigned capacity;   // capacity of min heap
    struct MinHeapNode **array;  // Attay of minheap node pointers
};

// A utility function allocate a new min heap node with given character
// and frequency of the character
struct MinHeapNode* newNode(char data, unsigned freq)
{
    struct MinHeapNode* temp =
          (struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
    temp-&gt;left = temp-&gt;right = NULL;
    temp-&gt;data = data;
    temp-&gt;freq = freq;
    return temp;
}

// A utility function to create a min heap of given capacity
struct MinHeap* createMinHeap(unsigned capacity)
{
    struct MinHeap* minHeap =
         (struct MinHeap*) malloc(sizeof(struct MinHeap));
    minHeap-&gt;size = 0;  // current size is 0
    minHeap-&gt;capacity = capacity;
    minHeap-&gt;array =
     (struct MinHeapNode**)malloc(minHeap-&gt;capacity * sizeof(struct MinHeapNode*));
    return minHeap;
}

// A utility function to swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
    struct MinHeapNode* t = *a;
    *a = *b;
    *b = t;
}

// The standard minHeapify function.
void minHeapify(struct MinHeap* minHeap, int idx)
{
    int smallest = idx;
    int left = 2 * idx + 1;
    int right = 2 * idx + 2;

    if (left &lt; minHeap-&gt;size &amp;&amp;
        minHeap-&gt;array[left]-&gt;freq &lt; minHeap-&gt;array[smallest]-&gt;freq)
      smallest = left;

    if (right &lt; minHeap-&gt;size &amp;&amp;
        minHeap-&gt;array[right]-&gt;freq &lt; minHeap-&gt;array[smallest]-&gt;freq)
      smallest = right;

    if (smallest != idx)
    {
        swapMinHeapNode(&amp;minHeap-&gt;array[smallest], &amp;minHeap-&gt;array[idx]);
        minHeapify(minHeap, smallest);
    }
}

// A utility function to check if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap)
{
    return (minHeap-&gt;size == 1);
}

// A standard function to extract minimum value node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
    struct MinHeapNode* temp = minHeap-&gt;array[0];
    minHeap-&gt;array[0] = minHeap-&gt;array[minHeap-&gt;size - 1];
    --minHeap-&gt;size;
    minHeapify(minHeap, 0);
    return temp;
}

// A utility function to insert a new node to Min Heap
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)
{
    ++minHeap-&gt;size;
    int i = minHeap-&gt;size - 1;
    while (i &amp;&amp; minHeapNode-&gt;freq &lt; minHeap-&gt;array[(i - 1)/2]-&gt;freq)
    {
        minHeap-&gt;array[i] = minHeap-&gt;array[(i - 1)/2];
        i = (i - 1)/2;
    }
    minHeap-&gt;array[i] = minHeapNode;
}

// A standard funvtion to build min heap
void buildMinHeap(struct MinHeap* minHeap)
{
    int n = minHeap-&gt;size - 1;
    int i;
    for (i = (n - 1) / 2; i &gt;= 0; --i)
        minHeapify(minHeap, i);
}

// A utility function to print an array of size n
void printArr(int arr[], int n)
{
    int i;
    for (i = 0; i &lt; n; ++i)
        printf("%d", arr[i]);
    printf("\n");
}

// Utility function to check if this node is leaf
int isLeaf(struct MinHeapNode* root)
{
    return !(root-&gt;left) &amp;&amp; !(root-&gt;right) ;
}

// Creates a min heap of capacity equal to size and inserts all character of 
// data[] in min heap. Initially size of min heap is equal to capacity
struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size)
{
    struct MinHeap* minHeap = createMinHeap(size);
    for (int i = 0; i &lt; size; ++i)
        minHeap-&gt;array[i] = newNode(data[i], freq[i]);
    minHeap-&gt;size = size;
    buildMinHeap(minHeap);
    return minHeap;
}

// The main function that builds Huffman tree
struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size)
{
    struct MinHeapNode *left, *right, *top;

    // Step 1: Create a min heap of capacity equal to size.  Initially, there are
    // modes equal to size.
    struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);

    // Iterate while size of heap doesn't become 1
    while (!isSizeOne(minHeap))
    {
        // Step 2: Extract the two minimum freq items from min heap
        left = extractMin(minHeap);
        right = extractMin(minHeap);

        // Step 3:  Create a new internal node with frequency equal to the
        // sum of the two nodes frequencies. Make the two extracted node as
        // left and right children of this new node. Add this node to the min heap
        // '$' is a special value for internal nodes, not used
        top = newNode('$', left-&gt;freq + right-&gt;freq);
        top-&gt;left = left;
        top-&gt;right = right;
        insertMinHeap(minHeap, top);
    }

    // Step 4: The remaining node is the root node and the tree is complete.
    return extractMin(minHeap);
}

// Prints huffman codes from the root of Huffman Tree.  It uses arr[] to
// store codes
void printCodes(struct MinHeapNode* root, int arr[], int top)
{
    // Assign 0 to left edge and recur
    if (root-&gt;left)
    {
        arr[top] = 0;
        printCodes(root-&gt;left, arr, top + 1);
    }

    // Assign 1 to right edge and recur
    if (root-&gt;right)
    {
        arr[top] = 1;
        printCodes(root-&gt;right, arr, top + 1);
    }

    // If this is a leaf node, then it contains one of the input
    // characters, print the character and its code from arr[]
    if (isLeaf(root))
    {
        printf("%c: ", root-&gt;data);
        printArr(arr, top);
    }
}

// The main function that builds a Huffman Tree and print codes by traversing
// the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size)
{
   //  Construct Huffman Tree
   struct MinHeapNode* root = buildHuffmanTree(data, freq, size);

   // Print Huffman codes using the Huffman tree built above
   int arr[MAX_TREE_HT], top = 0;
   printCodes(root, arr, top);
}

// Driver program to test above functions
int main()
{
    char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
    int freq[] = {5, 9, 12, 13, 16, 45};
    int size = sizeof(arr)/sizeof(arr[0]);
    HuffmanCodes(arr, freq, size);
    return 0;
}</pre>
<p> If you have any doubts ask us in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-of-huffman-coding-using-greedy-algorithm-approach/">C Program of Huffman coding using Greedy Algorithm Approach</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-of-huffman-coding-using-greedy-algorithm-approach/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C program to add two polynomials using Linked Lists</title>
		<link>http://www.ccodechamp.com/c-program-to-add-two-polynomials-using-linked-lists/</link>
		<comments>http://www.ccodechamp.com/c-program-to-add-two-polynomials-using-linked-lists/#comments</comments>
		<pubDate>Tue, 19 Feb 2013 07:40:52 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Linked Lists]]></category>
		<category><![CDATA[Numerical Series]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[Add two polynomials using linked list in C]]></category>
		<category><![CDATA[C code to add two polynomials using Linked Lists]]></category>
		<category><![CDATA[c program]]></category>
		<category><![CDATA[C program adding polynomials using Linked List]]></category>
		<category><![CDATA[C program for addition two polynomials using Linked lists]]></category>
		<category><![CDATA[C program to add two polynomials using Linked List]]></category>
		<category><![CDATA[C program to add two polynomials using Linked Lists]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=519</guid>
		<description><![CDATA[<p>C program to add two polynomials using Linked Lists : Adding two polynomials is quite easy stuff when we do it manually but it requires a bit effort while programming it. I have written a simple three step Algorithm to add polynomials: 1. Seperate the like terms aside say polynomial is 2xy^2 +x^2 +x. Now </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-add-two-polynomials-using-linked-lists/">C program to add two polynomials using Linked Lists</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C program to add two polynomials using Linked Lists</strong> : Adding two polynomials is quite easy stuff when we do it manually <img src='http://www.ccodechamp.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  but it requires a bit effort while programming it. I have written a simple three step Algorithm to add polynomials:</p>
<blockquote><p>1. Seperate the like terms aside say polynomial is 2xy^2 +x^2 +x. Now we have three seperate terms: xy^2, x^2 and x.</p>
<p>2. Add the coefficients of like terms.</p>
<p>3. Append the seperate terms to form an polynomial.</p></blockquote>
<p>The same concept is implemented below with the Help of Linked List. Let us see how to write a C program of adding two poynomials using Linked Lists.</p>
<h1> C program to add two polynomials using Linked Lists :</h1>
<pre class="brush:cpp">#include &lt;stdio.h&gt;
#include &lt;conio.h&gt;
#include &lt;malloc.h&gt;
#include &lt;stdlib.h&gt;
typedef struct pnode
   {
	float coef;
	int exp;
	struct pnode *next;
   }p;
p *getnode();
//Main function starts here
void main()
   {
	p *p1,*p2,*p3; 
	p *getpoly(),*add(p*,p*); 
	void display(p*);
	clrscr();
	printf(“\n Enter first polynomial”);
	p1=getpoly();
	printf(“\n Enter second polynomial”);
	p2=getpoly();
	printf(“\nThe first polynomial is”);
	display(p1);
	printf(“\nThe second polynomial is”);
	display(p2);
	p3=add(p1,p2);
	printf(“\nAddition of two polynomial is :\n”);
	display(p3); 
   }

/*Funtion to get polynomial*/
p *getpoly()
  {
	p *temp,*New,*last;
	int flag,exp;
	char ans;
	float coef;
	temp=NULL;
	flag=1;
	printf(“\nenter the polynomial in descending order of exponent”);
	do
	  {
		printf(“\nenter the coef &amp; exponent of a term”);
		scanf(“%f%d”,&amp;coef,&amp;exp);
		New=getnode();
		if(New==NULL)
		printf(“\nmemory cannot be allocated”);
		New-&gt;coef=coef;
		New-&gt;exp=exp;
		if(flag==1)
		  {
			temp=New;
			last=temp;
			flag=0;
		   }
		else
		  {
			last-&gt;next=New;
			last=New;
		   }
		printf(“\ndou want to more terms”);
		ans=getch();
	    }
      while(ans==’y');
      return(temp);
   }
/*Function to get the Nodes of Polynomial*/
p *getnode()
  {
	p *temp;
	temp=(p*) malloc (sizeof(p));
	temp-&gt;next=NULL;
	return(temp);
  }
/*Function to display Polynomial*/
void display(p*head)
  {
	p*temp;
	temp=head;
	if(temp==NULL)
	printf(“\npolynomial empty”);
	while(temp-&gt;next!=NULL)
	  {
		printf(“%0.1fx^%d+”,temp-&gt;coef,temp-&gt;exp);
		temp=temp-&gt;next;
	   }
	printf(“\n%0.1fx^%d”,temp-&gt;coef,temp-&gt;exp);
	getch();
   }
/*Function to add Polynomials*/
p*add(p*first,p*second)
  {
	p *p1,*p2,*temp,*dummy;
	char ch;
	float coef;
	p *append(int,float,p*);
	p1=first;
	p2=second;
	temp=(p*)malloc(sizeof(p));
	if(temp==NULL)
	printf(“\nmemory cannot be allocated”);
	dummy=temp;
	while(p1!=NULL&amp;&amp;p2!=NULL)
	  {
		if(p1-&gt;exp==p2-&gt;exp)
    		  {
			coef=p1-&gt;coef+p2-&gt;coef;
			temp=append(p1-&gt;exp,coef,temp);
			p1=p1-&gt;next;
			p2=p2-&gt;next;
	           }
		else
		if(p1-&gt;expexp)
		  {
			coef=p2-&gt;coef;
			temp=append(p2-&gt;exp,coef,temp);
			p2=p2-&gt;next;
		   }
		else
		if(p1-&gt;exp&gt;p2-&gt;exp)
		  {
			coef=p1-&gt;coef;
			temp=append(p1-&gt;exp,coef,temp);
			p1=p1-&gt;next;
		   }
	   }
	while(p1!=NULL)
	  {
		temp=append(p1-&gt;exp,p1-&gt;coef,temp);
		p1=p1-&gt;next;
		}
	while(p2!=NULL)
	  {
		temp=append(p2-&gt;exp,p2-&gt;coef,temp);
		p2=p2-&gt;next;
		}
	temp-&gt;next=NULL;
	temp=dummy-&gt;next;
	free(dummy);
	return(temp);
   }
/*Function to append the coefficients with Polynomial*/
p*append(int Exp,float Coef,p*temp)
  {
	p*New,*dum;
	New=(p*)malloc(sizeof(p));
	if(New==NULL)
	printf(“\ncannot be allocated”);
	New-&gt;exp=Exp;
	New-&gt;coef=Coef;
	New-&gt;next=NULL;
	dum=temp;
	dum-&gt;next=New;
	dum=New;
	return(dum);
  }</pre>
<p> We hope you all have enjoyed the C program to add two polynomials using Linked Lists. If you have any doubts or queries ask me in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-add-two-polynomials-using-linked-lists/">C program to add two polynomials using Linked Lists</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-add-two-polynomials-using-linked-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C program to Find Minimum Spanning tree KRUSKAL&#8217;s Algorithm</title>
		<link>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-kruskals-algorithm/</link>
		<comments>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-kruskals-algorithm/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 06:57:06 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Graph Algorithms]]></category>
		<category><![CDATA[Minimum Spanning Tree]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[algorithms in C]]></category>
		<category><![CDATA[C code of KRUSKAL's Algorithm]]></category>
		<category><![CDATA[C code to find Minimum Spanning tree of weighted graphs]]></category>
		<category><![CDATA[C code to implement KRUSKAL's Algorithm]]></category>
		<category><![CDATA[C program to Find Minimum Spanning tree KRUSKAL's Algorithm]]></category>
		<category><![CDATA[C program to Find Minimum Spanning tree using KRUSKAL's Algorithm]]></category>
		<category><![CDATA[C program to implement KRUSKAL's Algorithm]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[KRUSKAL's Algorithm implementation in C]]></category>
		<category><![CDATA[KRUSKAL's Algorithm in C]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=518</guid>
		<description><![CDATA[<p>C program to Find Minimum Spanning tree KRUSKAL&#8217;s Algorithm : Kruskal&#8217;s algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-kruskals-algorithm/">C program to Find Minimum Spanning tree KRUSKAL&#8217;s Algorithm</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C program to Find Minimum Spanning tree KRUSKAL&#8217;s Algorithm</strong> : <b>Kruskal&#8217;s algorithm</b> is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. If the graph is not connected, then it finds a <i>minimum spanning forest</i> (a minimum spanning tree for each connected component).</p>
<p>Generalized approach to find Minimum Spanning tree of weighted graphs using <strong>KRUSKAL&#8217;s Algorithm</strong> :</p>
<ul>
<li>
<blockquote><p>create a forest <i>F</i> (a set of trees), where each vertex in the graph is a separate tree</p></blockquote>
</li>
<li>
<blockquote><p>create a set <i>S</i> containing all the edges in the graph</p></blockquote>
</li>
<li>
<blockquote><p>while <i>S</i> is nonempty and F is not yet spanning</p></blockquote>
<ul>
<li>
<blockquote><p>remove an edge with minimum weight from <i>S</i></p></blockquote>
</li>
<li>
<blockquote><p>if that edge connects two different trees, then add it to the forest, combining two trees into a single tree</p></blockquote>
</li>
<li>
<blockquote><p>otherwise discard that edge.</p></blockquote>
</li>
</ul>
</li>
</ul>
<p>At the termination of the algorithm, the forest forms a minimum spanning forest of the graph. If the graph is connected, the forest has a single component and forms a minimum spanning tree.</p>
<p>Lets see how to write a C code to implement KRUSKAL&#8217;s Algorithm to find Minimum Spanning tree of weighted graphs.</p>
<h1>C program to Find Minimum Spanning tree using KRUSKAL&#8217;s Algorithm  :</h1>
<pre class="brush:cpp">#include&lt;stdio.h&gt;
#define INF 1000
char vertex[10];
int wght[10][10];
int span_wght[10][10];
int source;
struct Sort
{
int v1,v2;
int weight;
}que[20];
int n,ed,f,r;
int cycle(int s,int d)
{
int j,k;
if(source==d)
return 1;
for(j=0;j&lt;n;j++)
if(span_wght[d][j]!=INF &amp;&amp; s!=j)
{
if(cycle(d,j))
return 1;
}
return 0;
}
void build_tree()
{
int i,j,w,k,count=0;
for(count=0;count&lt;n;f++)
{
i=que[f].v1;
j=que[f].v2;
w=que[f].weight;
span_wght[i][j]=span_wght[j][i]=w;
source=i;
k=cycle(i,j);
if(k)
span_wght[i][j]=span_wght[j][i]=INF;
else
count++;
}
}
void swap(int *i,int *j)
{
int t;
t=*i;
*i=*j;
*j=t;
}
void main()
{
int i,j,k=0,temp;
int sum=0;
clrscr();
printf("\n\n\tKRUSKAL'S ALGORITHM TO FIND SPANNING TREE\n\n");
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&amp;n);
for(i=0;i&lt;n;i++)
{
printf("\n\tEnter %d value : ",i+1);
fflush(stdin);
scanf("%c",&amp;vertex[i]);
for(j=0;j&lt;n;j++)
{
wght[i][j]=INF;
span_wght[i][j]=INF;
}
}
printf("\n\nGetting Weight\n");
for(i=0;i&lt;n;i++)
for(j=i+1;j&lt;n;j++)
{
printf("\nEnter 0 if path Doesn't exist between %c to %c : ",vertex[i],vertex[j]);
scanf("%d",&amp;ed);
if(ed&gt;=1)
{
wght[i][j]=wght[j][i]=ed;
que[r].v1=i;
que[r].v2=j;
que[r].weight=wght[i][j];
if(r)
{
for(k=0;k&lt;r;k++)
if(que[k].weight&gt;que[r].weight)
{
swap(&amp;que[k].weight,&amp;que[r].weight);
swap(&amp;que[k].v1,&amp;que[r].v1);
swap(&amp;que[k].v2,&amp;que[r].v2);
}
}
r++;
}
}
clrscr();
printf("\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n");
printf("\n\tweight matrix\n\n\t");
for(i=0;i&lt;n;i++,printf("\n\t"))
for(j=0;j&lt;n;j++,printf("\t"))
printf("%d",wght[i][j]);
build_tree();
printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");
printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i&lt;n;i++)
for(j=i+1;j&lt;n;j++)
if(span_wght[i][j]!=INF)
{
printf("\n\t\t%c ------ %c = %d ",vertex[i],vertex[j],span_wght[i][j]);
sum+=span_wght[i][j];
}
printf("\n\n\t\tTotal Weight : %d ",sum);
getch();
}</pre>
<p>We hope you all have enjoyed the C program of Kruskal&#8217;s Algorithm to find minimum spanning tree. If you have any doubts or queries ask us in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-kruskals-algorithm/">C program to Find Minimum Spanning tree KRUSKAL&#8217;s Algorithm</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-kruskals-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C program to find Minimum Spanning tree PRIM&#8217;s Algorithm</title>
		<link>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-prims-algorithm/</link>
		<comments>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-prims-algorithm/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 06:29:09 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Graph Algorithms]]></category>
		<category><![CDATA[Minimum Spanning Tree]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[algorithms in C]]></category>
		<category><![CDATA[C code of Minimum Spanning tree using PRIM's Algorithm]]></category>
		<category><![CDATA[C code of Prims algorithm]]></category>
		<category><![CDATA[C code to find Minimum Spanning tree using PRIM's Algorithm]]></category>
		<category><![CDATA[C program of Minimum Spanning tree]]></category>
		<category><![CDATA[C program of Minimum Spanning tree using PRIM's Algorithm]]></category>
		<category><![CDATA[C program of MST using Prim's algorithm]]></category>
		<category><![CDATA[C program of Prim's algorithm]]></category>
		<category><![CDATA[C program to find Minimum Spanning tree using PRIM's Algorithm]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[C programs of Graphs]]></category>
		<category><![CDATA[Minimum Spanning tree using PRIM's Algorithm]]></category>
		<category><![CDATA[PRIM's Algorithm in C]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=517</guid>
		<description><![CDATA[<p>C program to find Minimum Spanning tree PRIM&#8217;s Algorithm : Prim&#8217;s algorithm is a greedy algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-prims-algorithm/">C program to find Minimum Spanning tree PRIM&#8217;s Algorithm</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C program to find Minimum Spanning tree PRIM&#8217;s Algorithm</strong> : <b>Prim&#8217;s algorithm</b> is a greedy algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.</p>
<p>General apporach for writing a C Code to Find Minimum Spanning tree using PRIM&#8217;s Algorithm :</p>
<ul>
<li>
<blockquote><p>create a tree containing a single vertex, chosen arbitrarily from the graph</p></blockquote>
</li>
<li>
<blockquote><p>create a set containing all the edges in the graph</p></blockquote>
</li>
<li>
<blockquote><p>loop until every edge in the set connects two vertices in the tree</p></blockquote>
<ul>
<li>
<blockquote><p>remove from the set an edge with minimum weight that connects a vertex in the tree with a vertex not in the tree</p></blockquote>
</li>
<li>
<blockquote><p>add that edge to the tree</p></blockquote>
</li>
</ul>
</li>
</ul>
<p>Let&#8217;s see how to write a C program of PRIM&#8217;s Algorithm to find Minimum Spanning tree.</p>
<h1>C program to find Minimum Spanning tree using PRIM&#8217;s Algorithm :</h1>
<p>&nbsp;</p>
<pre class="brush:cpp">#include&lt;stdio.h&gt;
#define INF 1000
int vertex[10];
int wght[10][10];
int new_wght[10][10];
int closed[10];
int n;
int inclose(int i,int n1)
{
/*chk for the ith vertex presence in closed*/
int j;
for(j=0;j&lt;=n1;j++)
if(closed[j]==i)
return 1;
return 0;
}
void buildtree()
{
int i=0,j,count=0;
int min,k,v1=0,v2=0;
closed[0]=0;
while(count&lt;n-1)
{
min=INF;
for(i=0;i&lt;=count;i++)
for(j=0;j&lt;n;j++)
if(wght[closed[i]][j]&lt;min &amp;&amp; !inclose(j,count))
{
min=wght[closed[i]][j];
v1=closed[i];
v2=j;
}
new_wght[v1][v2]=new_wght[v2][v1]=min;
count++;
closed[count]=v2;
printf("\nScan : %d %d---------%d wght = %d \n",count,v1+1,v2+1,min);
getch();
}
}
void main()
{
int i,j,ed,sum=0;
clrscr();
printf("\n\n\tPRIM'S ALGORITHM TO FIND SPANNING TREE\n\n");
printf("\n\tEnter the No. of Nodes : ");
scanf("%d",&amp;n);
for(i=0;i&lt;n;i++)
{
vertex[i]=i+1;
for(j=0;j&lt;n;j++)
{
wght[i][j]=INF;
new_wght[i][j]=INF;
}
}
printf("\n\nGetting Weight.\n");
printf("\n\tEnter 0 if path doesn't exist between {v1,v2} else enter the wght\n");
for(i=0;i&lt;n;i++)
for(j=i+1;j&lt;n;j++)
{
printf("\n\t%d -------- %d : ",vertex[i],vertex[j]);
scanf("%d",&amp;ed);
if(ed&gt;=1)
wght[i][j]=wght[j][i]=ed;
}
getch();
clrscr();
printf("\n\n\t\tNODES CURRENTLY ADDED TO SPANNING TREE\n\n");
buildtree();
printf("\n\tNEW GRAPH WEIGHT MATRIX\n\n");
printf("\n\tweight matrix\n\n\t");
for(i=0;i&lt;n;i++,printf("\n\t"))
for(j=0;j&lt;n;j++,printf("\t"))
printf("%d",new_wght[i][j]);
printf("\n\n\t\tMINIMUM SPANNING TREE\n\n");
printf("\n\t\tLIST OF EDGES\n\n");
for(i=0;i&lt;n;i++)
for(j=i+1;j&lt;n;j++)
if(new_wght[i][j]!=INF)
{
printf("\n\t\t%d ------ %d = %d ",vertex[i],vertex[j],new_wght[i][j]);
sum+=new_wght[i][j];
}
printf("\n\n\t Total Weight : %d ",sum);
getch();
}</pre>
<p>We hope you all have enjoyed the C program of PRIM&#8217;s Algorithm to find minimum spanning tree. If you have any doubts or queries ask us in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-prims-algorithm/">C program to find Minimum Spanning tree PRIM&#8217;s Algorithm</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-find-minimum-spanning-tree-prims-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C program to implement Cyclic Redundancy Check CRC</title>
		<link>http://www.ccodechamp.com/c-program-to-implement-cyclic-redundancy-check-crc/</link>
		<comments>http://www.ccodechamp.com/c-program-to-implement-cyclic-redundancy-check-crc/#comments</comments>
		<pubDate>Sun, 17 Feb 2013 18:38:57 +0000</pubDate>
		<dc:creator>Mr Coder</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C Code Champ]]></category>
		<category><![CDATA[C Programs]]></category>
		<category><![CDATA[Computer Networks]]></category>
		<category><![CDATA[Matrix]]></category>
		<category><![CDATA[Source Codes]]></category>
		<category><![CDATA[C code of Cyclic Redundancy Check]]></category>
		<category><![CDATA[C code to implement Cyclic Redundancy Check]]></category>
		<category><![CDATA[C program to implement CRC check]]></category>
		<category><![CDATA[C program to implement Cyclic Redundancy Check]]></category>
		<category><![CDATA[C programs]]></category>
		<category><![CDATA[Cyclic Redundancy Check in C programming]]></category>

		<guid isPermaLink="false">http://www.ccodechamp.com/?p=514</guid>
		<description><![CDATA[<p>C program to implement Cyclic Redundancy Check CRC : A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to raw data. Blocks of data entering these systems get a short check value attached, based on the remainder of a polynomial division of their </p><p>The post <a href="http://www.ccodechamp.com/c-program-to-implement-cyclic-redundancy-check-crc/">C program to implement Cyclic Redundancy Check CRC</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></description>
				<content:encoded><![CDATA[<p><strong>C program to implement Cyclic Redundancy Check CRC</strong> : A <b>cyclic redundancy check</b> (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to raw data. Blocks of data entering these systems get a short <i>check value</i> attached, based on the remainder of a polynomial division of their contents; on retrieval the calculation is repeated, and corrective action can be taken against presumed data corruption if the check values do not match.</p>
<p><strong>How to Compute CRC Cyclic Redundancy Check ?</strong></p>
<p>To compute an <i>n</i>-bit binary CRC, line the bits representing the input in a row, and position the (<i>n</i>+1)-bit pattern representing the CRC&#8217;s divisor (called a &#8220;polynomial&#8221;) underneath the left-hand end of the row.</p>
<p>Start with the message to be encoded:</p>
<blockquote>
<pre>11010011101100</pre>
</blockquote>
<p>This is first padded with zeroes corresponding to the bit length <i>n</i> of the CRC. Here is the first calculation for computing a 3-bit CRC:</p>
<blockquote>
<pre>11010011101100 000 &lt;--- input right padded by 3 bits
1011               &lt;--- divisor (4 bits) = x³+x+1
------------------
01100011101100 000 &lt;--- result</pre>
</blockquote>
<p>If the input bit above the leftmost divisor bit is 0, do nothing. If the input bit above the leftmost divisor bit is 1, the divisor is XORed into the input (in other words, the input bit above each 1-bit in the divisor is toggled). The divisor is then shifted one bit to the right, and the process is repeated until the divisor reaches the right-hand end of the input row. Here is the entire calculation:</p>
<blockquote>
<pre>11010011101100 000 &lt;--- input right padded by 3 bits
1011               &lt;--- divisor
01100011101100 000 &lt;--- result
 1011              &lt;--- divisor ...
00111011101100 000
  1011
00010111101100 000
   1011
00000001101100 000
       1011
00000000110100 000
        1011
00000000011000 000
         1011
00000000001110 000
          1011
00000000000101 000 
           101 1
-----------------
00000000000000 100 &lt;---remainder (3 bits)</pre>
</blockquote>
<p>Since the leftmost divisor bit zeroed every input bit it touched, when this process ends the only bits in the input row that can be nonzero are the n bits at the right-hand end of the row. These <i>n</i> bits are the remainder of the division step, and will also be the value of the CRC function (unless the chosen CRC specification calls for some postprocessing).</p>
<p>The validity of a received message can easily be verified by performing the above calculation again, this time with the check value added instead of zeroes. The remainder should equal zero if there are no detectable errors.</p>
<blockquote>
<pre>11010011101100 100 &lt;--- input with check value
1011               &lt;--- divisor
01100011101100 100 &lt;--- result
 1011              &lt;--- divisor ...
00111011101100 100

......

00000000001110 100
          1011
00000000000101 100 
           101 1
------------------
                 0 &lt;--- remainder</pre>
</blockquote>
<p>Let see how to write a C program to implement Cyclic Redundancy Check CRC.</p>
<h1>C program to implement Cyclic Redundancy Check CRC :</h1>
<pre class="brush:cpp">#include&lt;stdio.h&gt;
#include&lt;string.h&gt;
#define N strlen(g)

char t[28],cs[28],g[]="10001000000100001";
int a,e,c;

void xor(){
    for(c = 1;c &lt; N; c++)
    cs[c] = (( cs[c] == g[c])?'0':'1');
}

void crc(){
    for(e=0;e&lt;N;e++)
        cs[e]=t[e];
    do{
        if(cs[0]=='1')
            xor();
        for(c=0;c&lt;N-1;c++)
            cs[c]=cs[c+1];
        cs[c]=t[e++];
    }while(e&lt;=a+N-1);
}

int main()
{
    printf("\nEnter data : ");
    scanf("%s",t);
    printf("\n----------------------------------------");
    printf("\nGeneratng polynomial : %s",g);
    a=strlen(t);
    for(e=a;e&lt;a+N-1;e++)
        t[e]='0';
    printf("\n----------------------------------------");
    printf("\nModified data is : %s",t);
    printf("\n----------------------------------------");
    crc();
    printf("\nChecksum is : %s",cs);
    for(e=a;e&lt;a+N-1;e++)
        t[e]=cs[e-a];
    printf("\n----------------------------------------");
    printf("\nFinal codeword is : %s",t);
    printf("\n----------------------------------------");
    printf("\nTest error detection 0(yes) 1(no)? : ");
    scanf("%d",&amp;e);
    if(e==0)
    {
        do{
            printf("\nEnter the position where error is to be inserted : ");
            scanf("%d",&amp;e);
        }while(e==0 || e&gt;a+N-1);
        t[e-1]=(t[e-1]=='0')?'1':'0';
        printf("\n----------------------------------------");
        printf("\nErroneous data : %s\n",t);
    }
    crc();
    for(e=0;(e&lt;N-1) &amp;&amp; (cs[e]!='1');e++);
        if(e&lt;N-1)
            printf("\nError detected\n\n");
        else
            printf("\nNo error detected\n\n");
            printf("\n----------------------------------------\n");
        return 0;
}</pre>
<p>&nbsp;</p>
<p>Sample Output:</p>
<blockquote><p>Enter data : 1101</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Generatng polynomial : 10001000000100001<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Modified data is : 11010000000000000000<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Checksum is : 1101000110101101<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Final codeword is : 11011101000110101101<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Test error detection 0(yes) 1(no)? : 0</p>
<p>Enter the position where error is to be inserted : 2</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />
Erroneous data : 10011101000110101101</p>
<p>Error detected</p></blockquote>
<p>We hope you all have enjoyed the C program of Cyclic Redundancy check CRC. If you have any doubts ask us in form of comments.</p>
<p>The post <a href="http://www.ccodechamp.com/c-program-to-implement-cyclic-redundancy-check-crc/">C program to implement Cyclic Redundancy Check CRC</a> appeared first on <a href="http://www.ccodechamp.com">C codechamp</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://www.ccodechamp.com/c-program-to-implement-cyclic-redundancy-check-crc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
