Title: What a C program looks like.
1 Lecture 2 Introduction to C Programs
- What a C program looks like.
- Variables
- Declaration of variables
- Types of variables
- assigning values to variables
- Names of variables
- for statement (Syntax and Examples)
- if statement (Syntax and Examples)
- switch statement (Syntax and Examples)
2A Simple C Program
include ltiostream.hgt int main() cout ltlt
Hello, world! return 0
include ltiostream.hgt void main() cout ltlt
Hello, world!
3- include ltiostream.hgt
- it includes library codes for input/output
- int main()
- the main function requires a return type of
integer, execution of program starts from this
function. -
- beginning of main function. The content of the
main function is within this pair of parenthesis. - cout ltlt Hello, world!
- cout is standard output, is the object of
output. - Retuen 0
- returns value 0 to the system. It is useless in
this case. -
- end of main function.
4Layout of a Simple C Program
- include ltiostream.hgt
- int main()
-
- //variable declarations
- //statements
- return 0
NOTE Here // is the prefix for comments.
Everything after // is ignored.
5Variable Declarations
- int i, j, k
- int stands for integer and i, j, k are
variables. Here we define i,j,k to be variables
which store integer values. - Each variable has a type.
- Here i, j, and k are of type int.
- includeltiostreamgt
- int main ()
- int i, j, k
- coutltltEnter the 1st number
- cin gtgt i
- coutltltEnter the 2nd number
- cin gtgtj
- kij
- cout ltlt The sum is ltlt k
- return 0
- \(Demo the execution in class.) \
NOTE Here endl stands for newline.
6Other Data Types for Numbers
- int j integers, 2 bytes
- long i long integers 4 bytes
- float i real numbers 4 bytes
- double r double precision real
numbers, 8 bytes - long double i 10 bytes, approximately 10-4932
to 104932
Characters char i character, 1
byte.
NOTE One byte is 8 bits. Thus, an int-type
variable is at most 2 to the power of 15 which
is about 30K.
7Variables and Assignments
- A variable in C
- has an associated value
- the value can be changed by assignment statement
- its name is an identifier which starts with a
letter or the underscore symbol, the remaining
characters can be letters, digits, and the
underscore symbol. - Assignment
- assigns a value of a data type to a variable of
the same data type - Example int a a23
8- Variable Declarations
- Syntax
- type_name variable_name1, variable_name2, ...
- example
- int a, b, c
- Assignment Statements
- Syntax
- variableexpression ( is the assignment
operator) - example
- total2i
int a, b int c You can have many declaration
statements.
9- Syntax is a set of grammar rules for the
programming language (C in our course.) - The compile that translates a program in C to
the machine language relies on its syntax. If
there is a syntax mistake, the compile may not
understand what the user is trying to do and thus
would not be able to do a proper job in
translating it into the machine language.
Therefore, the compile complains about syntax
errors and would not provide executable code if
there is any syntax error.
10Useful Tips about Variables
- Initialization of variables every variable
appearing in an expression should be initialized
first. - Naming of variables variables should be given
meaningful names related to what they represent.
11In
Input/Output with cout/cin
- Output
- cout output to screen
- Syntax cout ltlt variable1ltltvariable2ltltsentenceslt
lt... - ltlt insertion operator
- endl,\n newline character
- Input
- cin input from keyboard
- Syntax cin gtgt variable1 gtgt variable2 gtgt ...
12Simple Flow of Control
There are two main types of control mechanism.
- loop Some actions are repeated carried out.
- branching According to different logic
conditions, different tasks/calculations are
carried out.
13Syntax of for
- syntax of for
- for (initial_actionlogic_expressionupdate_action
) - statement_sequence
- an example calculating the sum S i
i1,2,...,n - int i, n, sum0
- cout ltltinput the value of n
- cin gtgt n
- for (i1iltni) sumsumi
14Examples using for
- Example 1 calculating the sum S i i2,4, 6,
...,2n - int i, n, sum0
- cout ltltinput the value of n
- cin gtgt n
- for (i2ilt2nii2) sumsumi
- Example 2 calculating the sum S i i1,3, 5,
...,2n1 - int i, n, sum0
- cout ltltinput the value of n
- cin gtgt n
- for (i1ilt2n1ii2) sumsumi
15Program Style
- indenting a layout tool which allows programs to
be identified as different blocks. - for (i1 ilt5 ii1)
-
- cout ltltHello, world!\n
- cout ltltHello, world!\n /print out
two lines / -
- indenting is often used to make statements in a
group look like a group - statement sequences inside loops etc.
- braces should usually placed in a line on its
own. - There may be different schools of thought on
details of indentations. One should be consistent
with what (s)he uses and conform to the team
(s)he works with.
16- comments notes put in programs explaining
meanings of variables and statements. - There are two ways to do it.
- //comments
- / comments /
- Example 1 int i, j, k /declare variables i,
j,k / - Example 2 int i,j,k
- //declare variables i,j,k.
17Top-Down Design
- Break the task of the program to subtasks.
- Solve each subtask individually.
- Combine the subtasks together.
- Example Write a program that (1) allows user to
input an integer from the keyboard and store it
in variable n and (2) print out a trees
containing n-1 lines, where the 1st line is121,
2nd lineis 12321, and the i-th line is
12(i1)(i-1) 1. - 121
- 12321
- 1234321
18Top-Down Design (continured)
- The first phase
- 1. Print out one line
(The difficulty is that each time the
output is different.) - 2. Repeat step 1 (n-1) times.
- The second phase (further divide step 1)
- 1.1 print out a few spaces.
- 1.2 print out 1 2 3 size.
- 1.3 print out (size-1) (size-2) 1
- 1.4 change to a new line
- 1.5 size size1
- 2. Repeat step 1.1-1.4 (n-1) times.
19 Implementation of the second phase
- 1.1 for(i1 iltn-size i)
- cout ltlt
- 1.2 for (i1 iltsize i)
- cout ltlt i
- 1.3 for (isize-1 igt1 i--)
- cout ltlti
- 1.4 cout ltlt\n
- 1.5 sizesize1
- 2. Repeat step 1.1-1.4 (n-1) times.
20Implementation of the second phase(continued)
- int i, j, size2, n
- cin gtgtn
- for(j1 jltn-1 j)
-
- for(i1 iltn-size i)
- cout ltlt
- for (i1 iltsize i)
- cout ltlt i
- for (isize-1 igt1 i--)
- cout ltlti
- cout ltlt\n
- size
-
21 Moving Object Design using for
/Ball moving application
/
for(i100 ilt500 ii4)
setcolor(BLACK)
circle(x,y,radius) /erase the circle /
xxradius
setcolor(WHITE) circle(x,y,radius)
delay(50)
closegraph()
include ltgraphics.hgt include ltdos.hgt void
main() int x 100, y 160, radius
20, xdir 4, i int driver
DETECT, mode initgraph(driver, mode,
G\\APPS\\BC31.WIN\\bgi) / figure out
your own directory /
rectangle(79, 139, 521, 181)
22Moving Object Design using forand if
/Ball moving application
/
for(i100 ilt5000 ii4)
setcolor(BLACK)
circle(x,y,radius) /erase the circle /
if (xgt500) radius -4
if(xlt100) radius 4
xxradius setcolor(WHITE)
circle(x,y,radius)
delay(50) closegraph()
Note we need to set different values to
radius according to different sicuations.
include ltgraphics.hgt include ltdos.hgt void
main() int x 100, y 160, radius
20, xdir 4, i int driver DETECT,
mode initgraph(driver, mode,
G\\APPS\\BC31.WIN\\bgi ) / figure out
your own directory / rectangle(79, 139,
521, 181)
23s
Syntax of if statements
- if (logic_expression)
-
- yes_statement1
- yes_statement2
- ...
-
- next statement
- if (logic_expression)
- yes_statement
- next statement
No
exp
yes
Statement 1
Next statement
24Syntax for if-else statements
- if (logic_expression)
- yes_statement1
- yes_statement2
- ...
-
- else
- no_statement ...
- if (logic_expression)
- yes_statement
- else
- no_statement
no
yes
exp
no_statement
yes_statement
next statement
25- Consider a company which pays employer overtime
at double rate. The following program calculates
the weekly pay of an employer according to the
number of hours he/she worked in a week. - if (hours lt 40)
- gross_payratehours
- else
- gross_payrate402rate(hours-40)
26Logical Expression and Comparison Operators
symbol meaning example
- and (xgt5)(ylt10)
- or (xgt5)(ylt10)
- equal to (y 10)
- ! not equal to (y!10)
- lt less than (ylt10)
- lt less than or equal to (ylt10)
- gt greater than (xgt5)
- gt greater than or equal to (xgt5)
27More example of if statement
int score cingtgtscore if (scoregt100) cout
ltltscore should be less than or equal to
100 if(scorelt100 scoregt75) cout ltltgrade
is A if(scorelt74 scoregt65) cout ltltgrade
is B if(scorelt64 scoregt55) cout ltltgrade
is C if(scorelt54 scoregt40) coutltltgrade is
D if(scorelt39) cout ltlt grade is F
28More example of if statement(continued)
int level cingtgtlevel if (level 1) cout
ltltstop at the first floor if(level 2) cout
ltltstop at the second floor if(level 3) cout
ltltstop at the third floor if(levellt1 or
level gt3) cout ltltError
29switch
- Its syntax
- switch (controlling_expression)
-
- case constant_1
- statement_sequence
- break
- case constant_2
- statement_sequence
- break
- ...
- default default_statement_sequence
controlling_expression can be an integer or a
character
30An example
int level switch(level) case 1 cout
ltltstop at the first floor case 2 cout
ltltstop at the second floor case 3 cout
ltltstop at the third floor default cout
ltltError
31- Another example
- char grade cin gtgt grade
- switch (grade)
-
- case A cout ltlt Excellent! break
- case Bcout ltlt Good. break
- case C cout ltltSatisfactory break
- case D cout ltltPass break
- default coutltltYou need to re-take the
examination
32includeltiostream.hgt
// includeltdos.hgt
/This program moves
an air plane / includeltconio.hgt
/ forward with a fixed speed.
/ void main()
// int i,
x1 for(x1 xlt72 x)
clrscr() for(i1 iltxi)
coutltlt" " coutltlt"
\n " for(i1 iltx i)
coutltlt" " coutltlt"
\n" for(i1 iltx i)
coutltlt" " coutltlt"\n"
for(i1 iltx i)
coutltlt" " coutltlt" \n"
for(i1 iltx i)
coutltlt" " coutltlt" \n"
delay(300)
How to allow the plane to change speed? Modify
the program so that the speed of the plane is
reduced by half when the plane enter the area
(30, 50).
33includeltiostream.hgt includeltdos.hgt includeltconi
o.hgt void main() int i, x1
for(x1 xlt72 x)
clrscr() for(i1 iltxi)
coutltlt" " coutltlt" \n
" for(i1 iltx i)
coutltlt" " coutltlt" \n"
for(i1 iltx i)
coutltlt" " coutltlt"\n"
for(i1 iltx i) coutltlt"
" coutltlt" \n"
for(i1 iltx i) coutltlt" "
coutltlt" \n"
if(xgt25 xlt50) delay(600)
else delay(300)
Note use if-else statement and carefully
select the condition. Each row contains 80
characters.
34Shooting a Bullet include ltmath.hgt includeltd
os.hgt includeltstdio.hgt include
ltgraphics.hgt includeltconio.hgt void main(void)
int driver DETECT,mode int i,j
int x1,y1
initgraph(driver,mode,"a\\bgi") setcolor(WHITE
) line(1,400,400,400) for ( i 0 i lt 80 i
) setcolor(BLACK)
circle(400-x,400-y,2) x5i
/ xi / y9i-0.15ii /
yi / setcolor(RED)
circle(400-x,400-y,2) delay(300)
closegraph()
35include ltmath.hgt includeltdos.hgt includeltstdio.
hgt include ltgraphics.hgt includeltconio.hgt void
main(void) int driver DETECT,mode
int i,j,count0 int x1,y1
initgraph(driver,mode,"a\\bgi") //
d\\BC31\\bgi") setcolor(WHITE)
line(1,400,400,400)
for ( i 0 i lt 80 i )
x5i y9i-0.15ii
setcolor(RED) circle(400-x,400-y,2)
delay(300)
if(countgt10) x5.5(i-10)
y10(i-10)-0.15(i-10)(i-10)
setcolor(YELLOW) circle(400-x,400-y,2)
delay(300)
count closegraph() twoShoot.c
pp
36 Summary
- Variables
- Declaration of variables
- Types of variables
- assigning values to variables
- Names of variables
- for statement (Syntax and Examples)
- if statement (Syntax and Examples)
- switch statement (Syntax and Examples)
1. You have to know the syntax of the above
three statements. (Basic) 2. Understand the 4
issues about variables (Basic) 3. Understand
basic examples (not include slides 33,34,35). 4.
Examples in slides 33,34 and 35 are for fun
today.