MTH4300 Home

# MTH 4300: Midterm 2 Practice 3

Problem 1.

The user provides integers through the standard input. The first of them is the number bound, and is assumed to be positive. After this number, the user provides a sequence of non-negative integers, followed by a single negative integer which indicates that the user will not provide any more numbers. Create a program that properly reads the numbers provided by the user, ignores all the numbers bigger than or equal to bound, and calculates the sum of those numbers smaller than bound.

Print the obtained sum to the standard output. If there are no numbers to be summed, then the program should print 0.

Problem 2.

Use recursion to create a program that calculates $$x[n]$$ if $$x$$ is the sequence defined as $x=a, \quad\quad x[n+1]=\Big(x[n]\cdot(x[n]+1)+8\Big)\%p,\mbox{for }n\geq 0.$ The user input includes the numbers $$n$$, $$p$$, and $$a$$. The output should be $$x[n]$$.

Problem 3.

What happens when the following code is executed? Provide a rigorous justification for your answer.

// pointer_arithmetic.cpp
// compile with
// c++ -o p_a pointer_arithmetic.cpp -std=c++11
// execute with
// ./p_a
#include<iostream>
int main(){
int *x;
int *y;
x= new int;
x=3;x=5;x=6;
y=x;
y=7;y=8;y=9;
std::cout<<x+y+x+y+x+y<<std::endl;
delete[] x;
return 0;
}


Problem 4.

What happens when the following code is executed? Provide a rigorous justification for your answer.

 #include<iostream>
int mystery(int *x, int n){
int result=0;
if(n>0){
result=x+mystery(x+1,n-1);
}
return result;
}
int main(){
int* seq;
seq=new int;
seq=5;seq=9;seq=15;seq=12;seq=8;
std::cout<<mystery(seq,3)<<std::endl;
delete[] seq;
return 0;
}


Problem 5.

What happens when the following code is executed? Provide a rigorous justification for your answer.

#include<iostream>
public:
};
return helper;
}
void printResults(){
std::cout<<"7";
}
int main(){
printResults();
std::cout<<std::endl;
return 0;
}


Problem 6.

Find the sum of all elements of a given list.

Your code should replace // ??? in the text below in such a way that the obtained c++ source file accomplishes the described task.

#include<iostream>
#include"mth4300_list_basics.cpp"
// ???
}
int main(){

A sequence whose terms are from $$\{1,2,\dots, k\}$$ is called a no-repetition sequence if no two consecutive terms are the same. For example, for $$k=3$$ the sequences $$(1, 2, 1, 2, 3, 1)$$, $$(1, 2, 1, 2, 1)$$, and $$(2, 3, 2, 1, 3)$$ are no-repetition sequences, while $$(1, 2, 2, 1, 3)$$ and $$(3, 1, 2, 1, 1)$$ are not. Create a program that reads $$n$$ and $$k$$ from the standard input, and prints all no-repetition sequences of length $$n$$ whose components are from $$\{1, 2, \dots, k\}$$.