140 likes | 314 Views
PART 10 C++ Programming. Illustration 1 Illustration 2 Illustration 3 Illustration 4 Illustration 5. Illustration 1. 10-2. Add two integers, whose values are encoded in the program, and print out the result. Illustration 1. int x,y,z; x = 5; y = 10; z = x+y; cout << z;.
E N D
PART 10C++ Programming • Illustration 1 • Illustration 2 • Illustration 3 • Illustration 4 • Illustration 5
Illustration 1 10-2 Add two integers, whose values are encoded in the program, and print out the result.
Illustration 1 int x,y,z; x = 5; y = 10; z = x+y; cout << z; LD R0, x LD R1, y ADD R0, R0, R1 ST R0, z TRAP x21 HALT x .FILL #5 y .FILL #10 z .BLKW #1 10-3
Illustration 2 10-4 Add two integers, whose values are provided through input, and print out the result.
Illustration 2 TRAP x23 ST R0, x TRAP x23 ST R0, y LD R0, x LD R1, y ADD R0, R0, R1 ST R0, z TRAP x21 HALT x .BLKW #1 y .BLKW #1 z .BLKW #1 int x,y,z; cin >> x; cin >> y; z = x+y; cout << z; 10-5
Illustration 3 10-6 Compare two integers. Print out 1 if the first is larger than the second, -1 if the first is less than the second, and 0 if they are equal.
Illustration 3 AND R2, R2, #0 TRAP x23 ST R0, x TRAP x23 ST R0, y LD R0, x LD R1, y NOT R1, R1 ADD R1, R1, #1 ADD R0, R1, R0 BRnz NZ ADD R2, R2, #1 BRnzp DONE int x, y; int z = 0; cin >> x; cin >> y; if( x>y ) z = 1; else if( x<y ) z = -1; cout << z; 10-7
Illustration 3 NZ BRz DONE ADD R2, R2,#-1 DONE LD R2, z ADD R0, R2, #0 TRAP x21 HALT x .BLKW #1 y .BLKW #1 z .FILL #0 10-8
Illustration 4 • Add ten integers in sequence, and print out the sum. 10-9
Illustration 4 LEA R1, a AND R0, R0, #0 AND R2, R2, #0 AND R3, R3, #0 ADD R3, R3, #-10 AGAIN ADD R5, R2, R3 BRzp DONE LDR R4, R1, #0 ADD R0, R4, R0 ADD R2, R2, #1 BRnzp AGAIN int sum = 0; for( int i=0; i<10; i++ ) sum = sum + a[i]; cout << sum; 10-10
Illustration 4 DONE ST R0, sum TRAP x21 HALT sum .FILL #0 a .FILL #5 ………… ………… 10-11
Illustration 5 • Demonstrate how functions are used. 10-12
Illustration 5 TRAP x23 ST R0, y JSR XX ST R1, P LD R0, P TRAP x21 HALT y .BLKW #1 P .BLKW #1 XX ST R0, temp AGAIN LD R2, temp int XX( int x ) { int result = 0; int temp = x; while ( temp > 0 ) { result = result + x; temp = temp -1; } return result; } main( ) { int y; cin >> y; cout << XX(y); } 10-13
Illustration 5 BRnz DONE LD R1, result ADD R1, R0, R1 ST R1, result LD R2, temp ADD R2, R2, #-1 ST R2, temp BRnzp AGAIN DONE LD R1, result HALT temp .BLKW #1 result .BLKW #0 10-14