Showing posts with label Chapter 5: C Functions. Show all posts
Showing posts with label Chapter 5: C Functions. Show all posts

Friday, March 16, 2012

Math Library Function

Example of the usage of the Math Library function.
/*
   title: mathLibraryFunction
   author: aeriqusyairi
   date: Jan21 2012
*/
#include<stdio.h>
#include<math.h>

int main(){
   //square root
   printf("%.2f\n", sqrt(9));
   
   //exponential function e^x
   printf("%.2f\n", exp(1));
   
   //natural logarithm of x (base e)
   printf("%.2f\n", log(2.718282));
   
   //logarithm of x (base 10)
   printf("%.2f\n", log10(1));
   
   //absolute value of x
   printf("%.2f\n", fabs(-13.5));
   
   //round x to the smallest integer not less than x
   printf("%.2f\n", ceil(9.2));
   
   //round x to the largest integer not greater than x
   printf("%.2f\n", floor(9.2));
   
   //x raised to the power of y
   printf("%.2f\n", pow(2, 7));
   
   //remainder of x/y as a floating point number
   printf("%.3f\n", fmod(13.657, 2.333));
   
   //trigonometric sine of x (x in radian)
   printf("%.2f\n", sin(0.0));
   
   //trigonometric cosine of x (x in radian)
   printf("%.2f\n", cos(0.0));
   
   //trigonometric tangent of x (x in radian)
   printf("%.2f\n", tan(0.0));
   
   system("pause");
   return 0;       
}

Tower of Hanoi

Tower of Hanoi


Example of The Solution of Tower of Hanoi Problem

More about Tower of Hanoi here.
Program below simulate the solver of the legendary Tower of Hanoi.
/*
   title: towerOfHanoi
   author: aeriqusyairi
   date: Jan28 2012
*/
#include&lt;stdio.h&gt;
#include<math.h>

void hanoi( int, char, char, char );

int main(){
   int disk, moves;
   
   printf("Enter the number of disk you want to play with:");
   scanf("%d", &disk);
   
   moves = pow( 2, disk ) - 1;
   
   printf("\nThe number of moves required is = %d\n", moves );
   hanoi(disk, 'A', 'C', 'B' );
   
   system("pause");
   return 0;
}

void hanoi(int x, char from, char to, char temp){
   if( x == 1 )
      printf("Move disk from %c to %c\n", from, to );
   else{
      hanoi(x - 1, from, temp, to );
      printf("Move disk from %c to %c\n", from, to );
      hanoi( x - 1, temp, to, from );     
   }
}

Coin Tossing

Program below simulate coin tossing.The program will "toss" a coin 100 times and print each results and finally print the frequency of each outcome.
[ Note: Each side of the coin appear approximately half the time for a total of approximately 50 heads and 50 tails. ]
/*
   title: tossingCoin
   author: aeriqusyairi
   date: Jan24 2012
*/
#include<stdio.h>
#include<stdlib.h>

int flip(void);

int main(){
   int countHead = 0, countTail = 0, i, x;
   
   for(i = 0; i < 100; i++){
      x = flip();
      if(x == 1){
         printf("Heads\n");
         countHead++;     
      }else if(x == 0){
         printf("Tails\n");
         countTail++;      
      }         
   }       
   
   printf("TOTAL HEAD: %d\nTOTAL TAIL: %d\n", countHead, countTail);
   
   system("pause");
   return 0; 
}

int flip(void){
   
   return rand() % 2;     
}

Thursday, March 15, 2012

Recursive Fibonacci Series

The fibonacci series goes like this:
0, 1, 1, 2, 3, 5, 8, 13, 21
Program below reads user's desired fibonacci position and output the fibonacci value.
/*
   title: fibonacciSeries
   coder: aeriqusyairi
   date: Jan21 2012
*/
#include<stdio.h>

long fibonacci(long n);

int main(void){
   long result;
   long number;
   
   printf("Enter an integer: ");
   scanf("%ld", &number);
   
   result = fibonacci(number);
   
   printf("Fibonacci(%ld) = %ld\n", number, result);
   
   system("pause");
   return 0;
}

long fibonacci(long n){
   if(n == 0 || n == 1)
      return n;
   else
      return fibonacci(n - 1) + fibonacci(n - 2);     
}

Recursive Exponentiation

Program below is similar to the previous exponentiation program except the function execute recursively.
/*
   title: RecursiveExponentiation
   author: aeriqusyairi
   date: Jan24 2012
*/
#include<stdio.h>

int power(int, int);

int main(){
    int number = 0, toPower = 0;
    
    printf("Enter base:");
    scanf("%d", &number);
    printf("Enter exponent:");
    scanf("%d", &toPower);
    
    printf("%d to the power of %d is %d.\n", number, toPower, power(number, toPower));
    
    system("pause");
    return 0;
}

int power(int base, int exponent){
   if(exponent == 1)
      return base;
   else
      return base * power(base, exponent - 1);    
}

Guess the Number

Program below plays the game of "guess the number" as follow:
The program choose the number to be guessed by selecting an integer at random in the range 1 to 1000.Then the player need to guess the number and if incorrect the program will display the clue either your guessed number is too low or too high until the player guessed the correct number.
[Note: The searching technique employed in this problem is called binary search.]
/*
   title: GuessTheNumber
   author: aeriqusyairi
   date: Jan24 2012
*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int randomNumber(void);

int main(){
   int guess = 0, random = 0;
   char replay = 'y';
   
   while(replay == 'y'){
      system("cls");
                
      random = randomNumber();
   
      printf("I have anumber between 1 and 1000.\nCan you guess my number?\nPlease type your first guess.\n");
   
      while(guess != random){
         scanf("%d", &guess);
      
         if(guess > random)
            printf("Too high. Try again.\n");
         else if(guess < random)
            printf("Too low. Try again.\n");            
      }
   
      printf("Excellent! You guessed the number!\nWould you like to play again (y or n)?\n");
      scanf(" %c", &replay);
   }
   
   system("pause");
   return 0;       
}

int randomNumber(void){
   srand(time(NULL));
   
   return 1 + rand() % 1000;                            
}

Time in Seconds

Function calculateSeconds() below take the time as three integer argument (hours, minutes, and seconds) and returns the number of seconds since the last time the clock "struct 12".
/*
   title: timeInSecond
   author: aeriqusyairi
   date: jan24 2012
*/
#include<stdio.h>

unsigned calculateSecond(int, int, int);

int main(){
   int h = 0, m = 0, s = 0, seconds = 0;
   
   printf("Enter time in hour, minute, and second...\nHour: ");
   scanf("%d", &h);
   printf("Minutes: ");
   scanf("%d", &m);
   printf("Seconds: ");
   scanf("%d", &s);
   
   printf("The number of seconds since the last time the clock struck 12 is %u\n", calculateSecond(h, m, s));
   
   system("pause");
   return 0;
}

unsigned calculateSecond(int hours, int minutes, int seconds){   
   return (hours * 3600) + (minutes * 60) + seconds;         
}

Separating Digits

Reads an integer and print back with gap between digit.
Function seperateDigit() execute recursively.
/*
   title: seperatingDigits
   author: aeriqusyairi
   date: jan23 2012
*/
#include<stdio.h>

int seperateDigit(int);

int main(){
   int number = 0;
   
   printf("input an integer:");
   scanf("%d", &number);
   
   seperateDigit(number);
   printf("\n");
   
   system("pause");
   return 0;
}

int seperateDigit(int integer){
   if(integer <= 0){
      return;
   }else{
      seperateDigit( integer / 10 );
      printf("%2d", integer % 10 );   
   }   
}

Displaying a Square of Any Character

Input the side and your desired character and this program will print your desired square out of the character being input.
/*
   title: DisplayingASquareOfAnyCharacter
   author: aeriqusyairi
   date: Jan23 2012
*/
#include<stdio.h>

void displaySquare(char, int);

int main(){
   int side = 0;
   char qwerty;    
   
   printf("Input side:");
   scanf("%d", &side);
   printf("Input character:");
   scanf(" %c", &qwerty);
   
   displaySquare(qwerty, side);
   
   system("pause");
   return 0;
}

void displaySquare(char fillCharacter, int theSide){
   int i, j;
   
   for(i = 1; i <= theSide; i++){
      for(j = 1; j <= theSide; j++){
         printf("%c", fillCharacter);      
      }      
      printf("\n");
   }  
}

Even or Odd

Inputs a series of integers and passes them one at a time to function even, which use the remainder operator to determine if an integer is even.The function return 1 if the ineteger is even and 0 otherwise.
/*
   title: Even || Odd
   author: aeriqusyairi
   date: 23Jan 2012
*/
#include<stdio.h>

int even(int);

int main(){
   int a = 0, b = 0; 
   printf("Input an integer:");       
   scanf("%d", &a);
   
   b = even(a);
   
   if(b == 1)
      printf("%d is an even integer.\n", a);
   else
      printf("%d is not an even integer.\n", a);
   
   system("pause");
   return 0;
}

int even(int number){
   if(number % 2 == 0)
      return 1;
   else
      return 0;    
}

Multiples

Function multiple determines for a pair of integers whether the second integer is the the multiple of the first.
/*
   title: multiples
   author: aeriqusyairi
   date: Jan23 2012
   note: determine whether the second integer is
         the multiple of the first integer
*/
#include<stdio.h>

int multiple(int, int);

int main(){
   int a = 0, b = 0, c = 0;
    
   printf("Input 2 integer...\n1:");
   scanf("%d", &a);
   printf("2:");
   scanf("%d", &b);
   
   c = multiple(a, b);
   
   if(c == 1)
      printf("%d is a multiple of %d\n", b, a);
   else if(c == 0)
      printf("%d is not a multiple of %d\n", b, a);
      
   system("pause");
   return 0;   
}

int multiple(int first, int second){
   if(second % first == 0)
      return 1;
   else
      return 0;     
}

Exponentiation

Function integerPower( base, exponent ) returns the value of baseexponent
/*
   title: exponentiation
   author: aeriqusyairi
   date: Jan23 2012
*/

#include<stdio.h>

double integerPower(int, int);

int main(){
    int a = 0, b = 0;
    double c = 0;
    
    printf("Input base and exponent...\nBase:");
    scanf("%d", &a);
    printf("Exponent:");
    scanf("%d", &b);
    
    c = integerPower(a, b);
    
    printf("The value of %d to the power of %d is %.2lf\n", a, b, c);
    
    system("pause");
    return 0;
}

double integerPower(int base, int exponent){
   int i;
   double result = 1;
   for(i = 1; i <= exponent; i++)
      result*= base;
   return result;       
}

Hypotenuse Calculations

Define a function called hypotenuse that calculates the length of the hypotenuse of a right angle triangle when the other two side are given.
Take two argument of type double and return the hypotenuse as a double.
/*
   title: hypotenuseCalculation
   author: aeriqusyairi
   date: Jan23 2012
*/
#include<stdio.h>
#include<math.h>

double hypotenuse(double, double);

int main(){
   double firstSide = 0, secondSide = 0, hypo = 0;
   
   printf("Enter the side of a right triangle\nto calculate its corresponding hypotenuse...\n");
   printf("Side 1:");
   scanf("%lf", &firstSide);
   printf("Side 2:");
   scanf("%lf", &secondSide);
   
   hypo = hypotenuse(firstSide, secondSide);
   
   printf("The hypotenuse of a right triangle with %.2lf and %.2lf\nas the other 2 side is %.2lf\n",
    firstSide, secondSide, hypo); 
   system("pause");
   return 0;     
}

double hypotenuse(double a, double b){
   double c;
   return sqrt((a * a) + (b * b));        
}

Rounding Numbers

The statement y = floor( x + .5 ); will round the number x to the nearest integer and assign the result to y. Reads a number and print the original number and the rounded number.

/*
   title: roundingNumbers
   author: aeriqusyairi
   date: Jan22 2012
   source: exercise 5.10 Chapter 5
*/
#include<stdio.h>
#include<math.h>

double roundToInteger(double);
double roundToTenths(double);
double roundToHundreths(double);
double roundToThousandths(double);

int main(){
   float number = 0;
   printf("Enter a number to round:"); 
   scanf("%f", &number);
   
   printf("Original number: %.5f\n", number);
   printf("Round to nearest integer: %.5lf\n", roundToInteger(number));
   printf("Round to nearest tenths: %.5lf\n", roundToTenths(number));
   printf("Round to nearest hundreths: %.5lf\n", roundToHundreths(number));
   printf("Round to nearest thousandths: %.5lf\n", roundToThousandths(number));
   
   
   system("pause");
   return 0;      
}

double roundToInteger(double toRound){
   return floor(toRound + .5);       
}

double roundToTenths(double toRound){
   return floor(toRound * 10 + .5) / 10;    
}

double roundToHundreths(double toRound){
   return floor(toRound * 100 + .5) / 100;        
}

double roundToThousandths(double toRound){
   return floor(toRound * 1000 + .5) / 1000;        
}

Parking Charges

Minimum fee: $2.00 up to 3 hour
Additional fee: $0.50 per hour for each hour or part thereof over three hour
Maximum charge: $10.00 for 24 hours
Assumption: No car parked over 24 hours
/*
   title: parkingCharges
   author: aeriqusyairi
   date: Jan22 2012
   source: exercise 5.9 Chapter 5
*/
#include<stdio.h>

float calculateCharges(float);

int main(){
   int i, j;
   float c1 = 0, c2 = 0, c3 = 0,h1 = 0, h2 = 0, h3 = 0, hours = 0, charges = 0;
   
   printf("Enter the hours parked for each customer...\n");
   
   for(i = 1; i <= 3; i++){
      printf("Customer %d: ", i);

      switch(i){
         case 1: scanf("%f", &h1); 
                 c1 = calculateCharges(h1);
            break;
         case 2: scanf("%f", &h2); 
                 c2 = calculateCharges(h2);
            break;
         case 3: scanf("%f", &h3); 
                 c3 = calculateCharges(h3);
            break;  
      }     
   }   
   hours = h1 + h2 + h3;
   charges = c1 + c2 + c3;
    
   printf("%s%10s%10s\n", "Car", "Hours", "Charge");
   for(j = 0; j < 3; j++){
      switch(j){
         case 0: printf("%d.%10.1f%10.2f\n", j + 1, h1, c1); 
            break;
         case 1: printf("%d.%10.1f%10.2f\n", j + 2, h2, c2); 
            break;
         case 2: printf("%d.%10.1f%10.2f\n", j + 3, h3, c3); 
            break;           
      }      
   } 
   printf("%s%7.1f%10.2f\n", "TOTAL", hours, charges);
   
   system("pause");
   return 0;
}

float calculateCharges(float hour){
   float i = 0;
      
   if(hour <= 3)
      return 2;
   else if(hour > 3 && hour <= 24){
      i = ((hour - 3) * 0.5) + 2;
      if(i > 10)
         i = 10;
      return i;      
   }         
}