Writing and Running Your First C Program

Introduction

Now that you have set up your development environment, it’s time to write and run your first C program. In this chapter, we will take a look into the steps to create a simple “Hello, World!” program, compile it, and run it.

Steps to Write and Run Your First C Program

1. Create a New File

  • Open Your IDE or Text Editor:
    • Launch the IDE or text editor you installed earlier (e.g., Visual Studio Code, Code::Blocks, Eclipse).
  • Create a New File:
    • Create a new file and save it with a .c extension. For example, name it hello.c.

2. Write the Code

  • Type the Following Code into Your New File:
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
  • Explanation:
    • #include <stdio.h>: This line tells the compiler to include the standard input/output library, which is necessary for using the printf function.
    • int main(): This defines the main function, which is the entry point of every C program.
    • printf("Hello, World!\n");: This line prints the text “Hello, World!” to the console.
    • return 0;: This line ends the main function and returns 0 to the operating system, indicating that the program ran successfully.

3. Save the File

  • Save Your Code:
    • Make sure you save the file after writing your code.

4. Compile the Program

  • Open a Terminal or Command Prompt:
    • Navigate to the directory where your hello.c file is saved.
  • Compile the Code:
    • Type the following command to compile your program:
      • GCC: gcc hello.c -o hello
      • Clang: clang hello.c -o hello
      • Visual Studio (Developer Command Prompt): cl hello.c
  • Explanation:
    • gcc hello.c -o hello: This command tells the GCC compiler to compile hello.c and output an executable named hello.
    • clang hello.c -o hello: This command tells the Clang compiler to compile hello.c and output an executable named hello.
    • cl hello.c: This command tells the Visual Studio compiler to compile hello.c.

5. Run the Program

  • Run the Executable:
    • After compiling, run the program by typing the following command in the terminal or command prompt:
      • Linux/macOS: ./hello
      • Windows: hello
  • Expected Output:
    • You should see the text “Hello, World!” printed on the screen.

6. Verify the Output

  • Check the Output:
    • If you see “Hello, World!” on your screen, congratulations! You have successfully written, compiled, and run your first C program.

Conclusion

Writing and running your first C program is a significant milestone in learning C programming. By following these steps, you have created a simple program, compiled it using a C compiler, and executed it to see the output. This process forms the foundation of working with C, and you can now move on to writing more complex programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top