C Syntax, Output and Comments
This chapter explains the parts of a C program and shows how to print output.
The Parts of a C Program
Example
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}The example explained
| Line | Meaning |
|---|---|
#include <stdio.h> | Adds the standard input/output library, which contains printf |
int main(void) | The main function, where the program starts. It returns an int |
{ } | Curly braces hold the body of the function |
printf(...) | Prints text on the screen |
; | Every statement ends with a semicolon |
return 0; | Ends main and tells the system the program finished without errors |
C ignores extra spaces and blank lines, so use them to keep your code neat.
Printing with printf
printf does not add a new line by itself. Use \n where you want a line break:
Example
#include <stdio.h>
int main(void) {
printf("Workownix ");
printf("Institute\n");
printf("Orangi Town\nKarachi\n");
return 0;
}Workownix Institute Orangi Town Karachi
Escape Sequences
| Code | Result |
|---|---|
\n | New line |
\t | Tab space |
\\ | A backslash |
\" | A double quote |
Example
#include <stdio.h>
int main(void) {
printf("Item\tPrice\n");
printf("Tea\t120\n");
printf("He said \"Shukriya\"\n");
return 0;
}Item Price Tea 120 He said "Shukriya"
Printing Numbers
To print a value, put a format specifier in the text and the value after a comma:
Example
printf("Age: %d\n", 21);
printf("%d + %d = %d\n", 4, 5, 4 + 5);Age: 21 4 + 5 = 9
Spaces and Lines
C does not care about extra spaces or line breaks between statements. These two programs do the same thing, but the second one is much easier to read:
Example
int main(void){printf("Hi\n");return 0;}Example
int main(void) {
printf("Hi\n");
return 0;
}Indent the code inside braces by two or four spaces, and keep one statement on each line.
Comments
Comments are notes for humans. The compiler ignores them.
Example
#include <stdio.h>
int main(void) {
// A single-line comment
printf("Line one\n");
/* A comment that
spans many lines */
printf("Line two\n"); /* can also go at the end */
return 0;
}Line one Line two
C is case sensitive. printf works, but Printf or PRINTF gives an error.
Exercise
Exercise
Which escape sequence moves the output to a new line?
