360 likes | 409 Views
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)
E N D
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) CS3369 Real Time Computer Control Software /WANG Lusheng
A Simple C++ Program #include <iostream.h> int main() { cout << “Hello, world!”; return 0; } #include <iostream.h> void main() { cout << “Hello, world!”; } 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. • } • end of main function. 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. CS3369 Real Time Computer Control Software /WANG Lusheng
Variable Declarations • #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.) *\ • 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”. NOTE: Here “endl” stands for newline. CS3369 Real Time Computer Control Software /WANG Lusheng
int j; integers, 2 bytes long i; long integers4 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 Other Data Types for Numbers 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. 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; CS3369 Real Time Computer Control Software /WANG Lusheng
Variable Declarations: • Syntax: • type_name variable_name1, variable_name2, ...; • example: • int a, b, c; • Assignment Statements: • Syntax: • variable=expression; (“=“ is the assignment operator) • example: • total=2+i; int a, b; int c; You can have many declaration statements. 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. 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. CS3369 Real Time Computer Control Software /WANG Lusheng
In 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 >> ... ; 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. 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; 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; 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 tothe team (s)he works with. CS3369 Real Time Computer Control Software /WANG Lusheng
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. 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 • 12321 • 1234321 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. 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. CS3369 Real Time Computer Control Software /WANG Lusheng
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++ • } CS3369 Real Time Computer Control Software /WANG Lusheng
Moving Object Design using “for” /*===================Ball moving application ====================*/ for(i=100; i<=500; i=i+4) { setcolor(BLACK); circle(x,y,radius); /*erase the circle */ x=x+radius; setcolor(WHITE); circle(x,y,radius); delay(50); } closegraph(); } #include <graphics.h> #include <dos.h> 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); CS3369 Real Time Computer Control Software /WANG Lusheng
Moving Object Design using “for”and “if” /*===================Ball moving application ====================*/ for(i=100; i<=5000; i=i+4) { setcolor(BLACK); circle(x,y,radius); /*erase the circle */ if (x>=500) radius = -4; if(x<=100) radius = 4; x=x+radius; setcolor(WHITE); circle(x,y,radius); delay(50); } closegraph(); } Note: we need to set different values to radius according to different sicuations. #include <graphics.h> #include <dos.h> 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); CS3369 Real Time Computer Control Software /WANG Lusheng
Syntax of “if” statements s • if (logic_expression) • { • yes_statement1; • yes_statement2; • ...; • } • next statement; • if (logic_expression) • yes_statement; • next statement; No exp yes Statement 1 Next statement CS3369 Real Time Computer Control Software /WANG Lusheng
Syntax 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 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) CS3369 Real Time Computer Control Software /WANG Lusheng
&& and (x>5)&&(y<10) || or (x>5)||(y<10) = = equal to (y= = 10) != not equal to (y!=10) < less than (y<10) <= less than or equal to (y<=10) > greater than (x>5) >= greater than or equal to (x>=5) Logical Expression and Comparison Operators symbol meaning example 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”; 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”; CS3369 Real Time Computer Control Software /WANG Lusheng
“switch” controlling_expression can be an integer or a character • Its syntax: • switch (controlling_expression) • { • case constant_1: • statement_sequence; • break; • case constant_2: • statement_sequence; • break; • ...; • default: default_statement_sequence; • } 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”; } 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”; • } CS3369 Real Time Computer Control Software /WANG Lusheng
#include<iostream.h> /*****************************/ #include<dos.h> /*This program moves an air plane */ #include<conio.h> /* forward with a fixed speed. */ 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"; 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). CS3369 Real Time Computer Control Software /WANG Lusheng
#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. 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(); } 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(); } 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. CS3369 Real Time Computer Control Software /WANG Lusheng