Write Your First C Program

From CS113

Hello World

Use VIM to create hello.c with the following contents:

#include <stdio.h>

int main() {
    printf("Hello World.\n");
    return 0;

The #include line imports the definition of many standard library functions including printf that we later use to print a string to the screen. The int main() { line beings a new function main. The main function is where all C programs will start executing. The int in that line specifies that the function returns a value of type integer -- the return value from main is called the exit-status of the program (not important for this course). The empty parenthesis () is where the arguments to main are declared. While main can take in various arguments, for this simple program, we are not interested in these arguments so we do not declare any. The printf line prints the string given as the argument to the function to the screen. The \n is used to signify a new-line character that will end the previous line. The return 0 line returns from the function (in this case main) and returns the interger 0, which will be the exit-status of the program.

Compile the program using GCC:

gcc -o hello hello.c

GCC stands for the GNU C Compiler. The -o hello tells the compiler that the final output should go to the file hello. The input program is given as the next argument hello.c

Run the program by executing the output from GCC:


You should see Hello World. on your screen. The ./ before hello is required so the system knows where to find the file (./ referes to the current directory -- where gcc created the output).

Command Line Arguments

Use VIM to create cmd.c with the following contents:

#include <stdio.h>

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

    n = atoi(argv[1]);
    m = atoi(argv[2]);

    printf("Argument 1: %d\nArgument 2: %d\n", n, m);

    return 0;

The slightly more complex program above shows how to take integers as input to your program. In the declaration of main, there are two variables defined -- argc and argv. The type of argc is an integer. The type for argv is a character pointer pointer (or array of strings) ... we'll encounter more this type later. When the program is started from the command line (e.g. ./cmd 10 20), the number of arguments (in this case 2) and the array of argument strings (in this case "10" and "20") are passed into main. In the subsequent line, n and m are declared as integer variables. They are then assigned the integer values represented by the first and second command arguments. The atoi functions accepts a string and returns an integer represented in that string. Finally the printf call prints the two integers with the given formatting.

Compile and run the program.

gcc -o cmd cmd.c
./cmd 10 20

The output will be:

Argument 1: 10
Argument 2: 20
Personal tools