Friday, June 22, 2007

Maxiumum subsequence problem

Problem:
Given (possibly negative) integers A1,A2,...An, find the maxiumum value of the sub array.

Solution:


#include <stdio.h>

#define SIZEOF(arr) (sizeof(arr)/sizeof(arr[0]))

int arr[] = { 2, -3, 4, -1, 5, -1, -3, 6, -1, -1, -4, 2, -1};

void MaxSum(int arr[],int length)
{
int max,sum;
int i = 0 ;

max = sum = arr[0];

for(i=1;i<length;i++)
{
sum += arr[i];
if(sum > max)
{
max = sum;
}

if(sum < 0)
{
sum = 0;
}
}
printf("The max sum is : %d\n",max);
}


void PrintArray(int arr[],int size)
{
int i;
for(i=0;i<size;i++)
printf("%d ",arr[i]);
printf("\n");
}

int main()
{
PrintArray(arr,SIZEOF(arr));
MaxSum(arr,SIZEOF(arr));
return 0;
}

Tuesday, June 12, 2007

Character to number conversion

Problem:
Given the character representation of an integer convert it into its conventional decimal front.

Solution:

Note : This is the minimal version of the standard C library function atoi.

#include <stdio.h>
#include <string.h>


/* converts character string integer representation to decimal */
int chrtodec(char* string, int n)
{
int i; /* index for count of characters converted */
int dec; /* used to build converted decimal integer */
int base0; /* ascii or ordinal value of character 0 */

dec = 0;
base0 = '0';

for(i=0;i<n;i++)
dec = dec * 10 + string[i]-base0;
return dec;
}

int main()
{
char str[80];
printf("Enter the string : ");
scanf("%s",str);

printf(" chrtodec(%s) is %d\n",str,chrtodec(str,strlen(str)));
return 0;
}