C Hello World Program
Last Updated :
31 Jul, 2024
Write a C program to print “Hello, World!” on the console screen.
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. All one needs to do is display the message “Hello World” on the screen.
C Program to Print “Hello World”
To print the “Hello World”, we will use the printf function from the stdio.h library. The following C program displays “Hello World” in the output screen:
C
// Simple C program to display "Hello World"
// Header file for input output functions
#include <stdio.h>
// Main function: entry point for execution
int main() {
// writing print statement to print hello world
printf("Hello World");
return 0;
}
Explanation:
- #include <stdio.h> – This line includes the standard input-output library in the program.
- int main() – The main function where the execution of the program begins.
- printf(“Hello, World!\n”); – This function call prints “Hello, World!” followed by a new line.
- return 0; –This statement indicates that the program ended successfully.
Different Ways to Write a “Hello, World!” Program in C for Beginners
1. Basic Hello World
This is the simplest and most common way to write a “Hello, World!” program in C.
C++
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. Using a Function to Print Hello World
You can create a separate function to print “Hello, World!”.
C++
#include <stdio.h>
// Function to print Hello, World!
void printHelloWorld() {
printf("Hello, World!\n");
}
int main() {
printHelloWorld();
return 0;
}
3. Using a Macro
You can define a macro to print “Hello, World!”.
C++
#include <stdio.h>
#define HELLO_WORLD() printf("Hello, World!\n")
int main() {
HELLO_WORLD();
return 0;
}
4. Without Including stdio.h
Although not recommended for beginners, you can avoid including stdio.h and use system calls instead. This is more advanced and not as portable.
C++
int main() {
write(1, "Hello, World!\n", 14);
return 0;
}
5. Using Multiple Print Statements
You can break the message into multiple printf statements.
C++
#include <stdio.h>
int main() {
printf("Hello, ");
printf("World!\n");
return 0;
}
6. Using Character-by-Character Printing
You can print each character of the string separately.
C++
#include <stdio.h>
int main() {
char *str = "Hello, World!\n";
while (*str) {
putchar(*str++);
}
return 0;
}
7. Using puts() Function
The puts function can be used instead of printf for a simpler approach.
C++
#include <stdio.h>
int main() {
puts("Hello, World!");
return 0;
}
These are various ways to write a “Hello, World!” program in C. Each example demonstrates different aspects and functions of the language, providing multiple approaches for beginners to understand and explore.
NEXT TO READ:
Please Login to comment...