Tuesday 3 March 2015

Your First C Program


Let us write our first real C program. Throughout this course students will be using Linux as the development platform. A C program written for the Linux platform (or for UNIX) is slightly different to the program shown earlier. A modified version of the Hello World program is given next.


/* Program-2.2 - My First Program */
#include <stdio.h>
int main()
{
printf("Hello World!");
return 0;
}


Similar to the previous program, main() is placed as the first function; however with a slight difference. The keyword int is added before the function main. The keyword int indicates that main() function returns an integer value. Most functions return some value and sometimes this return value indicates the success or the failure of a function.

Because function main() returns an integer value, there must be a statement that indicates what this value is. The statement “return 0;” does that; in this case it returns zero (conventionally 0 is returned to indicate the success of a function).

Use your favorite text editor in Linux and type the above program. Save it as HelloWorld.c (all C source files are saved with the extension .c). Then use the shell and go to the directory that you have saved your source file. Use the command gcc HelloWorld.c to compiler your program. If there are no errors an executable file will be created in the same location with the default file name a.out. To execute the program at the prompt type ./a.out (i.e. to execute the a.out file in current directory). When you execute your program it should display “Hello World!” on the screen.


$ vim HelloWorld.c
$ gcc HelloWorld.c
$ ./a.out
Hello World!$


However you will see the prompt ($) appearing just after the message “Hello World!” you can avoid this by adding the new line character (\n) to the end of the message. Then your modified program should look like the following:

/* Program-2.3 - My First Program */

#include <stdio.h>
int main()
{
printf("Hello World!\n");
return 0;
}




No comments:

Post a Comment