Week 2 Tutorial — Sample Solutions

    1. int i;
      int fact = 1;
      for (i = 2; i <= n; n++) {
          fact = fact * i;
      }
      

    2. int gcd(int a, int b) {
          while (a != b) {
              if (a > b) {
                  a = a - b;
              } else {
                  b = b - a;
              }
          }
          return a;
      }
      

    1. Val[3] = 43
      String = "Txt"
      

    2. Provides a return status to the environment. Return value 0 indicates successful completion of the program (no execution error).
    1. int n;
      
      printf("Enter an integer: ");
      scanf("%d", &n);
      printf("The number is: %d\n", n);
      

    2. float x;
      
      printf("Enter a real number: ");
      scanf("%f", &x);
      printf("The number is: %f\n", x);
      

    3. #define MAX_CHARS 128
      ...
      char *string[MAX_CHARS];
      
      printf("Enter a string: ");
      fgets(string, MAX_CHARS, stdin);
      printf("The string is %s", string);
      

  1. #define MAX_CHARS 128
    ...
    FILE *inputStream;
    char *string[MAX_CHARS];
    
    inputStream = fopen("infile.txt", "r");
    if (inputStream != NULL) {
       while (fgets(string, MAX_CHARS, inputStream) != NULL) {
          printf("%s", string);
       }
       fclose(inputStream);
    }
    

  2. Val = 120