I can't figure out how this works, the code is really complicated because it is for a programming class I'm in. I can't seem to get the program's output when I work it through manually, it is the practice test for our final next week, I wouldn't cheat on a test, the professor gave us the program and the output, I just don't understand why that is the output..:
class FinalExam
{
private:
int This;
int That;
public:
FinalExam(int, int);
void One(int);
int Two(int);
};
FinalExam :: FinalExam(int A = 3, int B = 5)
{
This = A;
That = B;
}
void FinalExam :: One(int A)
{
This --;
That = A;
}
int FinalExam :: Two(int A) // Two gets the int 8
{
int Scrap;
Scrap = This + That - A; // 5 + 2 - 8 = -1????
return Scrap;
}
main()
{
FinalExam Block;
FinalExam Chunk(6, 7);
Block.One(2);
cout << Block.Two(3)
<< '\n'
<< Chunk.Two(8); //I get lost on this 8, It should go to "Two"
}
And the output is:
1
5
I have looked at this for about an hour and I don't understand.
FinalExam Block; // Not passing any arguments to the constructor. In that case,
// default argument values are taken. So, This = 3, That = 5
Block.One (2); // This = 2; That = 2
// Because This is decremented and That is assigned the value
// passed to the method which is 2.
cout << Block.Two (3) ; // 2 + 2 - 3 = 1 which is returned and is printed.
Similarly try the second one.
Explanation of what's happening in the comments between the lines.
int main(int, char**) {
FinalExam Block;
// At this point ..
// Block.This = 3;
// Block.That = 5
FinalExam Chunk(6, 7);
// Chunk.This = 6
// Chunk.That = 7
Block.One(2);
// Block.One decrement's This and assigns 2 to That so ..
// Block.This = 2
// Block.That = 2
std::cout << Block.Two(3)
// Block.Two(3) returns the result of this calculation
// This + That - 3
// This and That are both 2 at this point so..
// 2 + 2 - 3 == 1
// It returns 1 and prints out '1'
<< std::endl
<< Chunk.Two(8);
// Chunk's This and That are 6 and 7 respectively so ..
// cout << 6 + 7 - 8 == 5
}
Here's a line-by-line breakdown:
1 FinalExam Block;
Uses the constructor with default values, so Block.This = 3, and Block.That = 5.
2 FinalExam Chunk(6, 7);
Uses the constructor, specifying values, so Chunk.This = 6 and Chunk.That = 7.
3 Block.One(2);
Decrements Block.This (3 ==> 2), and assigns Block.That = 2 (was previously 5).
4 Block.Two(3)
returns Block.This + Block.That-3 ==> 2+2-3 ==> 1, which is output.
5 Chunk.Two(8)
returns Chunk.This + Chunk.That - 8 ==> 6+7-8 ==> 5, which is output.
Q.E.D. the output is "1 \n 5"
Firstly, you'll notice that we're creating two objects of type FinalExam called Block and Chunk.
Block:
since block wasn't passed any values via the parameter, it will take on the default values which come from this code block:
FinalExam :: FinalExam(int A = 3, int B = 5)
{
This = A;
That = B;
}
so This = 3 and That = 5
The next line that effects Block is:
Block.One(2);
which refers to this code block:
void FinalExam :: One(int A)
{
This --;
That = A;
}
so This = 2 (This = This - 1 or This = 3 - 1)
and That = 2 (That = A = 2(passed by value in parameters)
The last line effecting Block is:
cout << Block.Two(3)
which refers to this code block:
int FinalExam :: Two(int A) // Two gets the int 8
{
int Scrap;
Scrap = This + That - A; // 5 + 2 - 8 = -1????
return Scrap;
}
so we create a new integer called Scrap = 1 (This + That - A or 2 + 2 - 3(passed by value))
Chunk:
the first line that refers to Chunk is:
FinalExam Chunk(6, 7);
this set A = 6 and B = 7
and because of this code block:
FinalExam :: FinalExam(int A = 3, int B = 5)
{
This = A;
That = B;
}
This = 6 and That = 7 (This = A = 6 and That = B = 7)
and finally, we have this line:
Chunk.Two(8);
which refers to this code block:
int FinalExam :: Two(int A) // Two gets the int 8
{
int Scrap;
Scrap = This + That - A; // 5 + 2 - 8 = -1????
return Scrap;
}
A is set to 8 since we passed it by value through parameters
and Scrap = 5 (b + 7 - 8 or This + That - A)
Output:
We output Scrap from Block which is 1
and create a new line
and output Scrap from Chunk which is 5
Hope this helps, leave a comment if you have any additional questions
Related
I am trying to solve ax + by = n.
When I put n = 7, it solves the equation correctly as X = 2 and Y = 1.
But when I put n = 1, it does not solve the equation. Even though, this equation has valid integer solution, X = 17, Y = -11. here is my full program.
#include <iostream>
using namespace std;
void PrintXY(int a, int b, int n)
{
for (int i = 0; i * a <= n; i++) {
if ((n - (i * a)) % b == 0) {
cout << "x = " << i << ", y = "
<< (n - (i * a)) / b;
return;
}
}
cout << "No solution";
}
int main()
{
int a = 2, b = 3, n = 1;
PrintXY(a, b, n);
return 0;
}
Output when n = 7:
x = 2, y = 1
Output when n = 1:
No solution
Reasoning.
2*(2) + 3*(1) - 7 = 4 + 3 - 7 = 0
2*(17) + 3*(-11) - 1 = 34 - 33 - 1 = 0
Both equations solve to give 0. But what is wrong in my program that is causing it to give "No Solution".
The problem is with the termination condition:
i*a<=n
This(n>=a*i) need not be true, and is especially not true in case of the solution (ie X=17, Y=-11). Which seems reasonable - Without any bounds(limits) on the answer(either X or Y) , how would you find the solution to a linear equation(with an infinite possible range) in a closed for loop ?
I don't get this recursion exercise in C++. Here it is:
int fatt(int x){
int s=1; // here. since 's' will always be 1 shouldn't i get 1 as an output???
if(x>1) { s = x*fatt(x-1); }
return s;
}
int main()
{
int n;
cout << "Type a number: ";
cin >> n;
if (n < 0) { cout << "Error" << endl; }
if (n <=1) { cout << "Factorial: 1" << endl; }
else { cout << "Factorial: " << fatt(n) << endl; }
}
If I put s=0 it returns me as an output always 0, if I put 2 it doubles the result O.o I don't get how it works. I understand that x is always getting diminished until reaches 2 and the returns the result but everytime the function is called shouldn't 's' be given the value of 1???
Say you call the function with the parameter value 3: It would look like this:
int fatt(3) {
int s = 1;
if (3 > 1) s = 3 * fatt(3 - 1);
return s;
}
So s is the result of the calulation 3 * fatt(2) and the result of fatt(2) is:
int fatt(2) {
int s = 1;
if (2 > 1) s = 2 * fatt(2 - 1);
return s;
}
So s is the result of the calculations 2 * fatt(1) and the result of fatt(1) is:
int fatt(1) {
int s = 1;
if (1 > 1) s = 1 * fatt(1 - 1); // False so this is never executed.
return s;
}
The result of fatt(1) is 1. So that is what we return to the call of fatt(2) which then translates to:
s = 2 * 1;
Which gives the result 2 which is then returned to the call of fatt(3) which then gives:
s = 3 * 2;
Which gives the result 6.
Remember that the local variable s is pushed on the stack each time the function is executed. So it is not the same variable.
If you initiated s to 2, then the first line would read: s = 2 * 2; and the rest of the function would give double the value in result. Since s is really a factor that you end up multiplying with, in your factorial:
So the sequence: 3 * 2 * 1 becomes 3 * 2 * 2.
The variable s is local to the given instantiation of the function fatt. As the function recursively calls itself, every invocation gets its own new copy of s. This is initialised to 1, but doesn't affect all the previous s instances lower down in the stack. Each one of those is then assigned to the result of the fatt invocation mediately after it multiplied by its local copy of x.
's' should be 1 but it gets assigned and then changes the value it holds upon the completion of a function.
Recursions can be a bit hard to understand at first but once you do, it's beautiful.
I suggest you use a pen and paper.
1) Let x = 3;
int fatt(3) {
int s = 1;
if (3 > 1) s = 3 * fatt(3 - 1);
return s;}
2) In the function 3>1 = true so it gets passed on again but this time as (3-1) i.e 2
Note: function isn't done executing
3) Now x = 2
int fatt(2) {
int s = 1;
if (2 > 1) s = 2 * fatt(2 - 1);
return s;}
4) Repeat step 2) (2-1) i.e 1
5) Since x IS NOT > 1 in the 3rd function call this results in the returning of s
s = 1;
return s;
So...
Starting at the 2rd function call:
s = x * fatt(x-1);
s = 2 * 1;
return s;
Repeat this again for the first call)
s = x * fatt(x-1);
s = 3 * 2;
return s;
Think of it like a stack of functions
1st stack ------- calls stack 2 and waits
2nd stack ---------- calls stack 3 and waits
1st stack ---------- waiting
Finally...
3rd stack ---------- condition not met return
2nd stack ---------- condition done return
1st stack --------- condition done return
Hope that helps
"Number pong" is what I am trying to do. Ex:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 etc
I have tried several different things, incrementing one number, modal operators. I could not figure this out, and I could not figure out correct search words.
So:
int offset = 0;
int number = 0;
while(true) {
offset++;
number = offset%5; // idea 1
number = (offset%5)-5 // idea 2
number = (offset/5)%5 // idea 3
number = 5 - (offset%5) // idea 4
}
None of those work, obviously. I get patterns like 0 1 2 3 4 5 0 1 2 3 4 5 or just continuous numbers.
I would wrap this in an if(offset % 10 <= 5) { ... } else { ... } and use your existing ideas.
Regardless you're going to want to work % 10 since that's how long your cycle is.
Hint These sequences are very closely related:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 ...
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ...
#include <iostream>
int main()
{
int i = 0;
bool plus = true;
while(true) {
std::cout << i << std::endl;
if (plus) i++; else i--;
if (i == 5 || i == 0) plus = !plus;
}
}
Is there a requirement to generate the numbers in a single statement with variables and operators?
If not, then use an bool variable which switches its value (true means increasing, false means decreasing) from true to false and vice versa.
i.e.
int start = 0 ;
bool which_way = true ;
int loop_times = 100 ;
while(--loop_times) {
std::cout << start ;
start += which_way ? 1 : -1 ;
if(start % 5 == 0)
which_way = !which_way ;
}
Here is a crazy way of outputting the number pong (with set limit)
#include <stdio.h>
int main()
{
bool bFlip = false; //Decides if number will increase or decrease
int nLimit = 5; //How far up the number will count.
//Start at 0, keep going as long as number never reaches past the limit
//And increase/decrease depending on bFlip
for(int nNum = 0; nNum <= nLimit; (bFlip ? nNum++ : nNum--))
{
printf("%d ", nNum);
//When number reaches either end, do a barrel roll!
if (nNum % nLimit == 0)
{
bFlip = !bFlip;
}
}
return 0;
}
Be warned that this loop will go on forever so if you are going to go with this approach then you will need to set a limit on how many numbers you want to display.
Yet another crack at generating the sequence you're after:
#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> nums = {{0, 1, 2, 3, 4, 5}};
auto begin = nums.begin();
auto iterator = nums.begin();
auto end = nums.end();
auto loop_times = 100;
while (--loop_times) {
while (iterator != end) {
std::cout << *iterator++;
}
iterator--;
while (iterator != begin) {
std::cout<< *--iterator;
}
iterator++;
}
}
Thanks for the tips. I got it working with a single statement.
int count = 0;
int num = 0;
int out = 0;
while (count++ < 100) {
cout << abs( (num%10) - 5 ) << endl;
num++;
}
// Output: 5 4 3 2 1 0 1 2 3 4 5 4 etc
I'd probably do something like this:
// If you want in the range -val to val
//#define PONG(val, i) (abs(val%(i*4)-i*2) - i)
// If you want the range 0 to val
#define PONG(val, i) (abs(val%(i*2)-i))
int main() {
for(int i = 0; i < 100; i++) {
cout << PONG(i, 5) << endl;
}
}
Prints:
5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 ...
So I'm reading C++ Primer (5th edition) and this is the example code they give to explain the while statement:
#include <iostream>
int main()
{
int sum = 0, val = 1;
// keep executing the while as long as val is less than or equal to 10
while (val <=10) {
sum += val; // assigns sum + val to sum
++val; // add 1 to val
}
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
return 0;
}
And this is the program in the Command Line prompt:
I just can't understand where the 55 came from..
Isn't it supposed to be:
sum = 0
var = 1
sum = 0 + 1
var = 1 + 1
-snip-
sum = 6
var = 4
So shouldn't it print 6?
I'm really confused.
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
What it does is:
initializes val to 1
increments val till it reaches 10 in each iteration
this val is added to sum in each iteration
after 10 iterations, this sums up to 55.
Still not clear, use a debugger and check each step.
#include <iostream>
#include <vector>
using namespace std;
int main(void)
{
int i, s, g;
vector<int> a;
cin >> s;
for(i=1;i<=s;i++)
{
g = s;
if(g<10) a.push_back(g);
else {
vector<int> temp;
while(g > 0)
{
int k = g % 10;
g = g / 10;
temp.push_back(g);
}
for(int j=temp.size();j>0;j--)
{
a.push_back(temp[j]);
}
}
}
cout << a[s-1] << endl;
return 0;
}
What is wrong with the code above ? It doesn't give me the appropriate results.
The vector a is supposed to hold the values from 1, 2, 3...up to s such that a = 12345..910111213... and print to output a[s]. Ex if s=15 a=123456789101112131415 and a[15] = 2 .
If someone could tell me what's the problem
for(int j=temp.size();j>0;j--)
{
a.push_back(temp[j]);
}
Here the values of j include temp.size and exclude 0. Since vectors (like basically everything else with integer indices) are 0-indexed, this will access a out of bounds on the first iteration (i.e. when you access temp[temp.size()]).
You have the line g = s; when I think you want g = i;. As written, for s = 5, this will be your vector a: 5 5 5 5 5 Which is not at all what you want.
[Edit] Your handling of numbers > 10 is also off. For example, what happens in your code currently for the number 12? Well, temp will be 1 0 instead of 1 2, and then this will be pushed into a as 0 1, which is again not what you want.
To fix this, think about what k is supposed to do.
Corrected code:
int i, s, g;
vector<int> a;
cin >> s;
for(i=1;i<=s;i++)
{
g = i; //Why was it s?
if(g<10) a.push_back(g);
else {
vector<int> temp;
while(g > 0)
{
int k = g % 10;
g = g / 10;
temp.push_back(k); //You need to push the remainder
}
for(int j=temp.size()-1;j>=0;j--) //Out of bounds error
{
a.push_back(temp[j]);
}
}
}
cout << a[s-1] << endl;
return 0;
And a looks like this when s = 15 - is this what you were looking for?
a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4
a[4] = 5
a[5] = 6
a[6] = 7
a[7] = 8
a[8] = 9
a[9] = 1
a[10] = 0
a[11] = 1
a[12] = 1
a[13] = 1
a[14] = 2
a[15] = 1
a[16] = 3
a[17] = 1
a[18] = 4
a[19] = 1
a[20] = 5
I think there's a few problems here.
First, as MBennett said above, you should have done g = i; not g = s; to begin with.
Second, I think your inner loop also has an error, where you should be pushing back k not g as you are now.
Third, you should be doing push_front() not push_back() as you are now. Think of it this way, if you only had that loop, and had the number 162, if you push BACK (not front) every time, then it pushes 2, 6, 1, and so the sequence will have that, and not 1, 6, 2, in the order you want. Your copy after that seems OK, though there's more efficient ways of doing it.
I think that's it. Make those changes and it should function, though I haven't compiled it myself, I'm just solving in my head.