Docsity

Exam 1 Notes | Structured Programming in C | CSCE 206, Study notes of Computer Science

Toggle sidebar
bg1
C++ Reading Notes
Chapter 1 Introduction to Computers and Programing
Program?
Set of instructions a computer follows to perform a task
*note: Programs also called software
What must be designed for real world program?
Logical flow of instructions
The mathematical procedures
Appearance of the screens
Way information is presented to user
Program’s “user-friendliness”
Manuals and other forms of written documentation
1.2 Computer Systems: Hardware and Software
What is Hardware?
Physical components computer is made of
Typical computer system major components
1. Central Processing unit (CPU)
2. Main memory
3. Secondary storage devices
4. Input devices
5. Output devices
What is CPU?
Part of a computer that runs programs
Most important component
Its job is to fetch instructions, follow instructions, and produce
some result
Consists of 2 parts
oControl Unit: responsible for where to get the next
instruction and regulates other major components of
computer with control signals
oArithmetic and Logic Unit (ALU): performs mathematical
operations
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Exam 1 Notes | Structured Programming in C | CSCE 206 and more Study notes Computer Science in PDF only on Docsity!

C++ Reading Notes Chapter 1 Introduction to Computers and Programing Program?  Set of instructions a computer follows to perform a task  *note: Programs also called software What must be designed for real world program?  Logical flow of instructions  The mathematical procedures  Appearance of the screens  Way information is presented to user  Program’s “user-friendliness”  Manuals and other forms of written documentation 1.2 Computer Systems: Hardware and Software What is Hardware?  Physical components computer is made of Typical computer system major components

  1. Central Processing unit (CPU)
  2. Main memory
  3. Secondary storage devices
  4. Input devices
  5. Output devices What is CPU?  Part of a computer that runs programs  Most important component  Its job is to fetch instructions, follow instructions, and produce some result  Consists of 2 parts o Control Unit : responsible for where to get the next instruction and regulates other major components of computer with control signals o Arithmetic and Logic Unit (ALU): performs mathematical operations

What happens when computer is running program?  CPU is engaged in fetch/decode/execute process o Fetch: CPU control unite fetches from main memory the next instruction in the sequence o Decode: Instruction is encoded in the form of a number the control unit decodes the instruction and generates an electronic signal o Execute: Signal is routed to appropriate component of computer and signal causes component to perform an operation What is Main Memory?  Computers work area where computer stores program and the data for it  Memory is lost when computer is turned off  Known as random access memory or RAM which is a volatile type of memory  Memory divided into tiny storage areas called bytes one byte can store one letter of the alphabet or a small number o Byte: has 8 smaller storage locations known as bits o Bits: tiny electrical components that can hold a positive or negative charge  Address: each byte is assigned a number called an address What is secondary storage?  Type of memory that can hold data for long periods of time used by frequently used programs o Disk drive: most conman type of secondary storage device stores data by magnetically coding it onto a disk o USB drives, CDs, and DVDs are also popular for data storage What are input devices?  Input is any info the computer collects from the outside world o Ex. Mouse, keyboard, scanner, camera, microphone, disk drives, USB drives

Program Languages and Description  BASIC: Beginners All Purpose Symbolic Instruction Code. General programing language designed to be simple enough for beginners  FORTRAN: Formula Translator. Designed for programing complex mathematical algorithms  COBOL: Common Business-Oriented Language. Designed for business applications  Pascal: Structured, general purpose language designed for teaching programing  C: Structured, general purpose language developed at Bell Labs. Offers both low and high level features  C++: Based on C. Offers object oriented features not found in C. invented at Bell  C#: C sharp invented by Microsoft designed for developing applications on Microsoft .NET platform  Java: object oriented invented at Sun Microsystems. Used to develop programs run over internet  JavaScript: used to write small programs run on web pages. Not related to Java  Python: general purpose designed in 90’s popular for business and academic applications  Ruby: general purpose also designed in 90’s increasingly popular for programs run on web servers  Visual Basic: Microsoft programing language and software that allows programs to quickly create windows based applications Process of a C++ Program

  1. C++ Program is written and saved into a text editor.  Text editor: similar to word processing program  Source code: statements written by programmer  Source file: name of file source code is stored in
  2. Preprocessor program reads the source code by recognizing lines that start with # symbol
  3. Compiler then translates preprocessed source code instructions into machine code instructions  This process identifies any Syntax Errors o Syntax Errors: illegal uses of keywords, operators, punctuation, and other language elements

 Compiler then stores translated machine language instructions called Object Code

  1. Program called Linker then combines the Object file with the necessary library routines. Once this is finished an executable file has been created.  Library routines: collection of code available for use Source Code -> Preprocessor -> Modified Source Code -> Compiler -> Object Code -> Linker -> Executable Code

What is a Program made of?  Language Elements make up a program of any language o Key Words: Words that have a special meaning and can only be used for intended purpose also called reserve words. They are always written in lower case. These words have special meaning in C++ o Programmer-Defined Identifiers: Words or names made up and defined by programmer. They are symbolic for some variable the programmer assigned. Not part of C++ language. o Operators: They perform operations on one or more operands. An operand is a piece of data, like a number. o Punctuation: Punctuation characters that mark beginning or end of a statement, or separate items on a list. // This program calculates the user's pay. #include

Input, Processing, and Output  Input operations found in above program o cin >> hours; o cin >> rate;  Processing example from program above o pay = hours * rate;  Output examples from program above o cout << “How many hours did you work? “; o cout << “How much do you get paid per hour? “; o cout << “You have earned $ “ << pay << endl;

The Programming Process

  1. Clearly define what the program is to do o Identify the Purpose, Input, Process, and Output of the program you are creating o Example: Purpose- calculate user gross pay. Input- number of hours worked, hourly pay rate. Process – multiply hours by pay rate. Output- display user’s gross pay
  2. Visualize the program running on the computer o Visualize what the program looks like on the screen THE PROGRAM NOT THE SOURCE CODE
  3. Use design tools such as a hierarchy chart, flowcharts, or pseudo code to create a model of the program o Hierarchy chart begins with the overall task and refines it into smaller subtasks
  4. Check the model for logical errors o Mistakes that cause the program to produce erroneous results
  5. Type the code, save it, and compile it o Once model has been created and checked program is ready to by written in source code. The compiler will find any syntax errors
  6. Correct any errors found during compilation. Repeat steps 5 and 6 as many times as needed
  1. Run the program with test data for input o Test for logical errors such as mathematical mistakes
  2. Correct any run-time errors found while running the program. Repeat 5-8 as many times as needed o Use desk-checking which means read the program step by step looking over each detail of the process
  3. Validate the results of the program o Enter test data and determine whether the program solves the original problem

Procedural and Object-Oriented Programing  Procedural Programing is centered around the procedure, or function. The programmer constructs procedures the procedures are collections of programming statements that perform a specific task.  Object-Oriented Programing is centered around the object. Object is a programming element that contains data and the procedures that operate on the data. It is a self-contained unit. Chapter 2 Introduction to C++

Parts of a C++ Program  // : these marks indicate the beginning of a single line comment which is ignored by the compiler  #include : lines that start with # are called preprocessor directives the preprocessor sets up your source code for compiler o #include: causes the preprocessor to include the contents of another file, in this case the iostream o iostream: contains code that allows C++ to display output on the screen and read input from keyboard, the iostream file is called a header fileusing namespace std; : Variables, functions, and objects are program entities that need names. C++ uses namespace to

// A simple C++ program #include using namespace std; int main() { cout << "Programming is great fun!"; return 0; } The cout Object  Console output: simplest type of screen output that a program can display  Stream object: cout is classified as a steam object meaning it works with streams of data  The << operator is used to send a string in this case to cout where the stream insertion operator (<<) is pointing like an arrow  The stream insertion operator can be used to send more that one thing to cout Ex. (cout << “Programing is” << “great fun!” ;)  Unless you specify otherwise the information you send to cout is displayed in a continuous stream  endl; : This is used to start a new line on the information displayed it is called a stream manipulator o anytime the cout encounters an endl stream manipulator it advances the output to the beginning of the next line Escape Sequences  Escape sequences start with the() character and are followed by one or more control characters. It allows you to control the way output is displayed by embedding commands within the string itself o \n: Newline, this causes the cursor to go to the next line for subsequent printing o \t: Horizontal tab, this causes cursor to skip over to next tab stop o \a: Alarm, causes computer to beep o \b: Backspace, causes cursor to back up, or move left one position

o \r: Return, causes cursor to go to beginning of the current line, not the next line o \: Backslash, causes backslash to be printed o \’: Single quote, causes a single quotation mark to be printed o \”: Double quote, causes double quotation mark to be printed

#include Directive Ex. #include  iostream must be included in any program that uses the cout object. The reason why is cout is not apart of the core of the C++ language  cout is apart of the input-output stream library  Preprocessor directives are not C++ statements  #include must always contain name of a file

Variables and Literals Variables - Ex. int number;  This is called a variable definition it tells the compiler the variable’s name and the type of data it will hold  Int stands for integer (the type of data being held)  Variable definitions end with a semicolon Ex. number = 5;  This is called an assignment Ex. “number”  When double quotation marks are placed around the word number it becomes a string literal Literals - Ex. number = 5  In the case of the example above the number “5” is called a integer literalInteger Literal: A literal is a value that does not change during the program’s execution

 characters are internally represented by numbers o Ex. A is 65, B is 66, C is 67  In C++ an extra byte is stored in string literals. In this last byte a 0 is stored called a null terminator or null character it marks the end of a string  ‘A’ is stored as A which is a 1 byte character  “A” is stored as A 0 which is a 2 byte character  Escape sequences (Ex. \n) are stored as one byte  String literals are always stored in memory with a null terminator at the end

string Class  Must include header file #include  Define a string type variable o Ex. string movieTitle;  You can assign a string literal to movieTitle o Ex. movieTitle = “wheels of fury” ;  cout will display the value of movieTitle

Floating – Point Data Types  Used to define variables that can hold real numbers. They are stored in a manner similar to scientific notation with the first part of the number being called the mantissa.  Computer typically use E notation to represent floating values o Ex. (247.91 is 2.4791x10^2 and is 2.479E2 in E notation)  There are 3 data types that can represent floating point numbers o float Single precision 4 bytes. +-3.4E- o double Double precision 8 bytes. +-1.7E- o long double Long Double Precision same as double  A double is at least as big as a float  A long double is at least as big as a double  Floating – Point value to integer variables o Ex. int i; float f;

f = 7.5; i = f; o A value of 7 is assigned to i

bool Data Type  Boolean variables are set to either true or false  They also do not need quotations around them o True is represented in memory by the number 1 o False is represented in memory by the number 0

size of Data type  The operator sizeof will report the number of bytes of memory used by any data type or variable o Ex. (cout << “The size of an integer is “ << sizeof(int)) o This will come out as: The size of an integer is 4 o sizeof(long) would come out as 8 o ui Chapter 3 Expressions and Interactivity

The cin Object  cin object can be used to read data typed at the keyboard o Ex. cout << “what is the length of the rectangle?”; cin >> length;  This question is known as a prompt, it tells the user what data should be imputed  The >> symbol is the stream extraction operator, it stores the input in the variable to the right Entering Multiple Values  Ex. cin >> length >> width;

 pow is used to raise a number to a power o area = pow(4.0, 2.0) ;  The return value of this would be 16  The numbers inside the parentheses are arguments. The first argument is raised to the power of the second argument.  To use this function the program must include the header file .

Mixing data types  When an operator’s operands are of different data types, C++ will automatically convert them to the same data type. o Data Type Ranking  long double  double  float  unsigned long  long  unsigned int  int  Rule 1 : chars, shorts, and unsigned shorts are automatically promoted to int.  Rule 2 : When operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher-ranking value.  Rule 3 : When the final value of an expression is assigned to a variable, it will be converted to the data type of that variable.  THE ONE EXCEPTION when an int and a long are the same size an unsigned int outranks long because it can hold a higher value

Overflow and Underflow  When a variable is assigned a value that is too large or too small in range for that variable’s data type, the variable overflows or underflows  When variable is assigned number that is too large for its data type it overflows.  Likewise when a value that is too small is assigned it underflows  See example on page 102

Type Casting  A type cast expression lets you manually promote or demote a value. o static_cast (Value) This is a general formula o Ex. static_cast(number)  This would convert the data type of the value number to an integer data type o Val = int(number) This also works

Multiple Assignment and Combined Assignment  Multiple assignment means to assign the same value to several variables with one statement. o Ex. a = b = c = d = 12 o The value 12 will be assigned to all 4 statements Combined Assignment Operators  number = number +  In this case the value of number + 1 will be assigned to number this could also be stated as number+ = 1  Here is a list of these operators o += x += 5; x = x + 5; o -= y -= 2; y = y – 2; o *= z *= 10; z = z * 10; o = a /= b; a = a / b; o %= c %= 3; c = c % 3;  Here is another list of examples o x += b + 5; x = x + (b + 5); o a /= b + c; a = a / (b + c);  The statement to the right of = will be read first

 If we want the numbers padded with trailing zeroes we use the showpoint manipulator as shown. o double x = 123.4, y = 456.0; cout << setprecision(6) << showpoint << x << endl; cout << y << endl; o This will output 123.400 and 456. left and right Manipulators  Output is normally right justified.  You can cause the output to be right justified by using right manipulator o cout << left << x << endl; getline(cin, inputLine);  This allows the user to input an entire line to be stored in the variable (in this case inputLine) Using cin.get  If the program is using the cin.get function simply to pause the screen until the [enter] key is pressed and does not need to store the character, the function can also be called like this: o cin.get(); o The same result will also be given if cin.get(ch); is used (in this case the character ch must have been declared) and also ch = cin.get(); Mixing cin >> and cin.get  Look on page 124 for the example Using cin.ignore  The cin.ignore function tells the cin object to skip one or more characters in the keyboard buffer. Here is a general formula: o cin.ignore(n, c) o n is the integer and c is the character  using cin.ignore() allows you to skip over the last character (\n) letting your program run through string Member Functions and Operators

 string state = “Texas”; int size = state.length();  This will store the value 5 in the size variable

Mathematical Library Functions  All of these require the cmath header file  Chart on page 127 Random Numbers  y = rand();  This will produce the same sequence of random numbers in order to change that we use the time function ( header file ) with the srand() function  The function time is the number of seconds that have gone by since January 1, 1970  Example Program  // This program demonstrates random numbers. #include #include // rand and srand #include // For the time function using namespace std; int main() { // Get the system time. unsigned seed = time(0); // Seed the random number generator. srand(seed); // Display three random numbers. cout << rand() << endl; cout << rand() << endl; cout << rand() << endl; return 0; }