CS 2400 OHIO U Quiz 1 (1/29/21)

¡Supera tus tareas y exámenes ahora con Quizwiz!

Include directives

#include <iostream> #include <cstdlib> • Tells the compiler to find information about certain items in your program

C++ Program Structure

#include <iostream> using namespace std; int main() { variable declaration Statement_1 Statement_2 ... Last statement return 0; // EXIT_SUCCESS // #include <cstdlib> }

compile-time error

A compile-time error is a violation of the programming language rules that is detected by the compiler.

C++

C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s. - Used to maintain UNIX systems - Many commercial applications written in c • C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s. - Overcame several shortcomings of C - Incorporated object-oriented programming - C remains a subset of C++

What output is generated by the statements below? cout << "C++"; cout << " is " << endl; cout << "fun";

C++ is fun

Editing Your Program

Create the program in a text file with any of the following extensions: cc, cpp, cxx

Which of the following programs are not typically written in C++?

Web applications

Swap Variable Content

int num1 = 5, num2 = 6;

Program Style

• A program written with attention to style - is easier to read - easier to debug - easier to maintain

Alternative Formatting Method

• Alternatively, we can use: - cout.setf(ios::fixed); - These flags can also be combined in one cout.setf statement ocout.setf(ios::left | ios::fixed);

Strings

• Strings (#include <string>) - string: A group of characters. - string constants are surrounded by double quotes: "Hello World"

Program Errors

• Syntax errors - Violation of the grammar rules of the language - Discovered by the compiler o Error messages may not always show correct location of errors • Run-time errors - Error conditions detected by the computer at runtime • Logic errors - Errors in the program's algorithm - Most difficult to diagnose - Computer does not recognize an error

Running Your Program

• To run the program - ./a.out (Mac, Linux) - ./a.exe (Windows)

Variable Naming Convention

• Use all small letters - first, second • Use one of the following naming conventions if the variable name has multiple words - firstBank, firstLocalBank - first_bank, first_local_bank

Namespace

• using namespace std; Interpret iostream in a standard way. Without this line you have to enter - std::cout

Hardware Components

- CPU (Central Processing Unit) - Main Memory - Secondary Memory - Input Devices - Output Devices

Introduction Cont. (Large amounts of memory is measured in)

- Kilobyte (KB) = 103 = 1,000 bytes - Megabyte (MB) = 106 = 1,000,000 bytes - Gigabyte (GB) = 109 = 1,000,000,000 bytes - Terabyte (TB) = 1012 = 1,000,000,000,000 bytes

Introduction Cont. (Memory)

- Measured in bytes - A byte is 8 bits - a bit is the smallest unit of storage. A bit represents the binary digits 0 and 1. - Each byte has an address (A sequence of bytes are identified by the address of the first byte.) - A word is 2, 4, or 8 bytes depending on the system

Software

- Operating System (Windows, Mac OS, Linux, iOS etc.) - Applications (Chrome, Office products, C++ Compiler, Spreadsheets, GNU C++)

Introduction Cont. (Example calculating 5+6)

- What is involved in calculation - input/output - How much memory is required? - Can it be done with one memory location? Why/Why not?

setw, Cont.

- cout << setw(9) << "Hello"; // prints ¨¨¨¨Hello - cout << setw(2) << "hello"; • If the width value specified is not big enough, it will be ignored

Mixing Expressions

- long double -> most dominant type - double - float - long long - long int - int - short - char -> least dominant type

Math Functions Examples

- root = sqrt(16); will assign 4.0 to the variable root. sqrt function returns a double value - result = pow(2, 3); returns 23 oassigns the double value 8.0 to result. - log(x) returns ln x - log10(x) returns log10 x - Trigonometric functions: sin, cos, tan, etc. - abs returns the absolute value of an integer - fabs returns the absolute value of a float

Documentations/Comments

/** * @file: introProgram.cpp * @author: Nasseef Abukamail * * @date: August 28, 2019 * @brief: * A program that reads two integers and does simple * arithmetic calculations. */ To comment a single line use //

Which of the following statements is true about a compiler?

A C++ programmer using a compiler doesn't need to know machine instructions.

run-time error

A run-time error causes a program to take an action that the programmer did not intend.

Which of the following is not an advantage of programming in a higher-level language instead of machine code?

Instructions do not need to be encoded before a program runs.

Which of the following statements is false?

The distinction between upper- and lowercase letters is unimportant in C++.

Type Casting (Conversion)

Used for explicit type conversion int iVar = 2; double dVar; dVar = static_cast (iVar); Converts iVar to double and assigns it to dVar char ch = 'B'; cout << static_cast (ch); Displays the ASCII value of ch (66)

Character Arithmetic

char ch = 'A'; // assigns 'A' to ch ch = ch + 2; // assigns 'C' to ch int distance = ch - 'A'; - How far is ch from the letter 'A' in the ASCII table?

Fixed vs. Scientific "precision"

double value = 123456789.12345; cout << "Value without formatting: " << value << endl; cout << setprecision(4); cout << "Value after precision of 4: " << value << endl; cout << fixed << "Value in fixed notation: " << value << endl; Output: Value without formatting: 1.23457e+08 Value after precision of 4: 1.235e+08 Value in fixed notation: 123456789.1235

When writing a C++ program, you type your code into a(n) ___ window.

editor

Main function

int main() { //start here return 0; } • The main function of the program. This defines the entry point of the program.

Shortcut Assignment

number = number + 4; à number += 4; number = number - 6; à number -= 6; number = number % 3; à number %= 3; number = number * (3 + 4); à number *= 3 + 4; // tricky

Integer Remainders

• % operator gives the remainder from integer division int dividend, divisor,remainder; dividend = 23; divisor = 5; remainder = dividend % divisor; The value of remainder is 3

Increment/Decrement

• ++ increment operator - Adds 1 to the value of a variable number++; or ++number; is equivalent to number = number + 1; • -- decrement operator - Subtracts 1 from the value of a variable number--; or --number; is equivalent to number = number - 1;

Expressions

• A constant value (2, -3.4, 'A') • A variable • A combination of variables, constants, and operators (+, -, /, *, %) • May contain parenthesis ( )

Programming Style

• Add spaces around operators • Break long statements into either multiple statements or multiple lines • Indent blocks for if, while, etc. if (x == 0){ statements; } • Adding blank lines between logical groups of statements

Algorithm

• Algorithm - A set of well defined logical steps to perform a task (leads to a solution) • Computer Program - Set of instructions for a computer to follow written in a programming language such as C++.

Software Life Cycle

• Analysis and specification • Design of the software (program) - Writing an algorithm o Define the input o Define the process (calculations) o Define the output

Arithmetic

• Arithmetic is performed with operators - + for addition - - for subtraction - * for multiplication - / for division - % remainder of division of integers (mod operator) 11 May 2020 CS2

Division of Integers

• Be careful with the division operator! - int / int produces an integer result (true for variables or numeric constants) int dividend, divisor, quotient; dividend = 5; divisor = 3; quotient = dividend / divisor; - The value of quotient is 1, not 1.666... - Integer division does not round the result, the fractional part is discarded!

Variable Initializations

• Before use, variables must be declared. • Variables may be initialized at the declaration. Otherwise, they will contain garbage. - int rank = 3; - string name = "John Smith"; • Multiple variables can be declared and initialized in one declaration statement int first = 3, second, third = 8; char middle = 'A';

Testing and Debugging

• Bug - A mistake in a program • Debugging - Eliminating mistakes in programs - Term used when a moth caused a failed relay on the Harvard Mark II computer. Grace Hopper and other programmers taped the moth in logbook stating: "First actual case of a bug being found."

Math Functions

• Built-in functions in expressions • Must include the library - #include § sqrt(x), abs(x), fabs(x), sin(x), cos(x), exp(x), log(x), log10(x), pow(b, p) • These functions return the calculated value

Default Format for Double

• C++ default format for double values is to display up to 6 digits. The number will be rounded accordingly. • Examples: - 30000.123 displays as 30000.1 - 300000.567 displays as 300001 - 3.123456 displays as 3.12346 - 30000000 displays as 3e+07

Data Types, Cont. (Characters and Boolean)

• Characters - char 1 byte - characters are surrounded by single quotes: 'A','6', '?', ' ', • Boolean - bool 1 byte o Has values of true or false

ASCII/Unicode Characters

• Characters have standard codes • These codes are called ASCII (American Standard Code for the Information Interchange) codes • Each ASCII code is 8 bits, see Appendix C • Unicode characters use 16-bit codes • Some codes - 'A' is 65 in decimal, 01000001 in binary - '1' is 49 in decimal, 0011001 in binary

Software Life Cycle, Cont.

• Coding/Implementation - Writing the algorithm in C++ - Correct syntax errors • Testing - Correcting logic errors - Correcting run-time errors • Maintenance and evaluation

Compiling

• Compile and Link using the command - g++ -Wall first.cc oThis creates an executable file called • a.out (Mac and linux) • a.exe (Windows) - g++ -Wall first.cc -o first oThis creates the executable • first (Mac and linux) • first.exe (Windows)

Security Objectives CIA Triad

• Confidentiality (or secrecy) - Information cannot be accessed by people who are not authorized to view/use it • Integrity - Unauthorized users cannot alter data and make it unreliable • Availability - Authorized users can always access information

Division of Doubles

• Division with at least one operand of type double produces the expected results. double divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor; - quotient = 1.6666...

Program Style - Indenting

• Document all programs. Include: - Author name - Date created/modified § Description of the program - Add documentations throughout the program - Always prompt the user for the input • The program output should be readable and clearly labeled.

Type Compatibilities

• In general store values in variables of the same type - This is a type mismatch: int intVar; intVar = 2.99; - intVar will contain the value 2. - You may get a warning

Data Types

• Integers (whole numbers): -4, 0, 100, etc. - int 4 bytes - short 2 bytes - long At least 4 bytes, 8 on 64-bit systems - long long At least 8 bytes - unsigned qualifier is used for positive integers only - Overflow/underflow

Programming Languages

• Machine Language - The only language the computer understands - Consists of series of binary codes - Difficult to program - 00100010111010001 • Assembly Language - ADD EAX, EBX • High level languages - C++, C, Java, Swift, .. - English-like - Easy to program - value = 5 + 6

Formatting Output

• Must #include • Specifying the width of the next output field - cout << setw(5) << 3; // prints ¨¨¨¨3 // 4 spaces followed by 3 - cout << setw(5) << 34; // prints ¨¨¨34

ASCII Codes Cont.

• Organization of the ASCII codes - All Capital letters are in sequence - All the small letters are in sequence - All the digits are in sequence - letters o A -- 65 a -- 97 0 -- 48 o B -- 66 b -- 98 1 -- 49 o .. .. .. o Z - 90 z - 122 9 -- 57

Other Formatting Flags

• Other flags - cout << left; // left-justify - cout << right; // right-justify (default) - cout << scientific; //scientific notation (default) - cout << setfill('*'); //use * as a fill character instead of space cout << setfill('*') << setw(5) << 3; //outputs ****3

Data Types, Cont.

• Real numbers - Numbers with a fractional part: 3.45, 3, - 3.4, 4.5e3, -45.67e-3 (scientific notation) - float 4 bytes, Å}1.18Å~10−38 to Å}3.4Å~1038 - double 8 bytes, ±2.23Å~10−308 to ±1.80Å~10308 - long double 10/16 bytes, 10-4932 to 104932 - double and long double provide more accurate floating point data

High Level Languages

• Require a compiler and a linker - Compiler o Translates a high-level language into machine language (creates the object code) o Finds parse/syntax errors: errors that violate the rules/grammar of the language - Linker o Links translated code with other built-in code and creates an executable file

First Bug

• September 9, 1947 • First Instance of Actual Computer Bug Being Found • At 3:45 p.m., Grace Murray Hopper records the first computer bug in her logbook as she worked on the Harvard Mark II. The problem was traced to a moth stuck between a relay in the machine, which Hopper duly taped into the Mark II's logbook with the explanation: "First actual case of bug being found."

Formatting, Cont

• Setting the precision - cout << setprecision(p); //p specifies the number of decimal places to show on the screen Example: double value = 123.23456; cout << setprecision(3) << fixed; cout << "Value = " << value; //displays Value = 123.235

Precision

• Setting the precision behaves differently for fixed and scientific (default) notation • For fixed: It specifies the number of digits to display after the decimal point • For scientific: It specifies the number of meaningful digits (before and after the decimal point)

Assignment Statement

• Syntax: <variable> = <exp> ; • Examples: length = 5; width = length; length = width = 6; //both length and width are assigned 6 salary = salary + 100; //salary will be the previous salary plus 100

Formatting, Cont.

• The flags settings are in effect until they are changed • Example: to display dollar amounts using a decimal point along with two decimal places cout << fixed << setprecision(2); cout << "The amount is $" << dollars;

Identifier naming style

• Use meaningful identifier (variable) names • Use lower case letters and one the following two styles: - Style 1 (camel case): salary, facultySalary - Style 2: salary, faculty_salary. • Use constant declaration whenever possible. Use all uppercase for constant names. - const double TAX_RATE = 0.25;

Constants

• Using the const qualifier - const double PI = 3.14; - const double TAX_RATE = 25.0; • Mistyping a number is a lot easier than mistyping a constant name

bool Expressions

• Values of type bool are treated like int expressions • true is stored as non-zero usually 1 • false is stored as 0

Main Program

• Variable Declaration - Identify a type, name, and an optional initial value. - Variable name is an identifier. - Naming an identifier must follow the following rules 1. Must start with a letter or an underscore '_' 2. Can only contain letters, digits, and underscores 3. Must not be a reserved word such as int, double, etc. - Choose an identifier name that is meaningful (describes its content)

Expressions Cont.

• What are the values of the following expressions? 3 + 2 * 6 3 / 4 * 2 3 * (3 + 4) // * is required here 3 + 19 % 5 3 * 6 % 25 6 + 3 % 7

Integer Overflow

• What happens when an integer reaches its maximum value? • Try it: short num = 32767; //max value num = num + 1; cout << num; num = -32768; //min value num = num - 1; cout << num;

Variable Declaration

• int first, second; - Define integer variable used to store values in memory locations. • int first = 3, second = 7; - Defines integer variables and initialize them.

string Type

• string is a class, different from the primitive data types discussed so far - Use double quotes around the text to store into the string variable - Requires the following #include directive #include <string> • To declare a variable of type string: string name = "John"; name = name + " Smith"; //concatenation

string Functions

• string name = "Bob Smith"; • name.length() - Returns the length of the string (9). • name.substr(pos, len) - returns the substring of length len starting at position pos. - If len is omitted, then the rest of the string is returned. - Examples: o cout << name.substr(0, 3); ///outputs Bob o cout << s.substr(4); ///outputs Smith


Conjuntos de estudio relacionados

Essay #8 Analyze continuities and changes in the political, economic, or cultural practices of Mongolian society ​between the rise of Chinggiss Khan and the demise of the Mongolian empire in the 15th century.

View Set

Software Security Midterm Exam Questions (Practice)

View Set

Basics of Property and Casualty Insurance

View Set

Chapter 6 Organizaltional Ethics + Readings

View Set

Percent composition and molecular formula (practice)

View Set

Chapter 17; Medical Asepsis and Infection Control

View Set