Curriculum
In this lesson, we’ll start with the quintessential “Hello World” program in C and explore the basic structure of a C program.
The “Hello World” program is often the first program you write when learning a new programming language. It’s a simple program that displays the text “Hello, World!” on the screen. Here’s the code for a “Hello World” program in C:
#include <stdio.h>
int main() {
printf("Hello, World!n");
return 0;
}
Let’s break down the components of this program:
#include <stdio.h>: This line includes the standard input-output library (stdio.h) in your program. This library provides functions like printf and scanf for input and output operations.int main() { ... }: This is the main function of your C program. Every C program must have a main function, which serves as the entry point for the program’s execution.printf("Hello, World!n");: This line uses the printf function to print the text “Hello, World!” to the standard output (usually the console). The n is an escape sequence that represents a newline character, so the program’s output will appear on a new line.return 0;: This line indicates that the program has terminated successfully. The 0 is returned to the operating system to indicate success, while a non-zero value is typically used to indicate an error.A C program typically consists of various elements that work together to perform a specific task. Here’s an overview of the basic structure of a C program:
// Preprocessor Directives
#include <stdio.h>
// Other #include directives as needed
// Function Prototypes (optional)
int add(int a, int b);
// Global Variables (optional)
// Main Function
int main() {
// Local Variables
int x, y, result;
// Statements
// ...
// Function Calls
result = add(x, y);
// Output
printf("Result: %dn", result);
// Program Termination
return 0;
}
// User-Defined Functions (optional)
int add(int a, int b) {
return a + b;
}
Here’s an explanation of each section:
#, and they are used to include libraries (e.g., #include <stdio.h>) or define macros.main function is the entry point of your program. It contains local variables, statements, function calls, and the program’s output.To run your C program, follow these steps:
.c extension (e.g., hello.c).gcc hello.c -o hello
hello.c into an executable named hello../hello
You should see the “Hello, World!” message printed on the screen.