2017年3月15日 星期三









Write code to complete PrintFactorial()'s recursive case. Sample output if userVal is 5:
5! = 5 * 4 * 3 * 2 * 1 = 120

Answer:

#include <stdio.h>

void PrintFactorial(int factCounter, int factValue){
   int nextCounter = 0;
   int nextValue = 0;

   if (factCounter == 0) {            // Base case: 0! = 1
      printf("1\n");
   }
   else if (factCounter == 1) {       // Base case: Print 1 and result
      printf("%d = %d\n", factCounter, factValue);
   }
   else {                             // Recursive case
      printf("%d * ", factCounter);
      nextCounter = factCounter - 1;
      nextValue = nextCounter * factValue;

//solution 
   PrintFactorial(nextCounter,nextValue);
  
   
   }
}

int main(void) {
   int userVal = 0;

   userVal = 5;
   printf("%d! = ", userVal);
   PrintFactorial(userVal, userVal);

   return 0;
}

2017年2月23日 星期四

string code 3.9


Set hasDigit to true if the 3-character passCode contains a digit. 

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

int main(void) {
   bool hasDigit = false;
   char passCode[50] = "";
   int valid = 0;

   strcpy(passCode, "abc");

//solution
   for (valid =0; valid<50; valid++){
      if (isdigit(passCode[valid])){
         hasDigit=true;
         break;
      }
   }

   if (hasDigit) {
      printf("Has a digit.\n");
   }
   else {
      printf("Has no digit.\n");
   }

   return 0;
}





Replace any space ' ' by '_' in 2-character string passCode. Sample output for the given program:
1_
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
   char passCode[3] = "";

   strcpy(passCode, "1 ");

 
   if(isspace(passCode[0])){
      passCode[0]='_';
   }
    if (isspace(passCode[1])){
       passCode[1]='_';
    }
    if (isspace(passCode[2])){
       passCode[2]='_';
    }

   printf("%s\n", passCode);
   return 0;
}