C basics: main, printf, and functions
C is a compiled language
- C is one of the oldest and most important languages. Linux, databases, and even Python are built with C.
- Unlike Python, C is compiled: the computer first turns your code into a program, then runs it.
- C is strict: declarations and expression statements end with a semicolon
;, and every variable has a type. A block such asif (...) { ... }does not need an extra semicolon.
The C skeleton
- Every C program starts in a function called main. Your code goes inside main.
#include <stdio.h>gives youprintf, which prints text.return 0;at the end ofmainmeans "the program finished without an error".
#include <stdio.h>
int main(void) {
printf("C runs from inside main.\n");
int year = 11;
printf("Grade %d\n", year);
return 0;
}
printf and types
printfprints text. The\ninside the text means "start a new line".- To print a value, use a placeholder:
%dfor anint,%ffor adouble,%cfor one character. printf("Grade %d\n", year);puts the value ofyearwhere the%dis.- Every variable needs a type first:
int year = 11;ordouble pi = 3.14;.
Common mistakes
- End declarations and expression statements with
;. Blocks use braces; do not add a stray;after anifcondition.mainreturnsint(return 0;). printfneeds the right format (%d,%f) and\nfor a new line.
Now you try
- Each task pre-fills the code you need. Write inside
main, or complete the function shown. - Some tasks ask for a function only — do not write your own
main; the checker adds one. - For a complete program, Run compiles and runs it. For a function task, Check answer compiles your code with the supplied tests and shows the results. Your code is compiled and run on the server.
Compile then run
C source is compiled to a program, which you then run.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Inside main, use printf(...) to print exactly Hello, C! on its own line.
Click Run to see the output here.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Complete the function int square(int n) so it returns n * n. The checker calls it with several values. Do not write a main — the checker provides one.
Click Run to see the output here.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Inside main, declare int grade = 11;. Then use printf to print two lines: first Hello!, then Grade 11 — print the number with a %d placeholder, not by typing 11.
Click Run to see the output here.