Lecture 2: Introduction to C++ Programs

advertisement
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)
Page 1
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
A Simple C++ Program
#include <iostream.h>
#include <iostream.h>
int main()
void main()
{
{
cout << “Hello, world!”;
return 0;
}
cout << “Hello, world!”;
}
Page 2
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
 #include <iostream.h>
 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 << “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.
 }

5/29/2016
end of main function.
Page 3
CS3369 Real Time Computer Control
Software /WANG Lusheng
Layout of a Simple C++ Program







#include <iostream.h>
int main()
{
//variable declarations
//statements
return 0;
}
NOTE: Here “//” is the prefix for comments. Everything after “//” is ignored.
Page 4
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Variable 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”.
•
•
•
•
•
•
•
•
•
•
#include<iostream>
int main () {
int i, j, k;
cout<<“Enter the 1st number ”;
cin >> i;
cout<<“Enter the 2nd number”;
cin >>j;
k=i+j;
cout << “The sum is” << k;
return 0;
• }
\*(Demo the execution in class.) *\
NOTE: Here “endl” stands for newline.
Page 5
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Other Data Types for Numbers
 int j; integers, 2 bytes
 double r; double precision
 long i; long integers 4 bytes real numbers, 8 bytes
 long double i; 10 bytes,
 float i; real numbers 4
-4932
4932
approximately 10
bytes
to 10
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.
Page 6
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Variables 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;
a=2+3;
Page 7
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
 Variable Declarations:

Syntax:
• type_name variable_name1, variable_name2, ...;
• example:
int a, b;
– int a, b, c;
 Assignment Statements:

Syntax:
• variable=expression;
• example:
int c;
You can have many declaration
statements.
(“=“ is the assignment operator)
– total=2+i;
Page 8
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
 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.
Page 9
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Useful 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.
Page 10
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Input/Output with “cout/cin”
 Output:

cout: output to screen
• Syntax: cout << variable1<<variable2<<“sentences”<<...;


<<: insertion operator
endl,\n: newline character
 Input:

cin: input from keyboard
• Syntax: cin >> variable1 >> variable2 >> ... ;
Page 11
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Simple 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.
Page 12
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Syntax of “for”
 syntax of “for”:


for (initial_action;logic_expression;update_action)
{statement_sequence;}
 an example: calculating the sum S {i: i=1,2,...,n}




int i, n, sum=0;
cout <<“input the value of n”;
cin >> n;
for (i=1;i<=n;i++) sum=sum+i;
Page 13
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Examples using “for”
 Example 1: calculating the sum S {i: i=2,4, 6, ...,2n}
 int i, n, sum=0;
 cout <<“input the value of n”;
 cin >> n;
 for (i=2;i<=2*n;i=i+2) sum=sum+i;
 Example 2: calculating the sum S {i: i=1,3, 5, ...,2n+1}
 int i, n, sum=0;
 cout <<“input the value of n”;
 cin >> n;
 for (i=1;i<=2*n+1;i=i+2) sum=sum+i;
Page 14
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Program Style
 indenting: a layout tool which allows programs to be identified as different
blocks.

for (i=1; i<=5; i=i+1)

{

cout <<“Hello, world!\n”;

cout <<“Hello, 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.
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Page 15
 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.
Page 16
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Top-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…(i+1)(i-1) …1.

121


5/29/2016
12321
1234321
Page 17
CS3369 Real Time Computer Control
Software /WANG Lusheng
Top-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 =size+1;

2. Repeat step 1.1-1.4 (n-1) times.

Page 18
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Implementation of the second phase

1.1 for(i=1; i<=n-size; i++)

cout <<“ ”;
 1.2 for (i=1; i<=size; i++)

cout << i;
 1.3 for (i=size-1; i>=1; i--)

cout <<i;
 1.4 cout <<“\n”;
 1.5 size=size+1;
 2. Repeat step 1.1-1.4 (n-1) times.
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Page 19
Implementation of the second phase(continued)

int i, j, size=2, n;
 cin >>n;
 for(j=1; j<=n-1; j++)
 {

for(i=1; i<=n-size; i++)

cout <<“ “;

for (i=1; i<=size; i++)

cout << i;

for (i=size-1; i>=1; i--)

cout <<i;

cout <<“\n”;

size++

}
Page 20
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Moving Object Design using “for”
/*===================Ball moving application ====================*/
for(i=100; i<=500; i=i+4)
#include <graphics.h>
{
#include <dos.h>
setcolor(BLACK);
void main()
circle(x,y,radius); /*erase the circle */
{
x=x+radius;
int x = 100, y = 160, radius = 20, xdir = 4, i;
setcolor(WHITE);
circle(x,y,radius);
int driver = DETECT, mode;
delay(50);
initgraph(&driver, &mode, “G:\\APPS\\BC31.WIN\\bgi”);
}
/* figure out your own directory */
closegraph();
}
rectangle(79, 139, 521, 181);
Page 21
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Moving Object Design using “for”and “if”
/*===================Ball moving application ====================*/
#include <graphics.h>
for(i=100; i<=5000; i=i+4)
#include <dos.h>
{
setcolor(BLACK);
void main()
circle(x,y,radius); /*erase the circle */
{
if (x>=500) radius = -4;
int x = 100, y = 160, radius = 20, xdir = 4, i;
if(x<=100) radius = 4;
x=x+radius;
int driver = DETECT, mode;
setcolor(WHITE);
initgraph(&driver, &mode, “G:\\APPS\\BC31.WIN\\bgi ”);
circle(x,y,radius);
/* figure out your own directory */
delay(50);
rectangle(79, 139, 521, 181);
}
closegraph();
}
Note: we need to set different values to radius
5/29/2016
according to different sicuations.
CS3369 Real Time Computer Control
Software /WANG Lusheng
Page 22
s
Syntax of “if” statements
 if (logic_expression)


yes_statement;
next statement;
exp
No
yes
Statement 1
Next
• if (logic_expression)
•{
• yes_statement1;
• yes_statement2;
• ...;
• }
• next statement;
statement
Page 23
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Syntax for “if-else” statements
 if (logic_expression)

yes_statement;
 else

no_statement;
yes
exp
yes_statement
no
no_statement
• if (logic_expression) {
– yes_statement1;
– yes_statement2;
– ...;
• }
• else {
• no_statement;
next statement
...;
• }
Page 24
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
 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 <= 40)
• gross_pay=rate*hours;

else
• gross_pay=rate*40+2*rate*(hours-40)
Page 25
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Logical Expression and Comparison Operators
symbol








&&
||
==
!=
<
<=
>
>=
meaning
and
or
equal to
not equal to
less than
less than or equal to
greater than
greater than or equal to
example
(x>5)&&(y<10)
(x>5)||(y<10)
(y= = 10)
(y!=10)
(y<10)
(y<=10)
(x>5)
(x>=5)
Page 26
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
More example of “if” statement
int score;
cin>>score;
if (score>100) cout <<“score should be less than or equal to 100”;
if(score<=100 && score>=75) cout <<“grade is A”;
if(score<=74 && score>=65) cout <<“grade is B”;
if(score<=64 && score>=55) cout <<“grade is C”;
if(score<=54 && score>=40) cout<<“grade is D”;
if(score<=39) cout << “grade is F”;
Page 27
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
More example of “if” statement(continued)
int level;
cin>>level;
if (level == 1) cout <<“stop at the first floor”;
if(level == 2) cout <<“stop at the second floor”;
if(level ==3) cout <<“stop at the third floor”;
if(level<1 || or level >3) cout <<“Error”;
Page 28
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
“switch”
 Its syntax:


switch (controlling_expression)
{
controlling_expression
can be an integer or a
character
• case constant_1:
– statement_sequence;
– break;
• case constant_2:
– statement_sequence;
– break;
• ...;
• default:

default_statement_sequence;
}
Page 29
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
An example:
int level;
switch(level)
{
case 1: cout <<“stop at the first floor”;
case 2: cout <<“stop at the second floor”;
case 3: cout <<“stop at the third floor”;
default: cout <<“Error”;
}
Page 30
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
 Another example:



char grade; cin >> grade;
switch (grade)
{
•
•
•
•
•

case ‘A’: cout << “Excellent!”; break;
case ‘B’:cout << “Good.”; break;
case ‘C’: cout <<“Satisfactory”; break;
case ‘D’: cout <<“Pass”; break;
default: cout<<“You need to re-take the examination”;
}
Page 31
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
#include<iostream.h>
/*****************************/
/*This program moves an air plane */
/* forward with a fixed speed.
*/
/*****************************/
#include<dos.h>
#include<conio.h>
void main()
{
int i, x=1;
for(x=1; x<=72; x++)
{
clrscr();
for(i=1; i<=x;i++)
How to allow the plane to
cout<<" ";
change speed?
cout<<" * \n ";
for(i=1; i<=x; i++)
cout<<" ";
cout<<" * \n";
for(i=1; i<=x; i++)
Modify the program so that the
cout<<" ";
speed of the plane is reduced
cout<<"*********\n";
for(i=1; i<=x; i++)
by half when the plane enter
cout<<" ";
the area (30, 50).
cout<<" * \n";
for(i=1; i<=x; i++)
cout<<" ";
cout<<" *
\n";
delay(300);
}
5/29/2016
CS3369 Real Time Computer Control
}
Software /WANG Lusheng
Page 32
#include<iostream.h>
#include<dos.h>
#include<conio.h>
void main() {
int i, x=1;
for(x=1; x<=72; x++)
{
clrscr();
for(i=1; i<=x;i++)
cout<<" ";
cout<<" * \n ";
for(i=1; i<=x; i++)
cout<<" ";
cout<<" * \n";
for(i=1; i<=x; i++)
cout<<" ";
cout<<"*********\n";
}
for(i=1; i<=x; i++)
cout<<" ";
cout<<" * \n";
for(i=1; i<=x; i++)
cout<<" ";
cout<<" * \n";
if(x>=25 &&x<=50)
delay(600);
else
delay(300);
}
Note: use if-else statement and
carefully select the condition.
Each row contains 80 characters.
Page 33
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Shooting a Bullet
#include <math.h>
#include<dos.h>
#include<stdio.h>
#include <graphics.h>
#include<conio.h>
void main(void)
{
int driver =DETECT,mode;
int i,j;
int x=1,y=1;
initgraph(&driver,&mode,"a:\\bgi");
setcolor(WHITE);
line(1,400,400,400);
for ( i = 0; i < 80; i++ )
{
setcolor(BLACK);
circle(400-x,400-y,2);
x=5*i;
/* x=i; */
y=9*i-0.15*i*i; /* y=i; */
setcolor(RED);
circle(400-x,400-y,2);
delay(300);
}
closegraph();
}
Page 34
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
#include <math.h>
#include<dos.h>
#include<stdio.h>
#include <graphics.h>
#include<conio.h>
void main(void)
{
int driver = DETECT,mode;
int i,j,count=0;
int x=1,y=1;
initgraph(&driver,&mode,"a:\\bgi");
// d:\\BC31\\bgi");
setcolor(WHITE);
line(1,400,400,400);
for ( i = 0; i < 80; i++ )
{
x=5*i;
y=9*i-0.15*i*i;
setcolor(RED);
circle(400-x,400-y,2);
delay(300);
if(count>=10) {
x=5.5*(i-10);
y=10*(i-10)-0.15*(i-10)*(i-10);
setcolor(YELLOW);
circle(400-x,400-y,2);
delay(300);
}
count++;
}
closegraph();
}
Page 35
5/29/2016
twoShoot.cpp
CS3369 Real Time
Computer Control
Software /WANG Lusheng
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.
Page 36
5/29/2016
CS3369 Real Time Computer Control
Software /WANG Lusheng
Download