C Language | Introduction to C | Your First C Program

This article explains how to define the main() entry point and display text with printf().

Your First Program

A C program consists of functions. A function can receive arguments, process them, and return a value.

return-type function-name(parameters...)
{
 statements
}

Execution starts with main(). The operating system calls this entry point and receives its return value.

int main(void)
{
 statements
}

Code 1

int main()
{
 return 0;
}

This program does nothing and exits immediately. C is case-sensitive, and punctuation matters: a missing semicolon or mismatched brace causes a compilation error.

The return statement ends a function and returns control to its caller.

return expression;

Displaying Text

C delegates input and output to library functions. The standard library provides printf() for formatted output.

printf("Hello, world!");

To use printf(), include the stdio.h header.

#include <stdio.h>

Angle brackets are normally used for standard headers. Quotation marks are commonly used for project headers.

Code 2

#include <stdio.h>

int main() {
 printf("Kitty on your lap\n");
 return 0;
}

The \n escape sequence adds a newline. To write a backslash itself, use \\.

A string literal cannot contain an unescaped line break. For a long string, use a line-continuation backslash or place adjacent literals next to each other.

"Kitty on \
your lap"

"Kitty on "
"your lap"

Adjacent string literals are combined during compilation.

Code 3

#include <stdio.h>

int main() {
 printf("First line\n"
        "Second line\n");
 printf("Third line\n");
 return 0;
}