Saturday, October 13, 2007

Structure of a C program

Every C program consists of one or more functions. A function is nothing but a group or sequence of C statements that are executed together. Each C program function performs a specific task. The ‘main()’ function is the most important function and must be present in every C program. The execution of a C program begins in the main() function.

The figure below shows the structure of a C program.


Programmers are free to name C program functions (except the main() function).

Writing your first C program

Learning any programming language becomes easy with a hands-on approach, so let’s get right to it. The following is a simple C program that prints a message ‘Hello, world’ on the screen.


main() function1() function2()

{ { {

statement1; statement1; statement1;

statement2; statement2; statement2;

……; ……..; ……;

……; ……..; ……;

} } }


------------------------------------------------------------------------------------------

/*

Author: Globarena

Date: 13/10/2002

Purpose: This program prints a message

*/

1.#include

2.main()

3.{

4. printf(“Hello, world”);

5.}


Type this program in any text editor and then compile and run it using a C-compiler. However, your task will become much easier if you are using an IDE such as Turbo C (available freely from http://community.borland.com/downloads/). Download and install Turbo C on your machine and follow the steps given below in order to type and run the program given above:

1. Go to the directory where you have installed Turbo C.
2. Type TC at the DOS command prompt.
3. In the edit window that opens, type the mentioned program above.
4. Save the program as hello.c by pressing F2 or Alt + ‘S’.
5. Press Alt + ‘C’ or Alt + F9 to compile the program.
6. Press Alt + ‘R’ or Ctrl + F9 to execute the program.
7. Press Alt + F5 to see the output.

If you are using a Linux machine, you have to follow the steps mentioned below:

1. Go to the Linux command prompt (# or $).
2. Type vi.
3. The vi editor will open.
4. Type the program in the editor.
5. Press ‘Esc + Shift + ‘:’.
6. Type ‘w’ + ‘q’ followed by file name ‘hello.c’.
7. At the command prompt type ‘gcc hello.c’.
8. Type ‘./a.out’ to run the program.

Note: C is a case-sensitive language. It makes a distinction between letters written in lower and upper case. For example, ‘A’ and ‘a’ would be taken to mean different things. Also, remember that all C language keywords should be typed in lower case.

No comments: