{"content":{"id":58,"title":"'Build Your Own Lisp' Solutions: 3.3","body":"\u003cbr\u003e\r\n\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e Declare a function that outputs 'Hello World!' n number of times. Call this from main.\u003c/p\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e\r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e#include \u0026lt;stdio.h\u0026gt;\r\n#include \u0026lt;stdlib.h\u0026gt;\r\n\r\nvoid hello_n_times(int n)\r\n{\r\n while (n--)\r\n printf(\"Hello world!\\n\");\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n int n;\r\n\r\n /* not part of the exercise, but we \r\n may as well not hardcode the number */\r\n if (argv[1] \u0026\u0026 (n = strtol(argv[1], NULL, 10)))\r\n hello_n_times(n);\r\n else\r\n printf(\"Needs Positive Integer!\\n\");\r\n\r\n return 0;\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\r\n\r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e\u0026gt ./hello_n_times 3\r\nHello world!\r\nHello world!\r\nHello world!\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2018-06-14T00:00:00.000Z","created_at":"2018-06-06T01:19:27.000Z","updated_at":"2018-06-18T16:42:26.000Z","user_id":1,"rating":null},"tags":"\u003ca class=\"changeable-title\" href=\"/q?tag=c\"\u003ec\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=lisp\"\u003elisp\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=build_your_own_lisp\"\u003ebuild_your_own_lisp\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=answers\"\u003eanswers\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=programming\"\u003eprogramming\u003c/a\u003e"}

'Build Your Own Lisp' Solutions: 3.3


Q: Declare a function that outputs 'Hello World!' n number of times. Call this from main.

A:

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

void hello_n_times(int n)
{
        while (n--)
                printf("Hello world!\n");
}

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

        /* not part of the exercise, but we 
           may as well not hardcode the number */
        if (argv[1] && (n = strtol(argv[1], NULL, 10)))
                hello_n_times(n);
        else
                printf("Needs Positive Integer!\n");

        return 0;
}
> ./hello_n_times 3
Hello world!
Hello world!
Hello world!