Learning to program can be exciting and challenging, and every new programmer’s journey begins with printing “Hello World!” to the console. This classic exercise serves as a rite of passage, introducing fundamental concepts in programming. In this article, we’ll explore three ways to write Hello, World program in C language, each method offering unique insight into the language’s capabilities.
Three basic methods to write “Hello, World!” Program in C
Method 1) “Hello, World!” Program in C using printf
Let’s start with the most straightforward approach to print “Hello, World!” in C. This method involves using the printf
function, a standard output function provided by the C Standard Library.
Code Example
#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
Explanation of the code
#include <stdio.h>
: This line tells the compiler to include the Standard Input Output library, which contains theprintf
function.int main() { ... }
: Themain
function is the entry point of every C program. It’s where execution starts.printf("Hello, World!\n");
: Theprintf
function prints the specified string to the console. The\n
character at the end inserts a newline, moving the cursor to the next line.return 0;
: This statement signifies that the program has been executed successfully.
Method 2) “Hello, World!” Program in C using ‘puts’ Function
Another way to print “Hello, World!” is by using the puts
function, which is also part of the C Standard Library. This method is slightly simpler and does not require a newline character since puts
automatically adds one.
Code Example
#include <stdio.h> int main() { puts("Hello, World!"); return 0; }
Explanation of the code
puts("Hello, World!");
: Unlikeprintf
, theputs
function automatically appends a newline character to the string it prints. This makes it a more straightforward option when you just need to output a line of text.- The
puts
function does not allow for formatted output likeprintf
, but it is useful for simple tasks.
Method 3) “Hello, World!” Program in C using a custom Print function
For educational purposes, you might want to create your custom function to print “Hello, World!” This method demonstrates how to define and use functions in C.
Code Example
#include <stdio.h> // Custom function to print Hello, World! void printHelloWorld() { printf("Hello, World!\n"); } int main() { printHelloWorld(); // Call the custom function return 0; }
Explanation of the code
void printHelloWorld() { ... }
: This defines a custom function namedprintHelloWorld
. It does not return a value (void
) and contains a single statement to print “Hello, World!” usingprintf
.printHelloWorld();
: Inside themain
function, we callprintHelloWorld()
to execute our custom function.