Sum , factorial

/\*sum upto n numbers\*/ 

public static int Sum(int n)
{
int result = 0;
for (int i = 1; i <= n; ++i)
result += i;
return result;
}

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 <iostream> #include <iomanip> #include <cctype> using namespace std; //--- prototypes void countValue(int cnt); float getAverage(); //--- constants const int BINS = 21; // how many numbers can be counted //--- globals int valueCountBINSBINS; // 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 valueCountii = 0; } //--- Read chars in loop and decide if in a word or not. [Read More]

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. [Read More]

Calculate pow function

Lets look at some solutions. Solution 1 - Using recursion int pow(int x, int y) { if(y == 1) return x ; return x \* pow(x, y-1) ; } Divide and Conquer C program /\* Function to calculate x raised to the power y \*/ int power(int x, unsigned int y) { if( y == 0) return 1; else if (y%2 == 0) return power(x, y/2)\*power(x, y/2); else return x\*power(x, y/2)\*power(x, y/2); } /\* Program to test function power \*/ int main() { int x = 2; unsigned int y = 3; printf("%d", power(x, y)); getchar(); return 0; } Time Complexity: O(n) [Read More]