1 / 39

Midterm Exam Review

Midterm Exam Review . There are 7 basic data types in C++. They are: int Integer, machine dependent, current sys = 32 bits float Floating-point number, 32 bits. double Double precision floating point, 64 bits (long double 80 bits). char Character, 8 bits.

mkaiser
Download Presentation

Midterm Exam Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Midterm Exam Review There are 7 basic data types in C++. They are: int Integer, machine dependent, current sys = 32 bits floatFloating-point number, 32 bits. doubleDouble precision floating point, 64 bits (long double 80 bits). charCharacter, 8 bits. void“Nothing”, used to indicate that a function returns no value. wchar_tWide character, 16 bits, used for International characters. bool Boolean. Indicates true or false. Note: 8 bits = one byte

  2. Midterm Exam Review Identifiers Name used to identify variables, functions and objects Attributes of an Indentifier NameCorrespond to a location in the computer's memoryMust begin with a character or underscore which can then be followed by characters, underscores, and numbers TypeCan be one of the 7 basic machine defined type or a user defined type. Does not apply to Objects Size For simple variables, it is the size of “Type” For objects and structures, it is the size of data and not including the methods. For aggregate (arrays) datatype, use sizeof operator Value

  3. Midterm Exam Review Modifiers • Signed, unsigned, long, short can be applied to integers. • Signed and unsigned can be applied to characters. Example: unsigned inti; unsigned long inti; unsigned charc; Long can be applied to double. long doublex;

  4. Midterm Exam Review char (default) 8 bits -128 to 127 unsigned char 8 bits 0 to 255 unsigned short int 16 bits 0 to 65,535 short int 16 bits -32,768 to 32,767 long int 32 bits -2,148,483,648 to 2,147,483,647 int 32 bits -2,148,483,648 to 2,147,483,647 unsigned int 32 bits 0 to 4,294,967,295 unsigned long int 32 bits 0 to 4,294,967,295 double 64 bits 1.7E-308 to 1.7E+308 long double 80 bits 3.4E-4932 to 1.1E4932

  5. Midterm Exam Review • Storage class specifiers - Instructions to the compiler, on how a variable should be stored • Storage class • Duration during which the identifier exists in memory • Some are created, used and then destroyed • Some remain in memory throughout the execution of main • Two storage classes (category), automatic or static • Scope • Where object or data can be referenced in a program • Linkage • Where an identifier is known (current source file or external file) • C++ supports 5 specifiers • auto, extern, register, static, mutable

  6. Midterm Exam Review • auto, extern, register, static, mutable • auto • auto specifier declares a local variable. Since all variables are local by default, it is rarely used • extern • You can only define one copy of a global variable in a file for each program. This works fine if all functions are in one file. If the variable needs to be accessed across multiple files, the global variable is defined once and then declared as extern in each file that needs to access it. The extern specifier allows a variable to be made known to a module, but does not actually create that variable

  7. Midterm Exam Review • register • The register storage class specifier tells the compiler to store this variable in such a way that it can be accessed as soon as possible, like in a register of the CPU or cache memory. Can be used for any type of data. Typically used variables in loops. You can request, but Compiler decides if the variable will be register type or not.

  8. Midterm Exam Review • static • Makes a variable permanent similar to global, but static vars are only visible to functions they belong to. Effect of static on local variable is different than on global variable.STATIC LOCAL VARIABLEStatic variable is declared inside a function, global variables are declared outside of all the functions (including main). • When a static is applied to a local variable, it’s value is saved when the function ends and is restored when the function is restarted. It is initialized only once when the program execution begins. The difference between a static and global variable is that static variable is only visible to the function it is declared in, global variables are visible to all the functions.STATIC GLOBAL VARIABLEWhen static specifier is applied to a global variable, it is visible only to the functions that belong to this file. It is invisible to functions in other files, which may be part of the same program

  9. Midterm Exam Review Operators • Arithmetic, Logical, Relational and Bitwise. Arithmetic +, -, /, *, % Increment ++ Postfix or Prefix decrement -- Postfix or Prefix Relational >, >=, <, <=, ==, != • Returns true or false. Logical &&, ||, ! • Returns true or false. Bitwise &, |, ^, ~, <<, >>

  10. Midterm Exam Review • Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator (also called C++ shortcut) • Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; • Examples of other assignment operators include: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)

  11. Midterm Exam Review Relational Operators>, >=, <, <=, ==, != Logical Operators&&, ||, ! If a is greater than b and c does not equal d then execute code if ( a > b && c != d) { statements . . . .; } if ( i = 0 && j >= 5 ) note: logic ERROR, but not compiler error if (( iValue = 10 || !(iValue == 10)) && fValue != 2.5) if (cValue && ! (fValue - 2.5) || (iValue -10)) if (fValue - 2.5 || iValue != 10 || ! cValue )

  12. Midterm Exam Review • Control Structures – Seven Structures • Sequence structure • Built into C++. Programs executed sequentially by default • Selection structures • C++ has three types • if • if/else • switch • Repetition structures • C++ has three types • while • do/while • for

  13. Midterm Exam Review • Repetition structures - while loop • May require • initializing data before starting the loop • incrementing loop counter at the end initialization; while ( loopContinuationTest expression) { statement . . .; statement . . .; increment; }

  14. Product <= 1000 true product = 2 * product false Midterm Exam Review • Repetition structures - while loop while ( product <= 1000) { product = 2 * product; }

  15. Midterm Exam Review • Repetition structures - for loop • Three distinct parts • Initialization, test for condition, increment • Initialization and increment as comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) { statement . . .; statement . . .; cout << j + i << endl; }

  16. Midterm Exam Review • Repetition structures – do/while loop • May require • initializing data before starting the loop • May require incrementing loop counter data at the end • Executes the content of the loop at least once, then the condition is checked initialization; do { statement . . .; statement . . .; increment; } while ( loopContinuationTest expression);

  17. Midterm Exam Review • Selection structures • if/else • Only one statement will execute • What happens if you put ( grade >= 80 ) first ? Logic error if ( grade >= 90 ) { cout << “Student got an A“ << endl; } else if ( grade >= 80 ) { cout << “Student got a B“ << endl; } else { cout << “Student just passed“ << endl; }

  18. false true “Passed” next statement “Failed” grade >= 60 Midterm Exam Review • Selection structures if/else • Ternary conditional operator (?:) • Takes 3 args (condition, value if true, value if false) cout << ( grade >= 60?“Passed”:“Failed” );

  19. Midterm Exam Review • Selection structures • switch statement • Can only test against integer and character constants • switch differs from if in the following ways • switch can only test for equality; expression in the if statement can be of any time • No two case constants in the same switch can have same values • A switch statement is usually more efficient then nested if

  20. switch ( grade ) { case 'A':  // grade was uppercase A case 'a':  // or lowercase a++aCount; break;  // necessary to exit switchcase 'B':  // grade was uppercase B case 'b':  // or lowercase b ++bCount; break; case '\n': // ignore newlines,  default:   // catch all other characters cout << "Incorrect letter grade entered.“ << " Enter a new grade." << endl;break;  // optional}

  21. Midterm Exam Review • Break • Causes immediate exit from a while, for, do/while or switch structure • Program execution continues with the first statement after the structure • Common uses of the break statement: • Escape early from a loop • Skip the remainder of a switch structure • Continue • Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop

  22. Midterm Exam Review Function What is a function prototype? Write the prototype for a function ‘myFunc1’ that takes • two integers, one char and one double as arguments and returns a variable of type double   double myFunc1 (int, int, char, double);

  23. Midterm Exam Review Function • What are its components? • return type, function name, type, Name [return type] <function name> ( [typeparam_Name_1, …. type param_Name_n] ) Scope of variables Variables declared global Variable declared in main program Variable declared in a function Variables that are static Variable that have extern qualifier

  24. Midterm Exam Review Overloaded Functions • multiple functions with same name but different num of arguments or different argument type void mySort (int &x, int &y, int &z); // declaration of function mySort; void mySort (float &x, float &y, float &z); // declaration of function mySort; void mySort (char &x, char &y, char &z); // declaration of function mySort; Functions with default values void myfunc (int x, int y=9, int z=10); myfunc(a, b, c); //valid myfunc(a, b); //valid myfunc(a); //valid myfunc(a, , c); //INVALID

  25. Midterm Exam Review • Arrays • A way to declare a group of related data items • Static entity – Size is determined at the time of declaration and remains the same throughout program (compile time) Example: int a1, a2, a3, a4; int a[4]; a is an array of four elements of type int. Elements are a[0], a[1], a[2], a[3]

  26. Midterm Exam Review • Initialization int n[ 5 ] = { 1, 2, 3, 4, 5 }; int n[ 5 ] = { 0 }; Sets all the elements to 0 • Character arrays - Strings char string1[] = "hello"; (String has a NULL at the end) char string2[] = { 'h', 'e', 'l', 'l', 'o', '\0' }; int iArray[25]; // elements are from 0 to 24 for ( int i = 0; i<25; i++ ) iArray[ i ] = i; cin >> setw(24) >> string1; // reads up to 24 chars for ( int i = 0; string1[ i ] != '\0'; i++ ) cout << string1[ i ] << ' '; cout << endl << “string1 is: " << string1 << endl; cout << endl;

  27. Midterm Exam Review • Function prototype void modifyArray( int intArray[], int arraySize ); • From main, it will be called as modifyArray( intArray, 25 ); • Function declaration void modifyArray ( int intArray [], int arraySize ) { for ( int j = 0; j < arraySize; j++ ) intArray[j] = 10*j + 1; return; }

  28. Midterm Exam Review • Character constant • Integer value of a character • Single quotes • 'z' is the integer value of z, which is 122 • char z = 122; • String • Series of characters treated as one unit • Can include letters, digits, special characters +, -, * ... • String literal (string constants) • Enclosed in double quotes, for example: "I like C++" • Array of characters, ends with null character '\0' • Strings are constant pointers (like arrays) • Value of string is the address of its first character

  29. 5Midterm Exam Review • String assignment • Character array: char color[] = "blue"; • Creates 5 element char array, color, (last element is '\0') • variable of type char * char *colorPtr = "blue"; • Creates a pointer to string “blue”, colorPtr, and stores it somewhere in memory

  30. Midterm Exam Review 1.     Read one keystroke from the keyboard into a variable and if the user entered a lowercase y, then display a message to the screen. char ch; cout << endl << “Please enter a character :” ; if (ch == ‘y’) cout << endl << “You have entered ‘y’” << endl;

  31. Midterm Exam Review 2.Given integer variables a, b, and c that have already been initialized with values, display to the screen the largest value (only) that is contained in a, b or c. int max; max = a; if (b > max) max = b; if (c > max) max = c; cout << max << endl;

  32. Midterm Exam Review 3.Write a loop that will compute the sum of all odd integers from 1 to 23. int i; for (i = 1; i <= 23; i++) { if (i%2 != 0) sum += i; }

  33. Midterm Exam Review 1. The function prototype double mySqrt( int x ); • a)    Declares a function called mySqrt which takes an integer as an argument and returns a double • b)    Defines a function called double which calculates square roots • c)    Defines a function called mySqrt which takes an argument of type x and returns a double • d)    Declares a function called mySqrt which takes a double as an argument and returns an integer 2.     In function prototype double mySqrt( int x ); the return value is represented by: • a) mySqrt • b) double • c) int x • d) mySqrt( int x );

  34. Midterm Exam Review 5.Write the prototype for a function ‘myFunc1’ that takes an array of int and one integer as arguments and returns a variable of type double   double myFunc1 (int nArr[], int nSize);

  35. Midterm Exam Review 6.     Write a function “Sort2Int” and its prototype (declaration). This function takes two integers “by reference”, swap the value of the two integers and returns the sum of the two integers. The return type is an int.Do not write the main program. If you use variables, include their declaration. int Sort2Int (int &, int &); int Sort2Int (int &x, int &y) { int temp = 0; temp = x; x = y; y = temp; return x + y; }

  36. Midterm Exam Review  7.Given the following do-while loop, write a test condition so that loop will quit if the count is 23. For each pass of the loop print the loop count int i = 0; do { cout << “Count is “ << i << endl; i++ } while (i < 23);

  37. Midterm Exam Review 8.Given the following for and while loop, write a test condition so that loop will quit if the count is 23. For each pass of the loop print the loop count for (int i = 0; i < 23; i++ ) { cout << “Count is “ << i << endl; } int i = 0; while (i < 23) { cout << “Count is “ << i << endl; i++ }

  38. Midterm Exam Review 13. Display the following pattern to the screen. Assume the pattern will be in the upper left corner of the output screen. Write a complete program and submit hard copy of the .cpp file. Use the name exam1.cpp. You may use this page as scratch paper (I will grade what you submit) You may only use the following cout statements as the way to display to the screen. You must use two (nested) for loops (one outer and one inner for loop). Points will be taken off for code that is unnecessarily complicated. cout << "*" ; or cout << "X" ; or cout << “Y” ; or cout << endl ; Notice, There 8 “X”s and as the number of lines increase, the number of “X” decrease. *XXXXXXXXY *XXXXXXXY *XXXXXXY *XXXXXY *XXXXY *XXXY *XXY *XY *Y

  39. Midterm Exam Review #include <iostream> using namespace std; int main() { for (int j=0; j<9; j++) { cout << ‘*’ ; for (int i=8; i-j>0; i--) { cout << ‘X’ ; } cout << ‘Y’ ; cout << endl; } return 0; }

More Related