Archive

Archive for the ‘Programming’ Category

Randomness & A "True" Random Number Generator

March 20th, 2012 No comments

There are various algorithms that are used to generate random numbers. But the question is - Are these numbers truly random if there are being generated by an algorithm? That is, we could repeat the algorithm to regenerate the random number. Since it's an algorithm, there has to be a pattern and hence, the numbers will not be random.

randomness

For example, an algorithm might use the digits of a transcendental number like pi to generate random numbers. This is done by taking the digits of pi at regular intervals. Consider the value of pi upto a few decimal places : 3.1415926535897932384626.
Now, the algorithm would generate a random number 1(1st digit after the decimal place), then the next time, generate 5(the 4th digit after the decimal), then 6(the 7th digit), and then the 10th digit and so on.

The algorithm is hence a pseudo-random generator and not a true random generator. In fact, it is a pi-random generator since it uses the value of pi to generate randomness - or perhaps, pseudo-randomness. Hence, all algorithms need to use some reference to generate randomness and hence, they are all pseudo-random generators and not true random generators.

However, we can make the pseudo-randomness to be drived from more random sources (more random than the digits of pi) to approximate true randomness. The method used by this random number generator tool (by random.org) is atmospheric noise which makes it more random than the other algorithms. Try out the tool here to generate true randomness:

Decimal to Binary Converter in C

October 10th, 2011 1 comment

This program converts decimal to binary numbers. It works for positive integers 0-127. To see how conversions between number systems work, read the post on The Decimal, Binary, Octal & Hexadecimal Number Systems

Executable - Download decimal2binary.exe

Code -

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

/* program to convert decimal to binary
- works for positive numbers 0-127 */

int main()
{
    int x, i=0;
    printf("Enter the decimal number\n");
    scanf("%d", &x);
    int y=x;
    int j=0;
    /* this loop gets a count of the number of bigits/remainders */
    while(x!=0)
    {
      i=x%2;
      x=x/2;
      j++;
    }
    x=y;
    int n=0, a[n];
    /* second loop feeds values of bigits to array */
    while(n<j && x!=0)
    {
      i=x%2;
      x=x/2;
      a[n]=i;
      n++;
    }
    n=0;
    printf("The binary equivalent is ");
    /* third loop prints the reversed array */
    while(n<j)
    {
      printf("%d", a[j-(n+1)]);
      n++;
    }
    getch();
    return 0;
}

Calender Program in C

October 9th, 2011 No comments

Found this question on a C Programming Fan Page on Facebook. Decided to give it a shot.

Problem Statement : Write A Program that receives the month and year from the keyword as integers & prints the calendar in the following format.

Input : Month, Year

Output:
Mon Tue Wed Thu Fri Sat Sun
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31


Adding a link to the first executable. Will post the source code soon - needs some big time improvement.

Note - It doesn't work for certain leap years. Will fix it and update soon.

Download - calender.exe

ASCII Values & Table Generator in C

August 1st, 2011 2 comments

What are ASCII values? Why are they needed?
We are all aware of the fact that all computers understand is 0 & 1 - and everything else is stored as patterns containing 0's and 1's. Some of us also know that numbers like 25, 12, etc can be represented as patterns of 0's & 1's. The computer interprets 25 as 11001 and 12 as 1100.  But how does it interpret a  sentence like "My name is K" or a word like "name" or a letter like "K"? Also, how does it know the difference between 'k' & 'K'?

This is where ASCII values come in. Each character (including a space) has a certain corresponding number associated to it. And there are different numbers assigned to the lower and upper case of the same alphabet.  For instance, the letter 'a' corresponds to the number 97 while 'A' corresponds to the number 65.

An ASCII table maps the characters to the numbers. Apart from the equivalent decimal representation, it also gives the hexadecimal and octal representations of the character.

This is what the ASCII table looks like -

ascii value table

Here's a little tool that can help you experiment with ASCII values.

What's it got to do with programming?

Now, the more important question. What has your programming got to do with ASCII values?
To begin with, have a look at the following C code -

main()
{
char c;
printf("Enter any character\n");
scanf("%c", &c); /*scans a character */
printf("%d", c); /* prints a decimal */
getch();
}

It scans a character and returns an integer. Do you think the code is incorrect? Try compiling it. It does return a number for every character. And what is this number? Exactly, the decimal ASCII value of the character. Don't believe me? That's what the table is for.

Note that %d is responsible for giving us the corresponding decimal value from the ASCII table. We could similarly use %x to hexadecimal and %o for octal values corresponding to the character.

Now, we could try doing it the other way round. Input a number and get the corresponding character, that is.

main()
{
int d;
printf("Enter any number\n");
scanf("%d", &d); /* scans a decimal */
printf("%c", d); /* prints a character */
getch();
}

That's not it. We may even generate the complete column for a character from the ASCII table. All we need to do is print the dec, hex and oct equivalents for the input character.

main()
{
char c;
printf("Enter any character\n");
scanf("%c", &c); /*scans a character */
printf("%d\t", c); /* prints dec */
printf("%x\t", c); /* prints hex */
printf("%o", c); /* prints oct */
getch();
}

Now, we can easily use a loop to generate the complete ASCII table. The above table ends at the dec value 127. However, the extended ASCII table is defined to the decimal value 255(ie - it has 256 values). See this link for the extended ASCII table.

#include <stdio.h>
#include <conio.h>
/* program to generate the complete ASCII table */
main()
{
int x;
for(x=1;x<=255;x++)
{
printf("\n%c\t", x); /* prints char */
printf("%d\t", x); /* prints dec */
printf("%x\t", x); /* prints hex */
printf("%o", x); /* prints oct */
}
getch();
}

You can now try experimenting with ASCII values, decimal, hex, octal and characters. Good Luck!
{Btw, Just to let you know - ASCII stands for American Standard Code for Information Interchange}

 

Logic to Find Exponents with Integral Powers

July 22nd, 2011 No comments

If you've noticed, In C Programming, you cannot use a^b directly to find the value of an exponent. Although, there is a pow(a, b) function that gives you the result. But, it's always nice to work with the basic logic.

If you look at the definition of an exponential:

"Exponentiation is a mathematical operation, written as a^n. When n is a positive integer, exponentiation corresponds to repeated multiplication." - Wikipedia

We're gonna work out our logic using this very basic definition [especially the part where it says - exponentiation corresponds to repeated multiplication ;)]

Code:

main()
{
int base, index;
printf("Enter the base\n"); /* say, 2 */
scanf("%d", &base);
printf("Enter the index\n"); /* say, 3 */
scanf("%d", &index);

/* always remember that 2^3 is actually 2x2x2 ie-2 multiplied by itself 3 times */

int i;
int power=base; /* power is initiallized to 2 */
for(i=1;i<index;i++)
{
power=power*base; /* 1st loop : power = 2*2, 2nd loop : power =(2*2)*2 */
}

printf("\n%d", power);
getch();
}

It's pretty easy to understand using an example. Refer to the example in comments to see how the code works. Also, this is not the only way. Think of how you could achieve the same with a different (and perhaps, better) code.

Basic Quiz Program in C

July 21st, 2011 No comments

This is a program for a simple quiz on the C Programming Language. It can be modified to be made into a quiz on any topic. It includes negative marking for wrong answers, keeps track of the score & displays it at the end of the quiz.

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

main()
{
int score=0;
int answer;

printf("Welcome to the C quiz\nThe quiz has 5 very basic questions on the C Programming Language. You get +3 for each correct answer & -1 for each wrong/invalid answer.\n");

printf("\nQ1) Why is it called 'C' & not 'D'?\n");
printf("[1]C stands for code\t[2]The inventor's name started with a C\n[3]It developed after a language called 'B'\t[4]Why should I care?\n");
scanf("%d", &answer);

if(answer==3)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nQ) It was developed at?\n");
printf("[1]IBMt[2]Bell Labsn[3]MITt[4]Microsoft(?)\n");
scanf("%d", &answer);

if(answer==2)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("nQ) Which of these is not a C keyword as per ANSI C ?\n");
printf("[1]externt[2]volatilen[3]entert[4]break\n");
scanf("%d", &answer);

if(answer==3)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("nQ) What is ANSI, btw? ?\n");
printf("[1]Area of Natural and Scientific Interest\t[2]American National Standards Institute\n[3]American National Standardization Institute\t[4]American National Society Of Intellectuals\n");
scanf("%d", &answer);

if(answer==2)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nQ)Which of these concepts is NOT supported by C ?\n");
printf("[1]Pointers\t[2]Functions\n[3]Strings\t[4]Namespaces\n");
scanf("%d", &answer);

if(answer==4)
{
printf("That's Correct!\n");
score=score+3;
}
else
{
printf("Wrong Answer\n");
score=score-1;
}

printf("\nThank You for taking the Quiz.\n Your Total Score is %d out of 15", score);

getch();

}

Download the Application (.exe)

Personal Fitness & Weight Analyzer in C

July 20th, 2011 No comments

This C Program Analyzes if you're underweight, overweight or obese and accordingly suggests you to gain or lose the right amount of weight in the right period of time.

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

main()
{
int weight;

printf("Welcome to your Weight Analyser\n");
printf("To begin, Enter your current weight in pounds(lbs)\n\n");
scanf("%d", &weight);

printf("You currently have %d calories inside you.. In other words, If you lose %d calories, you'll dissapear altogether ;) Just Sayin!\n\n", weight*(3500), weight*(3500));

int height_ft, height_in;

printf("Now, to calculate your ideal weight, Enter your height.. How many feet?)n");
scanf("%d", &height_ft);
printf("And inches?nn");
scanf("%d", &height_in);

int bmi=(703*weight)/pow(((height_ft)*12+(height_in)),(2));

if(bmi<18.5)
{
printf("You're underweight, You need to gain weight.. How does that feel?\n");
}

else if(18.5<bmi && bmi<25)
{
printf("You don really need to lose any weight, Your height and weight are in proportion! :)\n");
}

else
{
if(25<bmi && bmi<30)
{
printf("You're overweight! :) Let's see what I can do you make you live longer and happier :).. \n\n");
}
else
{
printf("How do you even breathe? You're obese and sick! But I can help.\n\n");
}

int ideal_weight=(24.9/703)*(pow(((height_ft)*12+(height_in)),(2)));

printf("Considering your height will not increase anymore, For your ideal weight, You should reduce to %d \n\n", ideal_weight);
printf("Which means you'll need to shed %d pounds\n\n", weight-ideal_weight);
printf("For healthy weight loss, you should take %d days to do this by losing 500 calories each day\n\n", 7*(weight-ideal_weight));
printf("To do this, make sure that the calories you burn everyday are 500 more than the total calories you take in everyday.\n Good Luck \n");

}
getch();

}

Download the Application (.exe)

Arithmetic Progression Generator in C

July 20th, 2011 No comments

This application generates an AP series using a while loop by specifying the first term, common difference and the number of terms.

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

int main(void)
{
int repeat=1;

while(repeat==1)
{

int a, d, n;
printf("Enter first term\n");
scanf("%d", &a);
printf("Enter the common difference\n");
scanf("%d", &d);
printf("Enter number of terms\n");
scanf("%d", &n);

while(n>0)
{
printf("%dt", a);
a=a+d;
n=n-1;
}

printf("\n\nRepeat[1]\nExit[0\]n");
scanf("%d", &repeat);
}
getch();
}

Download the Application (.exe)

Basic Menu-Based Calculator in C

July 20th, 2011 No comments

Here's the code for a Basic Calculator Using Switch Statements:

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

int main(void)
{
int a, b;
int repeat=1;
printf("Welcome to the C calculator\nEnter any two numbers\n");
scanf("%d%d", &a, &b);

while(repeat==1)
{
int choice;
printf("Choose the operation to be performed\nDivision[1]\nMultiplication[2]\nAddition[3]\nSubtraction[4]\n");
scanf("%d", &choice);

int result;
switch(choice)
{
case 1:
result = a/b;
printf("The quotient is %d", result);
break;
case 2:
result = a*b;
printf("The product is %d", result);
break;
case 3:
result = a+b;
printf("The sum is %d", result);
break;
case 4:
result = a-b;
printf("The difference is %d", result);
break;
default:
printf("Please enter a valid choice");
break;
}
printf("\nRepeat[1]\nExit[0]n");
scanf("%d", &repeat);
}
getch();
}

Download the Application (.exe)

[C Tutorial 6] Performing Operations on the Input

July 4th, 2011 No comments

Once we get the input(s) from the user [Tutorial 5], it is time to modify the input by performing operations on it. The basic idea of coding is to design systems which perform various functions. And a function is nothing but a machine that gives output values for various input values.

Since our basic aim is to implement functions, we need to perform operations on the inputs to get outputs. Now, suppose you had to code a basic machine that adds 5 to the input.

function

You will need to:

Step 1 : Get an input value from the user

Step 2 : Add 5 to the input

Step 3 : Display output to the user

Method 1 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

int y;
y=x+5; /* Step 2 */
printf("The output is %d", y); /* Step 3 */
getch();
return 0;
}

In the above method, we have used two variables. x for the input and y for the output. However, we can add 5 to change the input itself and display it as the output (this is the power of programming, the otherwise constant inputs are variables in a program)

Method 2 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

x=x+5; /* Step 2 */
printf("The output is %d", x); /* Step 3 */
getch();
return 0;
}

Now, don't get confused when you see x=x+5; Just remember the following thumb rule :

In programming, the value on the right hand side(called the rvalue replaces the value on the left hand side(called the lvalue). In this case, (x+5) replaces x. hence, the new value of x is (x+5).

For a more elegant code, we could perform the addition in the printf function itself.

Method 3 -

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

int main()
{
int x;
printf("Enter any number\n"); /* Step 1 */
scanf("%d", &x);

printf("The output is %d", x+5); /* Steps 2 & 3 */
getch();
return 0;
}

In this case, the steps 2 and 3 can be implemented in a single line. As you will realize later, this is what programming is all about. A lot of people can program, but only a few can come up with the most elegant solution. And the most elegant one wins.

Note - in the above program, we did not have to define the "+" operator. It is one of the pre-defined C operators. C has a number of mathematical, logical and other operators. (discussed later)