Lecture 1-2
C Program Structure
2
Eric Chen
2019-03-05
objectives
• Know how a C program looks like
• Explain simple C program structure – main( ) function
– header file
– printf( ) function
– C string
Read & watch
• 1.1 in English text book or
• C program structure
http://www.tutorialspoint.com/cprogramming /c_program_structure.htm
• 4. Print Text on the Screen
https://www.youtube.com/watch?v=oSpmAp iUsHw
• 5. Comments
https://www.youtube.com/watch?v=oX 2FpFYXE38
3
Eric Chen 2019-03-05
The first C program • ex1.c (page 7)
#include
{
printf(“hello, world\n”); }
4
Eric Chen 2019-03-05
5
Eric Chen 2019-03-05
main ( ) function
• ex1.c
• A C program consists of one or more functions.
– A function is a sequence of statements that together perform a task
– It is something like ”method” in OOP language program
• Each C program must contain one and only one main ( ) function:
main( )
• main() tells where the program starts to execute and it stops
– When the program starts, the statements in main( ) are executed, one by one.
– When it reaches the end of the function, or a return statement, the program stops
•
The main( ) function ex1.c
#include
{
printf(“hello, world\n”); }
This main() has 1 statement, ended by semicolon (;) – semicolon is used to terminate a statement
The statements in a function are enclosed by a pair of braces { }
– It forms the body of the function
Eric Chen 2019-03-05
• •
6
The printf( ) function
• ex1.c
#include
{
printf(“hello, world\n”); }
• printf( ) is a function defined in the standard input/output library (stdio).
– call printf( ) to print data on the screen
– A text string is printed in this example – C provides with a collection of libraries
7
Eric Chen 2019-03-05
#include • ex1.c
#include
main ( ) {
printf(“hello, world\n”); }
• #include directive tells the C pre-processor to include the header file stdio.h in the program
– Pre-processor is a step in the compilation process
– Header files contain info about the function definitions
– To allow the compiler to check the usage of function printf( )
8
Eric Chen 2019-03-05
9
Eric Chen 2019-03-05
Compile and run this example
• ex1.c
– compile and run ex1.c program
you check if your CodeBlocks works
– modify the program so that it prints the
following 2 lines:
Hello !
Welcome to C world!!