Showing posts with label udf. Show all posts
Showing posts with label udf. Show all posts

Wednesday, September 1, 2010

Word Length Frequency

// word_len_histo.cpp : reads words and lists distribution
// of word lengths.
// Fred Swartz, 2002-09-01

// This would be nice to turn into an OO program, where
// a class represented a distribution of values.
// Some elements which are globals here would turn into
// private member elements in the class (eg, valueCount).


//--- includes
#include
#include
#include
using namespace std;

//--- prototypes
void countValue(int cnt);
float getAverage();

//--- constants
const int BINS = 21; // how many numbers can be counted

//--- globals
int valueCount[BINS]; // bins used for counting each number
int totalChars = 0; // total number of characters

//=========================================================== main
int main() {

char c; // input character
int wordLen = 0; // 0 if not in word, else word length

//--- Initialize counts to zero
for (int i=0; i
valueCount[i] = 0;
}

//--- Read chars in loop and decide if in a word or not.
while (cin.get(c)) {
if (isalpha(c)) { // letters are in words, so
wordLen++; // add one to the word length
} else {
countValue(wordLen); // end of word
wordLen = 0; // not in a word, set to zero
}
}
countValue(wordLen); // necessary if word ended in EOF

//--- print the number of words of each length
cout << "Why does this line disappear?" << endl;
cout << "Word length Frequency" << endl;
for (int j=1; j
cout << setw(6) << right << j << " "
<< setw(8) << right << valueCount[j] << endl;
}

//--- print average length
cout << "\nAverage word length: " << getAverage() << endl;

return 0;
}//end main


//==================================================== countValue
void countValue(int cnt) {
if (cnt > 0) {
// this must be the end of a word
if (cnt > 20) {
cnt = 20; // longer than 20 counts as 20
}
valueCount[cnt]++; // count in correct bin
}
totalChars += cnt;
}//end countWord


//==================================================== getAverage
float getAverage() {
int totalCount = 0;

for (int i=0; i
totalCount += valueCount[i];
}
if (totalCount > 0) {
return (float)totalChars/totalCount;
} else {
return 0.0;
}
}//end getAverage

Taking input as string 1 - " C-String to Int "

Converting C-Strings to Integer

If you want to convert a C-string (zero-terminated array of chars) of digits, you can call one of the library functions to do this (good idea), or write something like the following (good exercise).

Character codes for digits

Every character is represented by a pattern of bits. These patterns can be thought of as integers. If your system uses ASCII (or any of the newer standards), the integer value of the code for '0' is 48, '1' is 49, etc. This knowledge is commonly used when converting character digits to their equivalent values.

Example function to convert C-strings to int

One of the problems to solve immediately is what to do with errors. Let's make this a bool function that returns true if we can convert the string (eg, no illegal characters), and false otherwise. We'll pass the value back in a reference parameter.

The code

//============================================== string2int
bool string2int(char* digit, int& result) {
result = 0;

//--- Convert each digit char and add into result.
while (*digit >= '0' && *digit <='9') {
result = (result * 10) + (*digit - '0');
digit++;
}

//--- Check that there were no non-digits at end.
if (*digit != 0) {
return false;
}

return true;
}

Thursday, August 5, 2010

Writing log file in c++

void saveLog(int n,double timeelapsed1,double timeelapsed2)
{

ofstream SaveFile("logsort.txt",ios::app);
SaveFile << "No. of elements : "<<n<<endl;
SaveFile << "Time taken by bubblesort : "<<timeelapsed1<<endl;
SaveFile << "Time taken by quicksort : "<<timeelapsed2<<endl;
SaveFile.close();

}

Tuesday, August 3, 2010

Some udfs for arrays in cpp

void printArray (int *array,int size)
{
int i;
for (i = 0; i <= size; i++)
cout << array[i] << " ";
cout << endl;
}

Wednesday, July 28, 2010

Some udfs for arrays in c

1D arrays
Printing 1 D arrays
void printArray (int *array,int size)
{
int i;
for (i = 0; i < size; i++)
     printf("%d",array[i]);
printf("\n");
}
2 D arrays 
Printing 2D arrays
void printArray(int **array, int m, int n)
{
           for(i = 0; i < nrows; i++)  
              for(j= 0; j < nrows; i++)  
                         printf("%d",array[i][j]);
}

Allocating and Deallocating 2 D Arrays 

/*   allocate2D
/*   function to dynamically allocate 2-dimensional array using malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows and
/*   columns.
*/
void allocate2D(int** array, int nrows, int ncols) {
     
     /*  allocate array of pointers  */
     array = ( int** )malloc( nrows*sizeof( int* ) );
     
     /*  allocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          array[i] = ( int* )malloc( ncols*sizeof( int ) );
     }
}
/*   deallocate2D
/*   corresponding function to dynamically deallocate 2-dimensional array using
/*   malloc.
/*
/*   accepts an int** as the "array" to be allocated, and the number of rows. 
/*   as with all dynamic memory allocation, failure to free malloc'ed memory
/*   will result in memory leaks
*/
void deallocate2D(int** array, int nrows) {
     
     /*  deallocate each row  */
     int i;
     for(i = 0; i < nrows; i++) {
          free(array[i]);
     }
     
     /*  deallocate array of pointers  */
     free(array);
     
}
/*   EXAMPLE USAGE:   
int** array1;

allocate2D(array1,1000,1000); //allocates a 1000x1000 array of ints

deallocate2D(array1,1000);    //deallocates the same array

*/

Friday, November 27, 2009

pow function

Brute force C program


int pow(int x, int y)
{
  if(y == 1) return x ;
  return x * pow(x, y-1) ;
}



Divide and Conquer C program


#include 
int main(int argc, char*argv[])
{
  printf("\n[%d]\n",pow(5,4));
}

int pow(int x, int n)
{
  if(n==0)return(1);
  else if(n%2==0)
  {
    return(pow(x,n/2)*pow(x,(n/2)));
  }
  else
  {
    return(x*pow(x,n/2)*pow(x,(n/2)));
  }
}