program must be loaded into main memory before it is...

13
MSIS 501 Spring 2010 1 The Parts of a Computer System Hardware Software Data Hardware CPU CU Program Counter Instruction Register ALU Accumulator Main Memory Secondary Storage Input & Output Devices Software System programs Application Programs How Data is Represented Computer understands only 0 & 1. This is machine language. Sequence of 0’s & 1’s: Binary code Sequence of 8 bits: byte Counting in binary 00000000 00000001 00000010 00000011 00000100 etc. Convert these numbers to binary 0 4 Program must be loaded into main memory before it is executed. Different data types take up different number of slots

Upload: duongkhue

Post on 17-Mar-2018

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

1

The Parts of a Computer System

Hardware

Software

Data

Hardware

CPU

CU

Program Counter

Instruction Register

ALU

Accumulator

Main Memory

Secondary Storage

Input & Output Devices

Software

System programs

Application Programs

How Data is Represented

Computer understands only 0 & 1. This is machine language.

Sequence of 0’s & 1’s: Binary code

Sequence of 8 bits: byte

Counting in binary

00000000 00000001 00000010 00000011 00000100 etc. Convert these numbers to binary

0 4

Program must be loaded into

main memory before it is

executed.

Different data types take up

different number of slots

Page 2: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

2

7 15 28 127 Characters encoded in ASCII

7-bits: 128 characters

A – ASCII code of 65

So represented as 01000001 (65 in binary)

Logic with Bits

Logic is the process of combining true and false statements together to yield new statements.

We humans use logic all the time to draw conclusions from our observations.

Internally, the computer uses logic to perform arithmetic.

The three fundamental logic operations that a computer can perform are

AND

OR

NOT

The AND of two statements is true if an only if both statements that are anded together are true.

For example, this statement is true:

It is Tuesday and it is the evening.

This statement is false:

It is Tuesday and it is morning.

The OR of two statements is true if either or both statements are true. For example, these statements are

true:

It is Tuesday or it is the evening.

It is Tuesday or it is morning.

The NOT of a statement is its exact opposite. True becomes false and false becomes true.

For example,

It is not true that today is Wednesday.

Computers use a 1 to represent truth and a 0 to represent false. Knowing this, we can evaluate the logical

combination of two numbers, like this:

Page 3: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

3

1. Convert each number to binary.

2. Perform the requested logical operation bit-by-bit to determine the bits in the result.

3. Convert the binary result back into decimal form.

Here are some examples:

1. Determine what 13 AND 5 is.

2. Determine what 11 OR 7 is.

3. Determine what NOT 7 is.

So what?

Logic operations are behind a lot of encryption techniques. That is why it is useful for you to learn bitwise

representation and how to combine bits to arrive at new values. Think of the new values as an

encoding.

How are instructions represented?

Again, the machine only understands machine language – 0’s and 1’s

So, instructions are also represented as 0’s and 1’s

Windows 3.1 – 16-bit instructions

Windows 95 – XP – 32-bit instructions

Some Unix & Windows platforms – 64-bit instructions

Computer Languages

Programmers used to have to write programs in machine language – 0’s and 1’s

Then came assembly language

Use of mnemonics

Page 4: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

4

Example:

To make programming easier, people introduced high-level languages

High-Level Language

A programming language that looks a lot more like English than both machine-language and assembly language.

Examples

FORTRAN C

LISP C++

Pascal Java

BASIC C#

The high-level language prescription of what a program should do is called source code

High-level language must be converted to machine language through a several step process.

Two of the most popular high-level languages

C++

grew out of C

brings object orientation to the C language

Java

very similar syntax to C / C++

purely object-oriented.

Processing a high-level program: C++

Use an editor to write the source code file or files

A precompiler modifies the source code file to contain additional lines of instructions it might need

Compiler converts the high-level language to a machine-language file called the object program

A linker takes all the object programs that make up the program and appends them together into a single executable file

A loader shoves all the machine language instructions in the executable file into memory so that they can be executed

After the instructions have been loaded into memory, they can be executed

Performing these steps in C++

Page 5: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

5

Programmers on Windows use an Integrated Development Environment (IDE) to perform these tasks

IDE contains editor, precompiler, compiler, and linker tools

IDE also allows you to run the program easily so you can test it

IDE also typically has a tool called a debugger that enables you to find problems

Examples of IDE’s for C++:

Microsoft Visual C++

Borland C++ Builder

How to Create a C++ Program in Visual Studio .NET

This section is intended as a quick how-to guide to get you started writing C++ programs in Visual Studio .NET. Hopefully this gives you complete step-by-step guide for writing C++ programs in this environment. First, a Project is a collection of files that support or implement you C++ application. Those files include

source files, which contain C++ instructions. These have a .cpp extension

header files, which contain outlines of C++ classes and functions. These have a .h extension. We won’t use .h files too much in this class

resource files, which may contain pictures or graphical objects like buttons or text areas. We won’t use these in this class. As you can see, your job will be to create projects that consist primarily of C++ source files. As you begin programming in C++, each project you create will have just one C++ source file. As you begin to create more complicated C++ applications, projects may consist of multiple C++ source files and header files. To create a C++ project, follow these instructions.

1. Open Microsoft Visual C++ 2008 or 2010 Express Edition (or Visual Studio 2008 or 2010). 2. Choose File >> New >> Project. This action will open the following dialog. Highlight the nodes that are shown.

Then specify the name and location of your project.

3. The dialog shown here will open. Switch to Application Settings.

Page 6: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

6

4. On the Application Setting page, check the box labeled “Empty Project”. Make sure the dialog looks like identical to the one below, and then click Finish.

Page 7: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

7

5. Somewhere on your screen will be a pane called the Solution Explorer. It will look like this:

6. Our job now is to create a source file. Right-click on Source Files, and select Add >> New Item. That will bring up the following dialog:

Highlight “C++ File (.cpp)” on the right. Then, enter a name. For example, I might name the C++ file for this project “ProjectSource” by typing this in the Name text field. The Location value defaults to the folder that houses your project, and you will rarely need to change this setting. Click the Open button. You’ll see a blank white screen. This is where you’ll enter the code for your new C++ source file.

7. Enter the code for your C++ source file. For example, write a program to write the names of your three favorite movies to

the screen. Here’s the source code for that:

Page 8: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

8

/*Ray Klump – a list of my three favorite movies One of my first C++ programs */ #include <iostream> using namespace std; int main() { cout << "These are my favorite movies: " << endl; cout << "1. Godfather Part One" << endl; cout << "2. It's a Wonderful Life" << endl; cout << "3. Up" << endl; return 0; }

8. Now that your source code has been entered, it is time to compile it and link (build) it. Select Build >> Build Solution from

the main menu. If there are errors in your code, the program will list them near the bottom of the screen. Double click on an error to be taken to the line where it is located. If building is successful, then choose Debug >> Start Without Debugging to run your application and see its results.

Your First C++ Program

Write an application that prints your name, occupation, and birthday to the screen.

Code:

#include <iostream>

using namespace std;

int main()

{

cout << “Ray Klump”;

cout << “Professional Clown”;

cout << “March 31, 1971”;

return 0;

}

Things to notice

* #include statement

* using namespace statement

* the fun begins at int main()

* cout statements for output

Page 9: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

9

#include statement

#include is an instruction to the precompiler. It tells the precompiler to go to the specified file and copy all

of its contents in place of this #include line.

The files that #include references are called header files or libraries.

Common libraries include

<iostream> for cin and cout (input and output with keyboard and monitor

<fstream> for input and output with files

<cmath> for math functions like sqrt and pow

<string> for access to string data types

<iomanip> for output formatting symbols.

Data A program must manage data. It has to store it and manipulate it. But data takes up space, and that space must be reserved. Once it is reserved, you need some convenient way to access it. To provide this convenient access mechanism, you give the memory you reserve an easy-to-remember name. The name of the memory is what we call a variable. Data types

Data comes in different shapes and sizes

Need to communicate to the computer how much space to set aside o that’s where data types come in

Declaring variables

To declare a variable is to set aside space for it and to give that space an easy-to-remember name

The syntax for declaring a variable: datatype variableName; datatype variableName1, variableName2, … ;

Example

Here’s code that declares a double called money and an int called count: double money; int count;

Rules for naming variables

names of variables must begin with a letter or underscore

names can contain letter, digits, and underscores, but no funky symbols

capitalization convention: o first letter lowercase o first letter of subsequent words uppercase o for example:

count dollarCount superCalaFrajoListic Declaring constants A constant is a memory location whose contents are fixed (i.e. cannot change). So, once the value of a const is defined, it is not allowed to change. Constants are usually named with all capital letters. In C++, use the keyword const instead: const double PI = 3.14159;

Page 10: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

10

Primitive data types

Type Storage Approx. Range int 4 bytes +/- 2 billion short 2 bytes +/- 32,767 long 8 bytes +/- 9.2 x 10

18

byte 1 byte -129 to 127 float 4 bytes 7 – 8 digits double 8 bytes 16 – 17 digits char 2 bytes 65,536 boolean 1 byte true or false

Examples of data declarations int number; double length; double width = 4.2; char firstInitial = ‘R’; char letter = 65; float interestRate = 5.125F boolean cPlusPlusIsCool = true; The String data type string is a data type in C++ that holds a sequence of characters that are supposed to be treated as a unit. Strings have functions built into them. To declare and set the value of a String, follow this example: string str; str = “Happy Birthday!”; Notice the use of double quotes to enclose the actual value of the string. More advanced data types

The string data type is actually an example of an advanced data type. Any variable we declare of the string data type actually has the

ability to do things – they can perform functions.

For example, string supports the following functions:

length() – returns the number of characters in a string

substr(start,numChars) – returns numChar characters starting at position start

erase(start,numChars) – starting at position start, replace numChars characters

replace(start,numChars,replacementChar) – starting at position start, replace numChars characters with the

replacementChar

Page 11: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

11

find(stringTofind, start) – starting at position start, look for stringToFind. When you find it, tell me the position where you

found it.

Furthermore, strings allow you to pick off individual characters by appending [#] after the name of the string variable, where # is the

index of the character in which we are interested.

Obviously, string variables can do some pretty fancy things. This is typical of variables that come not from simple data types, but

more sophisticated, complicated ones.

Example

Write a program that asks the user to enter an integer, decimal, character, and string, and then reports them to the screen.

Example

Modify the code you wrote in the previous example to also allow the user to extract a portion of the string based on the starting

index and number of characters the user specifies.

Streams: Conduits for inputting and outputting data

In the previous examples, we have used

cin to do input from the keyboard

cout to do output to the screen.

cin and cout are called streams. Streams are sophisticated data types, so they can also do things. For example, an input stream can

get the next character – cin.get(ch);

ignore the next specified # of characters or until a particular character is found: cin.ignore(#,charToStopAt);

take a peek at the next character: cin.peek();

putback the character that was just removed from the stream: cin.putback(ch)

Of course, it’s possible to deal with more than just the keyboard and monitor. There are

file input streams, which are variables of type ifstream

file output streams, which are variables of type ofstream

Input and output with files

Here is how you perform output with a file:

1. #include <fstream> 2. Declare a variable of type ofstream:

ofstream fout; 3. Associate fin with an actual physical file on the disk:

fout.open(“c:\temp\junk.txt”); 4. Once the file is open, you may use << with fout exactly like you would with cout:

Page 12: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

12

fout << var1 <<var2; 5. Close the file when you are done.

fout.close(); Here is how you perform input with a file:

1. #include <fstream> 2. Declare a variable of type ifstream:

ifstream fin; 3. Associate fin with an actual physical file on the disk:

fin.open(“c:\temp\junk.txt”); 4. Once the file is open, you may use >> with fin exactly like you would with cin:

fin >> var1 >> var2; 5. Close the file when you are done.

fin.close();

Example

Rewrite the example you did before where you read an integer, a decimal and a string from the keyboard. Instead, this time, read

the values from a file named “data.txt,” and write the data to a file called “output.txt.”

Formatting output

Of course, we might want to take better control of how output looks. Here we learn about two mechanisms for doing this:

escape sequences

stream manipulators Escape sequences These are two-character codes beginning with a backslash that appear within quotes. Almost everything in double-quotes prints exactly as is. However, escape sequences are an exception. \n means “newline” i.e. go to the next line \t means “tab” Example: cout << “Have a\nnice day”; This prints Have a nice day Stream Manipulators These are commands that you direct at the output stream using the same << symbol you use to send quoted items and variable values to the output device. Here is a summary: endl: means “newline” or “end of line”, just like \n but outside quotation marks fixed: means use non-scientific notation to represent decimal numbers setprecision(#): use the specified number of decimal places when outputting decimal numbers. Inexact values will be rounded. setw(#): means set the width of the next output to occupy the specified number of characters left: means left-justify the next output in the space it’s supposed to take up as defined by setw right: means right-justify the next output in the space it’s supposed to take up as defined by setw setfill(‘*’): if more space is left over, use the * (in this example) to pad the extra space. Any symbol may be used instead of the *. All but the endl manipulator requires you to type #include <iomanip> at the top of your source file.

Page 13: Program must be loaded into main memory before it is ...cs.lewisu.edu/~klumpra/2011Spring/68501K/W1.pdf · A linker takes all the object programs that make up the program ... [s code

MSIS 501 Spring 2010

13

Example This code computes the result of 1 divided by 3 and then outputs it with 4 decimal places: double result = 1.0/3; cout << fixed << setprecision(4) << result << endl; Example This code prints the values of name and battingAverage to the screen. The name column takes up 20 characters and is left-justified, with extra characters filled by dots. The batting average is right justified in a field of 8 characters and always shows 3 decimal places, with extra spaces filled with blanks. cout << fixed << setprecision(3); cout << setw(20) << left << setfill(‘.’) << name << setw(8) << right << setfill(‘ ‘) << battingAverage;