Compsi Final exam

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

a = 5; bool x = true; int b = 2; int c = 4; !(a= =b) true or false? (x || c < 2) true or false? ((c+1>=a) && (4<=a*2)) true or false?

!(a= =b) true (x || c < 2) true ((c+1>=a) && (4<=a*2)) true

Write a program using class and object for the following task: a) Create a class "car" b) Add data members (variables) such as mileage, color and price for the class car and make it as public . c) Add some member functions such as brake(), reverse(), gear(0) etc ., and keep it as private . d) Then create an Object of the class named "Benz" which should use these data members and member functions. e) Finally, print all the members and functions of object Benz.

#include<iostream> using namespace std; class Car { private: string Company_name; string model_name; string fuel_type; int mileage; double price; public: void setData(string cname, string mname, string ftype, int m, double p) { Company_name=cname; model_name=mname; fuel_type=ftype; milege=m; price=p; } void displayData() { cout<<"Car properties : "<<endl; cout<<"Company's name is " <<Company_name<<endl; cout<<"Model name is " <<model_name<<endl; cout<<"CFuel type is " <<fuel_type<<endl; cout<<"Milege is " <<milege<<endl; cout<<"Price is " <<price<<endl; } }; int main(){ Car car1, car2, car3, car4; car1.setData("Benz", "C300", "petrol", 23, 60000); car1.displayData(); car2.setData("Benz", "C300", "petrol", 23, 60000); car2.displayData(); car3.setData("Benz", "C300", "petrol", 23, 60000); car3.displayData(); car4.setData("Benz", "C300", "petrol", 23, 60000); car4.displayData(); return 0; }

Rewrite the following code using ternary operator. if ( Your Grade <= 90) cout<<"Not Satisfactory"; else cout<<""Great Job!";

(YourGrade <= 90) ? "Great Job" : "Not Satisfactory";

Write a short C++ program that outputs the following: * * * ******** Time flies like an arrow * * *

) int main () { cout << " *" << endl; (5 spaces) cout << " *" << endl; (6 spaces) cout << " *" << endl; (7 spaces) cout << " ******** time flies like an arrow" << endl; cout << " *" << endl; (7 spaces) cout << " *" << endl; (6 spaces) cout << " *" << endl; (5 spaces) }

What is output by the following code fragment? int num = 0; int max = 10; while(num < max) { cout<<"num<<endl; num += 2; }

0 2 4 6 8

idea of classes?

A class is a blueprint (plan or template). With one you can print multiple objects.

array vs vector in c++

Array is stored in a fixed container while vector is a dynamic array which is flexible

In MATLAB, if b = 4 and c=5, write the output of the following ~(b==c & b==4)

False?

function in matlab & how to create

accept input arguments and return output arguments home > new > function

actual parameter vs formal parameters

actual: values passed to function when invoked, formal: variables defined by the function that receives values when function is called

arithmetic operator?

allows for math calculations

data type?

bool, char, int, float, double, void, wchar_t

list of i/o operations with suitable syntax

cout - standard output cin - standard input clog - standard log cerr - standard error

Write a single line of small snippet code that computes the average of three integer variables - num1 , num2 , and num3 - and stores the result in a variable of type double called result

int main () { double result, int num1 = 2, int num2 = 3, int num3 = 4; (num1 + num2 + num3)/3 = result; cout << result; }

program definition? importance of comp programming language?

program: self-contained set of instructions used to operate a computer to produce a specific result importance: raw data processed into desired output format

Write a function/method called Pair() that takes in three integer parameters and returns true if any two of the input parameters are the same.

public boolean pair (in a, int b, int c) { return (a = = b || a = = c || b = = c) }

Write a function called three value () that takes in thre e integer parameters and returns true if all three of them are the same, false otherwise.

public boolean threevalue (int a, int b, int c) { return ( a = = b || a = = c || b = = c) }

fgets()?

returns next line for file with identifier

Identify the syntax errors in the following snippet of code: Using namspace std; public clas Hello { public: void PrintHlloWorld() { cout << "Hllo Wold"

using namspace std; (spelling > namEspace) public clas Hello { (spelling > clasS) public: void printHlloWorld() (spelling > printHElloWorld) { cout << "Hllo Wold" (spelling > "HEllo World") (need end bracket)

Write a C++ program using vector and perform the following task • Initially Create a vector with 10 elements • Find the size of the vector - how many elements are in the vector • Push_back the element 40 and 50 in the vector - (Extend the vector with 2 elements - Make the vector bigger) • Pop_back the element 50 from the vector: reduce the size of the vector by 1 • Finally, print the number of elements available in the vector

#include <iostream > #include <vector> using namespace std; int main(){ int i; vector<int> vect(10); cout << "Size: " << vect.size() << endl; for (i = 0; i < 10; i++){ //vector declaration vect.at(i) = i + 1; } vect.push_back(40); vect.push_back(50); cout << "Size after push back: " << vect.size() << endl; cout << "Added values are: " << vect.at(10) << " " << vect.at(11) << endl; vect.pop_back(); cout << "Size after pop back: " << vect.size() << endl; cout << "Final vector elements: " << endl; for (i = 0; i < vect.size(); i++){ cout << vect.at(i) << endl; } return 0; }

Write a statement that computes the square root of a variable called discriminant and stores the value in a v ariable called result.

#include <iostream> #include <cmath> int main () { int discrimant = 4, int result; result = sqrt(discriminant) }

Write a program using IOstream and perform the following task • Initially declare four set of arrays: name, course, dept and college as char variables (Eg. char name [100]) • Assign fstream variable and open the file using file.open("xyz.txt", ios::out | ios::in) function. • Get the char variables from the user using cin • Write the char variables in the file "xyz.txt" using (<<) Eg. file << text <<endl; • Finally, read the char variables from the file "xyz.txt" using (>>) [Eg. file >> text >>endl;] and print the char variables in the command prompt • Note: "xyz.txt" is the n ew file you are going to create. (It shouldn't be there before running this program)

#include <iostream> #include <fstream> using namespace std; int main(){ //if you see this you're going to do great on your finals :)char student[100]; cout << "Enter your First name and Last name: "; cin.getline(student, 100);ofstream write("xyz.txt");write<<student;write.close();cout << "File write operation performed successful"<<endl; return 0;}

Write a simple C++ program which contains a header file, main() function, then program code. Explain every line of syntax

#include <iostream> using namespace std: int main () { cout << "Hello World!" << endl; return 0; }

Write a C++ program to print Fibonacci series using Recursion

#include <iostream> using namespace std; int Fibonacci (int x) { if ((x==0)||(x==1)){ return 1; } else { return(Fibonacci(x-1)+Fibonacci(x-2)); } } int main() { int num; cout << "Enter your number: " << endl; cin >> num; cout << "The Fibonacci Series are:" ; for (int y=0; y<num; y++) cout << " " << Fibonacci(y); cout << endl; return 0; }

Write a program that uses a two - dimensional array to store the MidtermI and MidtermII points for five students. The program should display the Midterm points in array format. Your program should do following tasks: • Create 2 dimensional arrays as follows : a) midtermI and midtermII (2 exams), b) students (5 number of students). • The program should read and store the points (2 exam points for 5 students) in the two - dimensional array using cin. • Display the po ints in an array format (8 points)

#include <iostream> using namespace std; int main() { int points[2][5]; cout << "Enter all points for first midterm and second midterm for 5 students \ n"; // Inserting the values into the temperature array for (int i = 0; i < 2; ++i) { for(int j = 0; j < 5; ++j) { cout << "Midterterm " << i + 1 << ", Student" << j + 1 << " : "; cin >> points[i][j]; } } cout <<endl<<"Displaying the points"<<endl; // Accessing the values from the Midterm array for (int i = 0; i < 2; ++i) { for(int j = 0; j < 5; ++j ) { cout << points[i][j]<<" "; } cout<<endl; } return 0;

Write a C++ program to sum (add) two matrices using Multi - dimensional Arrays and print the result • This program should ask user to enter the size of the matrix (rows and columns) • Then, it should ask the user to enter the elements of two matrices and finally it adds two matrix and displays the result.

#include <iostream> using namespace std; int main() { int row, column, i, j; int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10]; cout<<"Enter number of Rows: "; cin>>row; cout<<"Enter number of Columns: "; cin>>column; cout<<"Elements of first matrix : \n"; for (i = 0; i < row; i++) for (j = 0; j < column; j++) cin>>firstMatrix[i][j]; cout<<"Elements of second matrix : \n"; for (i = 0; i < row; i++) for (j = 0; j < column; j++) cin>>secondMatrix[i][j]; cout<<"Sum of entered matrices : \n"; for (i = 0; i < row; i++) { for (j = 0; j < column; j++) { resultMatrix[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; cout<<resultMatrix[i][j]<<"\t"; } cout<<"\n"; } return 0; }}

Write both the function declaration and code for a function called " productmul" . The function should have two integers passed by value as input and return an integer. The function should multiply the two input parameters and return the product of the two parameters.

#include <iostream> using namespace std; int productmult (int x, int y) { cin >> x >> y; return x*y; } int main() { int a, b; cout << productmult(a,b) return 0; }

Write a program that would print the information (name, year of joining, course, college) of three students by creating a class named ' Students'

#include <iostream> using namespace std; public {string name, int name, string course, string college;}; void insert (string n, int y, string c, string t) { name = n; year = y; course = c; college = t; void display () { cout << name << " " << year << " " << course << " " << college << endl;); int main () student1; student2; S1. insert ("Robert", 2018, "csc215", "tcnj") S1.display(): S2. insert ("Aidan", 2018, "csc215", "tcnj") S2.display(): S3. insert ("Eric", 2018, "csc215", "tcnj") S3.display(): } return 0; }

Write a C++ program using user defined functions and perform following task: - The program must be a menu driven, allowing the user to select the operation (+, - , *, or /) and input the numbers. Furthermore, your program must consist of following functions: void showChoices(); float add(float, float); float subtract(float, float);

#include <iostream> using namespace std; void showChoices(); float add(float, float); float subtract(float, float); float multiply(float, float); float divide(float, float); int main() { float x, y; int choice; do { showChoices(); cin >> choice; switch (choice) { case 1: cout << "Enter two numbers: "; cin >> x > > y; cout << "Sum " << add(x,y) <<endl; break; case 2: cout << "Enter two numbers: "; cin >> x >> y; cout << "Difference " << subtract(x,y) <<endl; break; default: cout << "Invalid input" << endl; } }while (choice != 5); return 0; } void showChoices() { cout << "Enter your choice :"; cout << "1: Add " << endl; cout << "2: Subtract" << endl; } float add(float a, float b) { return a + b; } float subtract(float a, float b) { return a - b; }

function overloading?

Function overloading is a feature in C++ that allows you us to have more than one function or variable with the same name but different parameter list

Write an application that prints out the following using a single call to the print method. Hello! How are you?

Hello!\n How \n are you?

Define a "class" city , and the convert below description into C++ syntax with the following specification. Add appropriate data members and member functions.

N/A

What is the output of following code ? Explain your answer int num[5]; int* p; p = num; *p = 10; p++; *p = 20; p = &num[2]; *p = 30; p = num + 3; *p = 40; p = num; *(p + 4) = 50; for (int i = 0; i < 5; i++) cout << num[i] << ", ";

N/A

write a MATLAB code using a colon operator to assigned a 1x11 matrix called time to contain the values from 1 to 6 in increments of 0.5

N/A

What is the value of the variable, a, after the following code is executed? a) int b = 5; int a = 6; b++; a -- ; a = a + b * a; b) int b = 15; int a = 6; a = b / a;

a = 6+6*6 a=72 a=15/16 a=2.5

How many times does each loop execute? a ) for (i = 0; i <= 100; i++) b. for (i = 1; i < 100; i++)

a) 101 b) 99

Evaluate the following logical Boolean expression: a) a=1 0; b=20; X =(a<15) & (b>0) b) a=5; b=6; c=8; Y=((a+b) <= 14) || (z==9)

a) logical b) logical

ANY 5 reserved keywords of c++

bool, class, delete, friend, false

break vs. continue

break terminates smallest enclosing/continue skips rest of loop statement and causes next iteration of the loop to take place

explain: c++ vs MATLAB, c vectors vs m vectors, c array vs m array, matrix vs 2d-array

c++: compile language, index of array can be zero, all variables have to be declared, ; is important matlab: script language, index in matrix can't be negative or zero, data types aren't important, ; isn't important

make comments on c++ and matlab codes

c++: start with // OR start with /* and end with */ matlab: start with %

ANY 5 differences between c & c++

c: only procedural style, doesn't support function overloading, data less secured, can't use functions in structure, operator overloading c++: multi-paradigm, supports function overloading, functions in structure, reference variables, operator overloading is possible

basic input/output stream? explain 3

cin (standard input stream) cout (standard output stream) cerr (standard error stream)

What are the difference between the following two statements: cin >> string_name; getline(cin, st ring _name );

cin >> string_name; ~ constrained to one word getline(cin, string_name); ~ allows for multiple words

primary concepts that support object-oriented programming

classes (blueprints for an object)

explain: clear, clear all, clear a b c, clc, delete x

clear: deletes all matrices from active workspace clear all: deletes variables created in workspace clear a b c: deletes a, b, c from workspace clc: clear command window delete x: deletes x matrix from workspace

diff commands used for colors and style in graphs

colors: 'w'- white, 'k' - black, 'b' - blue, 'r' - red, 'c' - cyan, 'g' - green, 'm' - magenta, 'y'- yellow style: '-' solid line (default), '- -' dashed line, ':' dotted line, '-.' dashed dot

compile-time error vs run-time error

compile-time errors are in the syntax (forgetting a semicolon) & run-time errors happen during execution (ex. 1+1=3)

purposes of 4 main MATLAB windows

current folder: allows access project folders & files command window: main area where commands are entered at command line workspace: shows variables created and/or imported from files command history: shows and return command that are entered at command line

steps to create object from class

define a class, n

steps in software engineering cycle

define, plan, code, test, documenting

what is the use of scope resolution operator?

defines a function outside a class or when a global and local variable have the same name

namespace std

differentiate similar variables with the same name in diff libraries

Write a short program that converts inches to centimeters. It should read the number of inches from the user as a floating - point number and output the number of centimetres at the end of the program. Note that there are 2.54 centimetres in an inch.

double Conversion(int centi) { double inch= .3937*centi; double feet= .0328*centi; cout<< "Inches: " <<inch; cout<< "Feet: " <<feet; return 0;

declare: a) variable for employee's salary 30,036.78 b) constant to hold whole number 7 c) variable for single character y

double salary = 30036.78; const days = 7; char y;

execution stages of c++

edit, preprocess, compiler, linker, loader, execute

What is length ( ) function in MATLAB?

equivalent to size()

What will be the output of the following code? int[] array = new int[25]; array[25] = 2;

error (array caps at 24 and code is calling the 25th value)

Write two different programs to find Fibonacci series using MATLAB scripts and functions

function f = fibonacci(n) f = zeros(n,1); f(1) = 1; f(2) = 2; for k = 3:n f(k) = f(k-1) + f(k-2); end function f = fibonacci(n) if n <= 1 f = 1; else f = fibonacci(n-1) + fibonacci(n-2); end

called function? what's the use?

group of statements that together perform a task. used to give different tasks to different places

advantages of high-level language vs machine code

high-level programming is easily understandable by human, problem-oriented syntax. machine-level programming is only understood by computers, binary

increment vs decrement operator

i++ (increases variable by one) i - - (decreased variable by one)

Consider the following snippet of code. int iResult; float fResult; int rResult; int iNum1 = 25; int iNum2 = 8; iResult = iNum1/iNum2; rResult = iNum2%iNum2; fResult = (float) iNum1/iNum2; What values are stored in iResult, rResult and fResult? Explain your answers.

iResult = = 3 rResult = = 0 fResult = = 3.125

Write a program to generate an output for the below grading system using if - else conditional statement. A college has following rules for grading system: a) Below 64 - F b) 65 to 7 5 - D c) 76 to 85 - C d) 86 to 95 - B e) 96 to 100 - A Ask user to enter points and print the corresponding grade.

if (grade>90) { cout << "Grade: A" <<endl; } else if (grade>80) { cout << "Grade: B" <<endl; } else if (grade>70) { cout << "Grade: C" <<endl; } else if (grade>60) { cout << "Grade: D" <<endl; } else { cout << "Grade: F" <<endl; } return 0; }

What is the need for Static Members?

if you want to change something and only one copy of the data is maintained for all objects

What is wrong with the following snippet of code? Rewrite it so it produces the correct output. if(a < b) if(a == c) cout<<"a < b and a == c"; else cout<<"a is not less than b";

if(a < b) // put into one statement lines 1 and 2 with &&if(a == c) cout<<"a < b and a == c"; elsecout<<"a is not less than b";

Give a recursive definition of the sum of the first n integers

int Sum (int x) { if (x!=0) { return (x+Sum(x-1)); } else return x ; } int main() { int num; cout << "Enter your number: " << endl; cin >> num; cout << "The Sum of the numbers are:" << Sum (num) cout << endl; return 0; }

Rewrite the following for loop as a while loop. for(int i = 0; i < MAX; i++)

int i= 0; while (i< max) { cout << i << endl; i++}

Write a short C++ program that outputs your name , your major , and your birthday on three different lines.

int main () { cout << " Tori" << endl; cout << "Bioengineering" << endl; cout << "February 28" << endl; }

Write the portion of C++ code that will ask the user to enter a number greater than zero. Store the number they enter in a variable. Keep asking them to enter a number if you enter an incorrect number. An incorrect number woul d be one that is less than or equal to zero.

int main () { cout << "enter a number greater than zero." cin >> i; while (i<=0) { cout << "enter a number greater than zero" cin >> i; }

Write a short program that declares a single integer variable called age and assigns it a value equal to your age. Also have it print out your age using the age variable. The output of your program should look similar to the following: I am 17 years old

int main () {int age = 18; cout << "I am " << age << " years old.";

Suppose your numeric grade is calculated using the following formula: Mid 1: 15% Mid 2: 15% Final Exam: 30% Homework: 10% Projects: 30% Determine a variable to represent each of these values. Write a single expression to compute your grade assuming the variables have been declared and each one stor es its value as an integer in the range 0 to 100.

int mid2; int finalExam; int homework; int proj; float grade = mid1 * 0.15 + mid2 * 0.15 + finalExam * 0.30 + homework * 0.10 + proj * 0.30; cout << grade << endl;

Rewrite the following cod e fragment so that it uses a "do...while..." loop to accomplish the same task. int n; cout << "Enter a non - negative integer: "; cin >> n; while (n < 0) { cout << "The integer you entered is negative." << endl; cout << "Enter a non - negative integer: "; cin >> n; }

int n; do { cout << "enter positive number: "; cin >> n; while (n<0) { cout << number is negative." << endl; cout << "enter positive number: "; cin >> n: } }

Write a C++ program using pointers to perform the following task . Create an integer type pointer to hold the address of another int variable. a ) Here, create an integer variable "x" and pointer "p" to holds the address of x b) Assign th e address of variable to pointer c) Print the address of the variable " x "

int x = 0; int *p; p = 7x; cout << "the value of x is: " << x << endl << cout << "the address of x is: " << p << endl << cout << "the address of p is: " << *p << endl;

local vs global variable

local variable is inside the function, global is defined outside main functions

levels of program development

low level language: binary language, non-portable, hard for humans to understand and find error mid level language: assembler + linker = translator , set of symbols and letters high level language: not efficient for computers, easy to find bugs, portable.

ANY 10 features of c++

machine independent, mid-level programming language, simple, rich library, structured programming language, memory management, fast, pointers, object-oriented, compiler-based

anatomy of a class

member functions, member variables, class functions, class variables

what is call by value?

method of passing arguments to function copies the actual value of an argument in formal parameter of the function

What is the output of following code ? Explain your answer #include <iostream> using namespace std; int main () { int arr[] = { 4, 5, 6, 7 }; int* p = (arr + 1); cout << *arr + 10; return 0; }

output = 14

explain: plot, bar, xlabel, xlim, title, linspace, LineWidth, MarkerEdgeColor, FaceColor, axis, grid on, legend()

plot: generates line graph bar: generates bar graph xlabel: generates labels along x - axis xlim: limits x-axis title: allows a title on the graph linspace: generates linearly spaced vectors linewidth: specifies width (in points of the line) MarkerEdgeColor: specifies edge color for filled markers FaceColor: specifies color of face for filled markers axis: sets axis scales grid on: allows you to put grid lines on the graph legend(): associates strings with the objects in the axes in the same order they're listed

references vs pointers

pointer holds memory address of another variable, reference variable is alias

access specifiers in c++

private: accessible to class members. (most secure) protected: accessible to class members and derived class. public: accessible everywhere. (least secure, everyone can access)

procedure-oriented programming vs object-oriented programming language

procedure-oriented programming focuses on procedural abstractions vs object-oriented programming focuses on data rather than algorithm

recursion

process when a function calls itself directly or indirectly

explain: pwd, what, diary, who, whos, help, zeros, rand, exist, type, date, :, :

pwd: displays current working directory what: list matlab files in current directory diary: saves files in private space who: only provides names of active variables whos: gives all information on active variables help: will describe matlab command or function zeros: fills matrix with zeros rand: fills matrix with random numbers exist: returns status of variable/file type: returns contents of specified file in command window date: returns current date as character vector : generates regularly spaced elements and represents an entire row or column ; separates columns and suppresses display

Rewrite the following C++ code to make it more efficient and remove any unnecessary code. if (x < y && y >= x) { cout << " Positive number . \ n"; } cout << " Wrong number \ n";

remove: && y>=x (because not needed)

scripts vs functions

scripts: can only operate on variables that are hard-coded into their m-file functions: have more input and output parameters

assembly language? steps?

set of symbols and letters programmer>linker>processor

escape sequence?

special characters used in control string to modify the format of an output

array? How to initialize and declare?

special variables which hold more than one value under the same variable name. initialize during declaration (int mark[5] = {19, 10, 5, 18, 26}

conditional statement? explain diff types

specifies whether another statement or block of statements should be executed or not if - specify a block of code to be executed, if specified condition is true else - specify a block of code to be executed, if same condition is false else if - specify a new condition to test, if first condition is flase

ANY 3 types of errors in matlab

syntax errors: calling incorrect syntax algorithm errors: when program executes perfectly but output is incorrect function calling errors: calling a function that doesn't exist in the code

#include <iostream>

tells compiler to include declarations of all standard input-output library functions

define pointers. explain & and *

variable that holds memory address, usually the location of another variable. & : address operator, determines address of variable * : indirection operator, access the value of address

variable declaration vs definition?

variables can have characters, digits, and underscores definition is setting a variable equal to something

The following code compiled, but while running it the program appears to hang (e.g. nothing happens). This is a clear sign of an infinite loop. What part of this code fragment caused the infinite loop? while(i < 50); { cout<<"i"; i+=2; }

while(i < 50); // the semicolon after the while statement makes it an infinite loop. { cout<<"i";i+=2; }

Write the MATLAB code that will assign the following two - dimensional matrix to the variable called x.

x=[7 9 7 5; 8 5 3 0;7 5 2 4]

Write the MATLAB code that will take a 3x4 matrix called data and extract rows 1 and 3 into a matrix called sampleData . Your sampleData matrix will be a 2x4 matrix.

x=[7 9 7 5; 8 5 3 0;7 5 2 4] .... not finished


Kaugnay na mga set ng pag-aaral

Money, Credit, and FI Ch. 2 HW Review

View Set

EAQ-Content Area-MedSur-Respiratory

View Set

Test Out Linux Pro 4.2.9 Bootloaders (Practice Questions)

View Set