Your First C Program
What C is, how a C program is compiled, and the classic hello program.
C is a compact language created in the early 1970s. It gives you direct control over memory and produces very fast programs, which is why it is still used for operating systems, microcontrollers and performance-critical libraries.
Unlike Python, C is compiled: a program called a compiler turns your source file into a machine-code executable, and then you run that executable.
Setting up a compiler
- Linux: install
gccfrom your package manager (for examplesudo apt install build-essential). - macOS: run
xcode-select --installto getclang, which works the same way. - Windows: install MSYS2 or MinGW-w64 to get
gcc, or use an IDE such as Code::Blocks.
Hello, world
Save this as hello.c:
int main(void) {
printf("Hello, world!\n");
return 0;
}
Hello, world!
Compile and run it from a terminal:
gcc hello.c -o hello
./hello
What each line does
#include <stdio.h>brings in the standard input/output library, which providesprintf.int main(void)is where every C program starts. It returns anintto the operating system.printf(...)prints text. The\nat the end means "new line"; C does not add one for you.return 0;tells the system the program finished without errors.- Every statement ends with a semicolon
;, and curly braces{ }group statements together.
Printing numbers
printf uses format specifiers to insert values into text: %d for whole numbers and %f for decimals.
int main(void) {
printf("%d + %d = %d\n", 7, 5, 7 + 5);
printf("Half of 9 is %.1f\n", 9 / 2.0);
return 0;
}
7 + 5 = 12 Half of 9 is 4.5
GATE-style practice questions
What does the following program print?
int main(void) {
printf("GATE");
printf(" %d\n", printf("CS"));
return 0;
}
Show answer and explanation
Answer: Bprintf returns the number of characters it printed. The inner printf("CS") must run before the outer call (its result is an argument), so it prints CS right after GATE and returns 2. The outer call then prints " 2" and a newline.
Which statements about a C program's main function are true? (Select all that apply.)
Show answer and explanation
Answer: A, B, DThere must be exactly one main. It is where execution begins, and its return value (0 for success) goes back to the operating system.