C Tutorial menu

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

c
#include <stdio.h>

int main(void) {
  printf("Hello World\n");
  return 0;
}

The example explained

LineMeaning
#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

c
#include <stdio.h>

int main(void) {
  printf("Workownix ");
  printf("Institute\n");
  printf("Orangi Town\nKarachi\n");
  return 0;
}
Output
Workownix Institute
Orangi Town
Karachi

Escape Sequences

CodeResult
\nNew line
\tTab space
\\A backslash
\"A double quote

Example

c
#include <stdio.h>

int main(void) {
  printf("Item\tPrice\n");
  printf("Tea\t120\n");
  printf("He said \"Shukriya\"\n");
  return 0;
}
Output
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

c
printf("Age: %d\n", 21);
printf("%d + %d = %d\n", 4, 5, 4 + 5);
Output
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

c
int main(void){printf("Hi\n");return 0;}

Example

c
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

c
#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;
}
Output
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?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp