CS Final
Write the following formula in C++: C = √(A2 + B2)
#include <iostream> #include <cmath> int main() { double A, B, C; cout << "Enter the value of A: "; cin >> A; cout << "Enter the value of B: "; cin >> B; C = sqrt(A * A + B * B); cout << "The value of C is: " << C << endl; return 0; }
Write a complete C++ program that will read some integer values (sorted from lowest to highest, no more than 1000) from the data file and find the median value
#include <iostream> #include <fstream> #include <vector> using namespace std; double findMedian(const vector<int>& values) { int size = values.size(); if (size % 2 == 0) { // If the number of elements is even, average the middle two elements return (static_cast<double>(values[size / 2 - 1]) + static_cast<double>(values[size / 2])) / 2.0; } else { // If the number of elements is odd, return the middle element return static_cast<double>(values[size / 2]); } } int main() { ifstream inputFile("data.txt"); // Replace "data.txt" with your file name if (!inputFile.is_open()) { cout << "Unable to open file." << endl; return 1; } vector<int> values; int value; // Read values from the file into a vector while (inputFile >> value) { values.push_back(value); } inputFile.close(); // Calculate the median double median = findMedian(values); cout << "Median value: " << median << endl; return 0; }
Write a while loop that will read all data items from a data file until no more data is found.Leave the body of the loop empty
#include <iostream> #include <fstream> int main() { ifstream inputFile("data.txt"); // Replace "data.txt" with your file name // Check if the file opened successfully if (!inputFile.is_open()) { cout << "Unable to open file." << endl; return 1; } // Reading data items until no more data is found while (inputFile >> /* variable or data type */) { // The body of the loop is left empty as per the request } // Close the file after reading all data inputFile.close(); return 0; }
Write a complete C++ program that will ask the user for their first, last name and then display the number of letters in their name back to the console window
#include <iostream> #include <string> using namespace std; int main() { string firstName, lastName; // Ask for the user's first and last names cout << "Enter your first name: "; cin >> firstName; cout << "Enter your last name: "; cin >> lastName; // Calculate the total number of letters in the name int totalLetters = firstName.length() + lastName.length(); // Display the number of letters back to the user cout << "Total number of letters in your name: " << totalLetters << endl; return 0; }
Write a function to perform a linear search of a string array for a match
#include <iostream> #include <string> using namespace std; // Function to perform linear search on a string array // Returns the index of the found element or -1 if not found int linearSearch(const string arr[], int size, const string& target) { for (int i = 0; i < size; ++i) { if (arr[i] == target) { return i; // Element found, return index } } return -1; // Element not found } int main() { string arr[] = {"apple", "banana", "orange", "grape", "kiwi"}; int size = sizeof(arr) / sizeof(arr[0]); string target = "orange"; int result = linearSearch(arr, size, target); if (result != -1) { cout << "Element found at index " << result << endl; } else { cout << "Element not found" << endl; } return 0; }
Set up a do-while loop that will validate the user's input when the user is asked to enter valuesbetween 0 and 100 inclusive
#include <iostream> int main() { int userInput; do { cout << "Enter a value between 0 and 100 inclusive: "; cin >> userInput; // Check if the input is within the specified range if (userInput < 0 || userInput > 100) { cout << "Invalid input. Please enter a value between 0 and 100." << endl; } } while (userInput < 0 || userInput > 100); cout << "Valid input received: " << userInput << endl; return 0; }
Set up a FOR loop that will iterate 100 times, and values of the loop control variable must startwith 0 and be only even numbers
#include <iostream> int main() { for (int i = 0; i < 100; i += 2) { // Process even numbers (i) cout << i << " "; } cout << endl; return 0; }
Set up a FOR loop that will iterate 109 times; the initial value of the loop control variable isirrelevant
#include <iostream> int main() { for (int i = 0; i < 109; ++i) { // Process each iteration (i) cout << "Iteration: " << i << endl; } return 0; }
Write a function to perform a binary search of an integer array for a match
#include <iostream> using namespace std; // Function to perform binary search on an integer array // Returns the index of the found element or -1 if not found int binarySearch(int arr[], int size, int target) { int left = 0; int right = size - 1; while (left <= right) { int mid = left + (right - left) / 2; // Check if the middle element is the target if (arr[mid] == target) { return mid; // Element found, return index } // If target is greater, ignore left half else if (arr[mid] < target) { left = mid + 1; } // If target is smaller, ignore right half else { right = mid - 1; } } return -1; // Element not found } int main() { int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; int size = sizeof(arr) / sizeof(arr[0]); int target = 12; int result = binarySearch(arr, size, target); if (result != -1) { cout << "Element found at index " << result << endl; } else { cout << "Element not found" << endl; } return 0; }
What is the overall Anatomy of a C++ program... fill in the blanks: _________ _____________ int main(){ ________}
#include <iostream> using namespace std; int main() { variables and data; return 0; }
Given an array X exists with 45 elements filled with integer data, find the sum of all elements that contain a value greater than 50.
#include <iostream> int main() { int X[45]; // Assuming X is an array of 45 elements filled with integer data // Your code to fill the array with data goes here int sum = 0; for (int i = 0; i < 45; ++i) { if (X[i] > 50) { sum += X[i]; // Add the value to sum if it's greater than 50 } } std::cout << "The sum of elements greater than 50 is: " << sum << std::endl; return 0; }
Write an if-else statement for problem 34
#include <iostream> int main() { int score; char grade; cout << "Enter the student's score: "; cin >> score; if (score >= 90 && score <= 100) { grade = 'A'; } else if (score >= 80 && score < 90) { grade = 'B'; } else if (score >= 70 && score < 80) { grade = 'C'; } else if (score >= 60 && score < 70) { grade = 'D'; } else if (score >= 0 && score < 60) { grade = 'F'; } cout << "The student's grade is: " << grade << endl; return 0; }
Write an if-else-if statement to assign letter grades based on student scores. 90-100 A, 80-89 B,etc
#include <iostream> int main() { int score; char grade; cout << "Enter the student's score: "; cin >> score; if (score >= 90 && score <= 100) { grade = 'A'; } else if (score >= 80 && score < 90) { grade = 'B'; } else if (score >= 70 && score < 80) { grade = 'C'; } else if (score >= 60 && score < 70) { grade = 'D'; } else if (score >= 0 && score < 60) { grade = 'F'; } cout << "The student's grade is: " << grade << endl; return 0; }
Complete the following C++ program segment to display a pattern like the one shown below (use two nested for loops in your solution). *$* *$**$* *$**$**$* *$**$**$**$* *$**$**$**$**$*
#include <iostream> using namespace std; int main() { int rows = 5; // Number of rows in the pattern for (int i = 1; i <= rows; ++i) { for (int j = 1; j <= i; ++j) { if (j % 2 == 0) { cout << "**"; } else { cout << "*$"; } } cout << endl; } return 0; }
Write a segment of code that will select a random number between 0 and 99
#include <iostream> #include <cstdlib> // Include for rand() and srand() #include <ctime> // Include for time() using namespace std; int main() { // Seed the random number generator using current time srand(static_cast<unsigned int>(time(nullptr))); // Generate a random number between 0 and 99 int randomNumber = rand() % 100; // rand() generates a number between 0 and RAND_MAX cout << "Random number between 0 and 99: " << randomNumber << endl; return 0; }
Given that a data file called "in.dat" contains unordered integer values, one per line, write C++code to find the average of the numbers.
#include <iostream> #include <fstream> int main() { std::ifstream inputFile("in.dat"); // Open the input file if (!inputFile.is_open()) { std::cout << "Unable to open file." << std::endl; return 1; } int number; int sum = 0; int count = 0; // Read numbers from the file and calculate the sum and count while (inputFile >> number) { sum += number; // Add each number to the sum count++; // Increment the count for each number read } inputFile.close(); // Close the input file if (count > 0) { double average = static_cast<double>(sum) / count; // Calculate the average std::cout << "The average of the numbers is: " << average << std::endl; } else { std::cout << "No numbers found in the file." << std::endl; } return 0; }
Set up a while loop that reads data from a file until there is no more data and counts how many items were read
#include <iostream> #include <fstream> int main() { std::ifstream inputFile("data.txt"); // Replace "data.txt" with your file name int count = 0; // Counter to track the number of items read int value; // Variable to store each read item if (!inputFile.is_open()) { cout << "Unable to open file." << endl; return 1; } while (inputFile >> value) { // Process each item read (you can perform additional operations here) count++; } cout << "Number of items read: " << count << endl; inputFile.close(); return 0; }
Given that a data file called "in.dat" contains unordered integer values, one per line, write C++code to find the largest and the smallest values.
#include <iostream> #include <fstream> #include <limits> int main() { std::ifstream inputFile("in.dat"); // Open the input file if (!inputFile.is_open()) { std::cout << "Unable to open file." << std::endl; return 1; } int number; int smallest = std::numeric_limits<int>::max(); // Set smallest to maximum possible integer value int largest = std::numeric_limits<int>::min(); // Set largest to minimum possible integer value // Read numbers from the file and find the smallest and largest values while (inputFile >> number) { if (number < smallest) { smallest = number; // Update smallest if a smaller number is found } if (number > largest) { largest = number; // Update largest if a larger number is found } } inputFile.close(); // Close the input file if (smallest == std::numeric_limits<int>::max() || largest == std::numeric_limits<int>::min()) { std::cout << "No numbers found in the file." << std::endl; } else { std::cout << "The smallest value is: " << smallest << std::endl; std::cout << "The largest value is: " << largest << std::endl; } return 0; }
Write an if statement that will display "Correct" in the console window if the user's answer is "Thomas."
#include <iostream> #include <string> // Include the string header for using strings int main() { string userAnswer; // Assuming the user's answer is stored in a string // Get the user's answer (you can replace this with your input logic) cout << "Enter your answer: "; cin >> userAnswer; // Check if the user's answer is "Thomas" if (userAnswer == "Thomas") { cout << "Correct" << endl; } return 0; }
Write code to swap contents of array elements ary[4] with ary[9]
#include <iostream> int main() { int ary[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Displaying the array before swapping cout << "Array before swapping: "; for (int i = 0; i < 10; ++i) { cout << ary[i] << " "; } cout << endl; // Swapping elements ary[4] and ary[9] int temp = ary[4]; ary[4] = ary[9]; ary[9] = temp; // Displaying the array after swapping cout << "Array after swapping: "; for (int i = 0; i < 10; ++i) { cout << ary[i] << " "; } cout << endl; return 0; }
Knowing that char data type is stored internally as an integer... write a statement that willdisplay 32◦○ F ... note the degrees symbol (ASCII 167)
#include <iostream> int main() { char degreesSymbol = 167; cout << "32" << degreesSymbol << " F" << endl; return 0; }
Write code that will initialize array scores that can hold 50 student scores to zero
#include <iostream> int main() { const int numOfStudents = 50; int scores[numOfStudents] = {0}; // Initializes all elements to zero // Outputting the initialized array for verification cout << "Initialized scores array:" << endl; for (int i = 0; i < numOfStudents; ++i) { cout << scores[i] << " "; } cout << endl; return 0; }
Given that there are two integer arrays in your program and you know that the first one has 20 elements and the second one has 50, write code to copy all of the elements of the array one to corresponding elements of array two
#include <iostream> int main() { const int size1 = 20; // Size of the first array const int size2 = 50; // Size of the second array int array1[size1]; // First array with 20 elements (assume it's populated) int array2[size2]; // Second array with 50 elements // Copy elements from array1 to array2 for (int i = 0; i < size1; ++i) { // Ensure we don't go beyond the bounds of array2 if (i < size2) { array2[i] = array1[i]; } else { // Handle the case where array1 is larger than array2 cout << "Array1 has more elements than Array2. Cannot copy all elements." << endl; break; } } // Displaying array2 after copying elements cout << "Array2 after copying elements from Array1: "; for (int i = 0; i < size2; ++i) { cout << array2[i] << " "; } cout << endl; return 0; }
Set up a sentinel control while loop which will iterate until value -1 is encountered
#include <iostream> int main() { int value; cout << "Enter values (-1 to exit):" << endl; // Loop continues until the sentinel value (-1) is encountered while (true) { cout << "Enter a value: "; cin >> value; if (value == -1) { break; // Exit the loop if the sentinel value is entered } // Process the entered value (you can perform additional operations here) cout << "Entered value: " << value << endl; } cout << "Exited loop. Sentinel value (-1) encountered." << endl; return 0; }
Using a stream insertion operator, write a C++ statement that would result in "It's cold outside."printed to the console window.
#include <iostream> int main() { std::cout << "It\'s cold outside." << std::endl; return 0; }
In order to use the string data type, what file must be included in your C++ program?
#include <string>
Write a truth table for the Boolean && operator and || operator
&&: only true if both are true, false if both are false or only one is false ||: true if 1 or more is true and false if both are false
What is the value stored in x given the code below: 1. int x; 2. x = 10 % 5
0
What is the output of the following code segment? n = 1; while (n <= 9) { if ((n % 3) == 1) cout << n << ' '; n++; } a. 1 2 3 4 5 b. 1 1 1 1 1... forever c. 2 5 8 d. 1 4 7 e. None of the above
1 4 7
What are the rules for naming identifiers and functions in C++?
1.valid characters: Identifiers can consist of letters (both uppercase and lowercase), digits, and the underscore character ('_'). The first character of an identifier cannot be a digit. 2.No Spaces or Special Characters: Identifiers cannot contain spaces or most special characters (except for the underscore) 3.Case-Sensitivity: C++ is case-sensitive, so MyVariable, myvariable, and MYVARIABLE are considered different identifiers. 4.Reserved Keywords: Identifiers cannot be the same as C++ keywords (e.g., int, for, while). These are reserved for specific language purposes and cannot be used as identifiers. 5.Naming Conventions: Camel Case or Underscore Naming: It's a convention to use either camel case (e.g., myVariableName) or underscores (e.g., my_variable_name) for naming variables and functions. Meaningful and Descriptive Names: Choose identifiers that convey the purpose or meaning of the variable or function. 6.Length Limit: There's no fixed limit on the length of an identifier, but long identifiers can make code harder to read. It's advisable to keep them reasonably short while remaining descriptive. 7.Starting with Underscore: Identifiers starting with an underscore followed by a capital letter or another underscore are reserved for the implementation (e.g., _Variable, __Variable).
What is the result of this statement: double quotient = 0.0; quotient = 5 / 2;
2.0
What will these two statements display in the console window? cout << 13 / 5.0; cout << 91.0 / 7; cout << 91 / 6;
2.6 , 13, and 15
What's the output of the following statement? cout << 4 * 5 / (1 + 3 % 10) << endl;
5
Define what a counter variable is
A counter variable is a variable used to keep track of counts or iterations within a loop or process. It's typically employed to control the number of times a loop iterates or to count occurrences or increments during program execution. ex: for (int i = 0; i < 5; ++i) { // Loop body }
What is the best use of a do-while loop?
A do-while loop is particularly useful when you want to execute a block of code at least once, regardless of whether the loop condition is initially true or false. Its primary advantage lies in its structure, ensuring that the loop body is executed before checking the loop condition.
What is a newline escape sequence? What does it do? Is there another way to accomplish thesame thing?
A newline escape sequence in C++ is represented by \n. It's a special sequence of characters that represents a newline character, which causes the cursor to move to the beginning of the next line when output to the console.Another way to accomplish the same effect without using escape sequences is by using multiple std::cout statements or by including std::endl (which inserts a newline character and flushes the output buffer) after the text you want to display on a new line.
Define what an accumulator variable is
An accumulator variable is a variable used to accumulate or collect values by incrementally adding or accumulating them over the course of a program or a specific process. It's commonly employed to calculate a sum, total, or aggregate value by continuously adding new values to an existing total. ex: int sum = 0;
C++ has three types of arithmetic operators... list them and give examples.
Binary- addition, subtraction, multiplication, division, modulus unary - plus (+=) and minus (-=) increment/decrement- i++ and i--
Is the expression ( 5 * 5 != 20 || 13 % 5 == 1 ) evaluated to True or False?
False
Is this a valid statement? char letters[10] = "Garbage";
In C++, "Garbage" is a string literal, and if you try to initialize a character array of size 10 with this string, it would result in a compilation error because the string literal "Garbage" consists of 8 characters (including the null terminator '\0'), which exceeds the allocated size of the array (10 characters). To initialize a character array with a string literal, the size of the array must be large enough to accommodate the string along with the null terminator.
What are keywords? Give an example
Keywords in C++ are predefined reserved words that have specific meanings and functionalities within the language. These words have predefined purposes and cannot be used for other purposes such as naming variables, functions, or classes ex: int, if, else
Is this a valid statement? char letterA = "A";
No because its supposed to be 'A' with single quotes because its a character not a string
What are preprocessor directives, and where do they go in the program?
Preprocessor directives are commands interpreted by the preprocessor, a tool that runs before the actual compilation of a C++ program. They are used to provide instructions to the preprocessor, which performs various tasks like file inclusion, macro definitions, conditional compilation, etc. Preprocessor directives start with a # symbol and are written at the beginning of a C++ program, typically before any code. They are not terminated by a semicolon (;).
Semicolons end each C++ statement, but some other program statements do not require asemicolon. What are they?
Preprocessor directives like #include and function definitions because they use braces
What is "procedural programming"?
Procedural programming is a programming paradigm that involves writing code in a linear, step-by-step manner. In this paradigm, a program is divided into procedures, functions, or routines that contain a series of computational steps to be carried out. These procedures can take inputs, perform operations, and produce outputs.
What are programmer-defined identifiers? Give an example
Programmer-defined identifiers in C++ are names created by the programmer to represent variables, functions, classes, or any other user-defined entity within the program. These identifiers can be chosen by the programmer to make the code readable and meaningful. They follow certain rules, such as starting with a letter or underscore, and can consist of letters, digits, and underscores. Here's an example illustrating programmer-defined identifiers: #include <iostream> int main() { int userAge; // 'userAge' is a programmer-defined identifier for an integer variable userAge = 25; // Assigning a value to the 'userAge' variable std::cout << "The user's age is: " << userAge << std::endl; // Outputting the value return 0; }
What are the two ways to create comments in C++?
Single-Line Comments: Single-line comments begin with // and continue until the end of the line. Anything after // on that line is considered a comment and is ignored by the compiler. Multi-Line Comments (or Block Comments): Multi-line comments start with /* and end with */. They can span multiple lines and can be used to comment out multiple lines of code or text.
What is the best use of a for loop?
The for loop is especially useful when you know the number of iterations required or have a clear control variable to manage the loop execution. Its structure allows concise initialization, condition checking, and iteration updates in a single line, making it versatile for various scenarios. Here are some optimal uses of a for loop:
What type of loop is the while loop? Pre-test or post-test and why?
The while loop is a pre-test loop because it checks the loop condition before executing the loop body. If the condition is initially false, the loop body is not executed at all. The condition is evaluated before entering the loop, and if it's false from the beginning, the loop will never execute.
How would you verify that the results obtained by your program satisfy the original requirements?
To verify that the results obtained by the program satisfy the original requirements, you can manually perform the calculations step by step according to the given expression and check if the output matches.
What is the difference between ++i and i++
With ++i, the increment happens before the value is used. With i++, the value is used first and then incremented afterward.
Evaluate the following expression given a=10, b=8, and c=0bool hardquestion = a==12 && !(b*c % 5 - 30*c/a || 20%c+a*b%c)
a == 12 will be 10 == 12, which evaluates to false. b * c % 5 - 30 * c / a will be 8 * 0 % 5 - 30 * 0 / 10, which simplifies to 0 - 0, resulting in 0. 20 % c + a * b % c will be 20 % 0 + 10 * 8 % 0, resulting in division by zero which is undefined behavior.
Define what a flag variable is
a variable specifically used to control or signal a condition within a program. It typically acts as a boolean variable (having a value of true or false) that indicates whether a certain condition has been met or whether a specific situation exists in the program.
Assume a=2, b=4, c=6 and determine values of the following: a. A==4 || b>2 b. 6 <= c && a>3 c. 1 !=b && c != 3 d. A >= -1 || a <=b e. ! (a>2)
a. true b. false c. true d. true e. true
Assume w=5, x=4, y=8, and z=2 what will be stored in Result (integer variable) a. Result = x+y; b. Result = z*2; c. Result =y / x; d. Result = y - z; e. Result =w%3;
a: 12 b: 4 c: 2 d:6 e: 2
What would be the result of these statements? int i=0; ary[1]; ary[i++]=99; ary[++i]=99;
array[0] will be 99 array[1] will be undefined array[2] will be 99
Write an if statement that will display "Game over" if either player1 (bool) has won or the number of turns exceeded 30
bool player1HasWon = true; // Assuming player1's win status int numberOfTurns = 25; // Assuming the number of turns if (player1HasWon || numberOfTurns > 30) { cout << "Game over" << endl; }
Show what would be in the elements of the array letters after the statement in problem 23 executes
char letters[8] = "Garbage";
Show what would be stored in the computer's memory for each variable: char letter = 'A'; string letter = "A";
char would store a single character, string would store a sequence of letters
Declare an array variable capable of holding prices of items in a store
const int
Given that variable myname contains student first and last name and the variable class containsstudent class rank, write a cout statement that will produce a message similar to "Josh Simms isa Senior at BGSU"
cout << myname << " is a " << classRank << " at BGSU" << endl;
Declare an identifier capable of holding the value Pi
double
What is the difference between i=i+1 and i+=1
i = i + 1: This expression explicitly assigns the value of i + 1 back to the variable i. It performs addition by taking the current value of i, adding 1 to it, and then assigning the result back to i. i += 1: This is a compound assignment operator in C++. It's a shorthand notation for incrementing i by 1. It performs the same operation as i = i + 1, but in a more concise form. It's often used for clarity and brevity in code.
Which element is 97 stored in given the code below: int scores[ ] = {83, 62, 77, 97};
index 3 but the 4th element
Declare an identifier capable of holding a whole number
int
Be able to trace a C++ function that will compute N factorial
int NFact( int N) { int factResult; if (N <= 1) { factResult = 1; } else { factResult = N*NFact (N-1); } return factResult; }
Write a C++ statement that assigns value of product of 23 and 8 to variable X.
int X = 23 * 8;
Why is the indentation of code important
it improves readability and it is standardized
What does the following function do when it is called for the first time? int IntArr [10]; int M = 0; mystery (IntArr, M); //function call--void mystery (int array [ ], int &N) //function header{int val; cin >> val; array[N] = val; N++; } a. Sums the values in the array b. Inserts a new value in the last element of the array c. Adds a value to each element of the array d. Inserts a new value at the first element of the array e. None of these
it reads an integer from the standard input and assigns it to the first element of IntArr and then increments the value of M by 1
Is int main() same as int Main() ?
no
Declare an identifier capable of holding a series of letters
string
What three main errors programmers make
syntax errors: These errors occur when the code violates the rules of the programming language. Syntax errors prevent the code from being compiled or executed. They include mistakes such as misspelled keywords, missing semicolons, incorrect use of parentheses, etc logic errors: Logic errors, also known as semantic errors, occur when the code runs without syntax errors but does not produce the expected or desired output. These errors occur due to flaws in the program's logic or algorithm. For instance, a miscalculation in a formula, incorrect conditional statements, or incorrect loop conditions can lead to logic errors runtime errors: Runtime errors occur during the execution of the program. They might not be identified until the program is running and can cause the program to terminate abnormally. Common runtime errors include division by zero, accessing an invalid memory location, stack overflow, etc.
Given that p and q are Boolean expressions, prove that p && q == !( !p || !q)
the ! proves that the second statement is not true, and the second statement is opposing the first.