Skip to main content

C PROGRAM SAMPLES

SAMUEL ADDA   -   215ETK1100072
PROGRAMMING WITH C
ASSIGNMENT

Valley View University

  5.9   (Parking Charges) A parking garage charges a $2.00 minimum fee to park for up to three
hours and an additional $0.50 per hour for each hour or part thereof over three hours. The maximum
charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours
at a time. Write a program that will calculate and print the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each
customer. Your program should print the results in a tabular format, and should calculate and print
the total of yesterday's receipts. The program should use the function calculate Charges to determine the charge for each customer. Your outputs should appear in the following format:
customer   hrs          charge
1            1.5             2.00
2            4.0             2.50
3            24.0           10.00
TOTAL  29.5            14.50



ANSWER TO 5.9


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

    // THIS PROGRAM WILL CALCULATE CAR PARKING CHARGES
int main(void)
{
 
  float charge1;
  float  charge2;
  float charge3;
  float totalcharge;
  float totalhours;
  float hours1, hours2, hours3;
  float bonus=2.00;        // the charge for hours from 0 - 3.
  float high=10.00;        // the charge for parking for 24 hours.
 
 
  printf("enter customer1 hours\n");//prompt user
  scanf("%f",&hours1);//accept integer
 
  printf("enter customer2 hours\n");//prompt user
  scanf("%f",&hours2);//accept integer
 
  printf("enter customer3 hours\n");//prompt user
  scanf("%f",&hours3);//accept integer
 
  totalhours = hours1 + hours2 + hours3;
 
 
      if(hours1<=3){
        charge1=bonus;
        }
        else
   if(hours1>3 && hours1<24){
     charge1=bonus +( (hours1 - 2) * 0.5);
     }
     else
 
   if(hours1==24){
        charge1= high;
        }      
 
 
      if(hours2<=3){
        charge2=bonus;
        }
        else
   if(hours2>3 && hours2<24){
     charge2=bonus +((hours2 - 2) * 0.5);
     }
     else
 
   if(hours2==24){
        charge2=high;
        }      
 
 
      if(hours3<=3){
        charge3=bonus;
        }
        else
   if(hours3>3 && hours3<24){
     charge3=bonus +( (hours3 - 2) * 0.5);
     }
     else
   
 
   if(hours3==24){
        charge3=high;
        }      
      //end if    
       totalcharge= charge1 + charge2 + charge3;
 
       
   printf("    Customer    Hours     CalculatedCharge\n");
 
   printf("\t1\t%.2f\t\t%.2f\n",hours1, charge1);
 
   printf("\t2\t%.2f\t\t%.2f\n",hours2, charge2);
 
   printf("\t3\t%.2f\t\t%.2f\n\n",hours3, charge3);
 
   printf("\tTotal\t%.2f\t\t%.2f\n\n",totalhours, totalcharge);

  system("pause");
  return 0;
}
//end main











5.10   (Rounding Numbers)   An application of function floor is rounding a value to the nearest
integer. The statement
y = floor( x + .5);
will round the number x to the nearest integer and assign the result to y. Write a program that reads
several numbers and uses the preceding statement to round each of these numbers to the nearest
integer. For each number processed, print both the original number and the rounded number.



ANSWER TO 5.10

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

  //THIS PROGAM WILL ROUND NUMBERS TO THE NEAREST INTEGER
 
int main (void)
{
    float number1;
    float number2;
    float number3;
    float number4;
    float number5;
    float number6;    // initialisation stage
   
     
    float a1;
    float a2;
    float a3;
    float a4;
    float a5;
    float a6;
   
   
               // accepting numbers to be converted.
             
    printf("Enter six diferent numbers to be rounded to the nearest integer\n\n");
    scanf("%f%f%f%f%f%f", &number1,&number2, &number3,&number4,&number5,&number6);
   
    printf("\n\n");
   
    a1=floor(number1 +.5);      // declaration of floor.
    a2=floor(number2 +.5);
    a3=floor(number3 +.5);
    a4=floor(number4 +.5);
    a5=floor(number5 +.5);
    a6=floor(number6 +.5);
   
   

   
   
    printf("Number1:\t%f\tRounded:\t%f\n", number1,a1);
     printf("Number2:\t%f\tRounded:\t%f\n", number2,a2);
      printf("Number3:\t%f\tRounded:\t%f\n", number3,a3);
       printf("Number4:\t%f\tRounded:\t%f\n", number4,a4);
        printf("Number5:\t%f\tRounded:\t%f\n", number5,a5);
         printf("Number6:\t%f\tRounded:\t%f\n", number6,a6);
       
       
         system ("pause");
    return 0;
}
//end main



5.17 (Multiples)   Write a function multiple that determines for a pair of integers whether the second integer is a multiple of the first. The function should take two integer arguments and return 1
(true) if the second is a multiple of the first, and 0(false) otherwise. Use this function in a program
that inputs a series of pairs of integers.



ANSWER  TO 5.17



#include <stdlib.h>
#include <stdio.h>



int main(int argc, char *argv[])
{
   
//declaration of variables
   int number1;    
   int number2;
 
  printf("\n");
 
 
   printf("%s","Enter number1 and number2( 0 and 0 to end)\n\n");//prompts user
   scanf("%d%d",&number1,&number2);//accepts integer
 
    while(number1 !=0 && number2 !=0) {
           
   if(number2%number1==0){
                    printf("\t\t1\n\n"); }    // 1 means second number is a multiple of first number
                    else
                    {
                    printf("\t\t0\n\n");      // 0 means second number is not a multiple of first number
                   
                    }
   
 
   printf("%s","Enter num1 and num2( 0 and 0 to end)\n\n");
   scanf("%d%d",&number1,&number2);
}
 
    system("pause");
    return 0;
}
//end main






5.18 (Even or Odd)   Write a program that inputs a series of integers and passes them one at a time
to function even, which uses the remainder operator to determine whether an integer is even. The function should take an integer argument and return 1 if the integer is even and 0otherwise.



ANSWER TO 5.18


#include <stdlib.h>
#include <stdio.h>

// THIS PROGRAM WILL DETEMINE WHETHER A NUMBER IS ODD(0) OR EVEN(1)

int main(int argc, char *argv[])
{
   

   int integer;   //declaration of variables
 
 
  printf("\n");
 


 
 
   printf("%s","Enter the integer( 0 to end)\n\n");//prompts user
   scanf("%d",&integer);//accepts integer
 
    while(integer!=0) {
           
   if(integer%2==0){
                    printf("\t\t1\n\n"); }    // 1 means integer is an even integer.
                    else
                    {
                    printf("\t\t0\n\n");      // 0 means integer is an odd integer.
                   
                    }
   
   
   printf("%s","Enter the integer( 0 to end)\n\n");
   scanf("%d",&integer);
}
 
    system("pause");
    return 0;
}
//end main







6.26 (Eight Queens) Another puzzler for chess buffs is the Eight Queens problem. Simply stated:
Is it possible to place eight queens on an empty chessboard so that no queen is “attacking” any other—that is, so that no two queens are in the same row, the same column, or along the same diagonal?
Use the kind of thinking developed in Exercise 6.24 to formulate a heuristic for solving the Eight
Queens problem. Run your program. [Hint:It’s possible to assign a numeric value to each square
of the chessboard indicating how many squares of an empty chessboard are “eliminated” once a
queen is placed in that square. For example, each of the four corners would be assigned the value
22, as in Fig. 6.27.]
Once these “elimination numbers” are placed in all 64 squares, an appropriate heuristic might
be: Place the next queen in the square with the smallest elimination number. Why is this strategy
intuitively appealing?


ANSWER TO  6.26


#include <stdio.h>
#include <stdlib.h>

int *x, count = 0;


int Place(int k, int i)
{
        int j;
   
    for(j = 0; j < k-1; j++)
       if( (x[j] == i) || (abs (x[j] - i) == abs(j - k)) )
         return 0;
        return 1;
}



void NQueens(int k, int n)
{
        int i,loop;
   
    for(i = 0; i <= n; i++)
    {
       if( Place(k,i) )
       {
          x[k] = i;
          if(k == n)
          {
            for(loop = 0; loop < n; loop++)
              printf("%u  ", x[loop] );
            printf("\n");
            count++;
            return ;
          }              
          else
            NQueens(k+1,n);
       }
    }
}  
                   

int main()
{
        int n;
   
    printf("Enter the size of the chessboard : ");
    scanf("%u",&n);
   
    x = (int*)calloc(n,sizeof(int));
       
    printf("\nThe solutions to the problem are :- \n\n");
    NQueens(0,n-1);
   
    printf("count : %d",count);
     system("pause");
    return 0;
}
//end main






6.36 (Print a String Backward) Write a recursive function stringReverse that takes a character
array as an argument, prints it back to front and returns nothing. The function should stop processing and return when the terminating null character of the string is encountered.

ANSWER TO 6.36

#include <stdio.h>
#include <stdlib.h>
 //THIS PROGRAM WILL REVERSE A STRING
   void printStringRev( char *s )
  {
   if( s && *s )
   {
      printStringRev( s + 1 );               // Reverse string.
      fputc( *s, stdout );
    }
  }

  int main( void )
  {
   char buf[1024]={0};

   puts("\n\t Enter the text message to be reversed:\n");   // accepting text
   fgets( buf, 1024, stdin );
   printStringRev( buf );


   system("pause");
   return 0;
  }
//end main







6.37 (Find the Minimum Value in an Array) Write a recursive function recursiveMinimum that
takes an integer array and the array size as arguments and returns the smallest element of the array.
The function should stop processing and return when it receives an array of one element.

ANSWER TO 6.37


#include <stdio.h>
#include<stdlib.h>
int min(int *arr,int size)
{
    static int *m;

    if(!m) m=arr;

    return size ? ( *m>*++arr ? min((m=arr),size-1) : min(arr,size-1) ) : *m;
}

int main(void)
{
    int i,size;

    printf("Enter Array Size:\n\n");
    scanf("%d",&size);

    int arr[size];

    printf("Enter Array Elements:\n\n");
    for(i=0;i<size;i++)
    scanf("%d", arr+i);

    printf("The Minimum no. is %d\n\n",min(arr,size));

 system("pause");
    return 0;
}
//end main






6.38 (Project: Sudoku Puzzles )In Appendix D, Game Programming: Solving Sudoku, we’ll discuss various simple solution strategies and suggest what to do when these fail. We’ll also present various approaches for programming Sudoku puzzle creators and solvers in C. Unfortunately, Standard
C does not include graphics and GUI (graphical user interface) capabilities, so our representation
of the board won’t be as elegant as we could make it in Java and other programming languages that
support these capabilities. You may want to revisit your Sudoku programs after you study a game
programming library such as Allegro, which offers capabilities that will help you add graphics and
even sounds to your Sudoku programs.
Be sure to check out our Sudoku Resource Center at www.deitel.com/sudokufor downloads,
tutorials, books, e-books and more that will help you master the game. And—not for the faint of
heart—try fiendishly difficult Sudokus with tricky twists, a circular Sudoku and a variant of the
puzzle with five interlocking grids.



ANSWER TO 6.38


#include <iostream>
#include <algorithm>
#include <ctime>
#include <cmath>

bool solve_recursive(unsigned full[9][9], int r, int c,
    unsigned candidates[9][9][9], unsigned row[9], unsigned col[9], unsigned box[9])
{
    ++c;
    if (c == 9) {
        ++r;
        c = 0;
        if (r == 9)
            return true;
    }

    if (full[r][c])
        return solve_recursive(full, r, c, candidates, row, col, box);

    int b = r - r % 3 + c / 3;

    unsigned free = 511 ^ (row[r] | col[c] | box[b]);
    if (!free) return false;
    for (int i = 0; i < 9; ++i) {
        if (candidates[r][c][i] & free) {
            row[r] |= candidates[r][c][i];
            col[c] |= candidates[r][c][i];
            box[b] |= candidates[r][c][i];
            full[r][c] = candidates[r][c][i];
            if (solve_recursive(full, r, c, candidates, row, col, box))
                return true;
            row[r] ^= candidates[r][c][i];
            col[c] ^= candidates[r][c][i];
            box[b] ^= candidates[r][c][i];
            full[r][c] = 0;
        }
    }
    return false;
}

bool generate_random_solution(unsigned full[9][9])
{
    unsigned candidates[9][9][9];
    unsigned row[9] = {0}, col[9] = {0}, box[9] = {0};

    for (int r = 0; r < 9; ++r) {
        for (int c = 0; c < 9; ++c) {
            for (int i = 0; i < 9; ++i) {
                candidates[r][c][i] = 1 << i;
            }

            std::random_shuffle(candidates[r][c], candidates[r][c]+9);
            full[r][c] = 0;
        }
    }

    return solve_recursive(full, -1, 8, candidates, row, col, box);
}


int main()
{
    srand(time(0));
    unsigned puzzle[9][9];
    generate_random_solution(puzzle);

    for (int i = 0; i != 9; ++i) {
        for (int j = 0; j != 9; ++j) {
            std::cout << log2(puzzle[i][j])  + 1 << ' ';
        }
        std::cout << '\n';
    }
    system("pause");
}
//end main





Comments

Popular posts from this blog

PROGRAMMING WITH C 7.12      (Card Shuffling and Dealing) Modify the program in Fig. 7.24 so that the card-dealing function deals a five-card poker hand. Then write the following additional functions: a) Determine whether the hand contains a pair. b) Determine whether the hand contains two pairs. c) Determine whether the hand contains three of a kind (e.g., three jacks). d) Determine whether the hand contains four of a kind (e.g., four aces). e) Determine whether the hand contains a flush (i.e., all five cards of the same suit). f) Determine whether the hand contains a straight (i.e., five cards of consecutive face values) ANSWER 7.12 #include<stdio.h> #include<stdlib.h> #include<time.h> //main functions void shuffle( int wDeck[][ 13 ] ); void deal( const int wDeck[][ 13 ], const char *wface[], const char *wSuit[], char *wfSuit[], char *wfFace[] ); //operation functions void pair( const char *wfSuit[], const cha
Hei guys ! Watch out for more on c plus plus
NEW RELEASE!!  C PLUS PLUS (C++ ) BY PROF SAM QUESTIONS AND ANSWERS Q1.   Date Design a class called Date that has integer data members to store month, day, and year. The class should have a three-parameter default constructor that allows the date to be set at the time a new Date object is created. If the user creates a Date object without passing any arguments, or if any of the values passed are invalid, the default values of 1, 1, 2001 (i.e., January 1, 2001) should be used. The class should have member functions to print the date in the following formats: 3/15/13 March 15, 2013 15 March 2013 Demonstrate the class by writing a program that uses it. Be sure your program only accepts reasonable values for month and day. The month should be between 1 and 12. The day should be between 1 and the number of days in the selected month. ANSWER. #include <iostream> #include <cstring> using namespace std; class Date {