18-05-13 Weekly Links



'Build Your Own Lisp' Solutions: 3.1

Q: Use a for loop to print out Hello World! five times.

A:

#include <stdio.h>

int main(void) {
  int i;

  for (i = 0; i < 5; i++) {
    printf("Hello World!\n");
  }

  return 0;
}
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!


18-05-19 Weekly Links



K&R Solutions - 1.1
#include <stdio.h>

int main(void)
{
  printf("Hello, World!\n");

  return 0;
}


18-05-27 Weekly Links



18-06-03 Weekly Links


K&R Solutions - 1.2

Q: Experiment to find out what happens when printf's argument string contains '\c', where 'c' is some character not listed above.

A:

#include <stdio.h>

int main(void)
{
  printf("Hello, World!\c");

  return 0;
}
> make 1.2
1.2.c: In function ‘main’:
1.2.c:6:10: warning: unknown escape sequence: '\c'
   printf("Hello, World!\c");


SICP Solutions - 1.1

Q: Below is a sequence of expressions. What is the result printed by the interpreter in response to each expression? Assume that the sequence is to be evaluated in the order in which it is presented.

A:

> 10
10
> (+ 5 3 4)
12
> (- 9 1)
8
> (/ 6 2)
3
> (+ (* 2 4) (- 4 6))
6
> (define a 3)
> (define b (+ a 1))
> (+ a b (* a b))
19
> (= a b)
#f
> (if (and (> b a) (< b (* a b)))
      b
      a)
4
> (cond ((= a 4) 6)
        ((= b 4) (+ 6 7 a))
        (else 25))
16
> (+ 2 (if (> b a) b a))
6
> (* (cond ((> a b) a)
           ((< a b) b)
           (else -1))
     (+ a 1))
16


K&R Solutions - 1.3

Q: Modify the temperature conversion program to print a heading above the table.

A:

#include <stdio.h>

int main(void)
{
  double fahr, celsius;
  double lower, upper, step;

  lower = 0;
  upper = 300;
  step = 20;

  fahr = lower;

  printf("Fahrenheit    Celsius\n");
  printf("---------------------\n");

  while (fahr <= upper) {
    celsius = (5.0/9.0) * (fahr-32.0);
    printf("%10.0f    %6.1f\n", fahr, celsius);
    fahr += step;
  }

  return 0;
}
> make 1.3
> ./1.3
Fahrenheit    Celsius
---------------------
         0     -17.8
        20      -6.7
        40       4.4
        60      15.6
        80      26.7
       100      37.8
       120      48.9
       140      60.0
       160      71.1
       180      82.2
       200      93.3
       220     104.4
       240     115.6
       260     126.7
       280     137.8
       300     148.9