Please explain the execution of the program such that why it will generate such specific outputs.
The output is
6 10 20
6 10 8
2 2 14
My guess would have to be that it is due to the IN, OUT, INOUT parameters but I am not really understanding it
#include <iostream>
using namespace std;
void sunny(int&, int);
void cloudy(int, int&);
int temp;
int main()
{
int num1 = 6;
int num2 = 10;
temp = 20;
cout << num1 << " " << num2 << " " << temp << endl;
sunny(num1, num2);
cout << num1 << " " << num2 << " " << temp << endl;
cloudy(num1, num2);
cout << num1 << " " << num2 << " " << temp << endl;
}
void sunny(int& a, int b)
{
int w;
temp = (a + b) / 2;
w = a / temp;
b = a + w;
a = temp - b;
}
void cloudy(int u, int& v)
{
temp = 2 * u + v;
v = u;
u = v - temp;
}
Actually the output is:
6 10 20
2 10 8
2 2 14
We can see the steps like this:
Sunny call:
temp = (6 + 10)/2 = 8
w = 6/8 = 0 //This is because w is declared int, and int(6/8) = 0
b = 6 + 0 = 10
a = 8 - 6 = 2
Therefore num1 is now 2, because of the reference argument, and temp is changed to 8 because its global
Cloudy call:
temp = 2 * 2 + 10 = 14
v = 2
u = 2 - 14 = -12 //This variable is doing nothing
Therefore num2 is now 2 for same reason as before and temp is 14
Related
I used a for loop to generate a list of strings, and I've been trying to make them print horizontally instead of vertically.
Currently:
the list is printed vertically, up to 10.
Goal: To have the list printed horizontally.
Code for reference:
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y, z = 0;
int result;
for (z = 1; z <= x; z++)
{
cout << '\n';
for (y = 1; y <= z; y++)
{
result = z * y;
cout << z << " * " << y << " = " << result << '\n';
}
cout << '\n';
}
}
For the first block of number (1x1 .. 5x5), here's something similar to your expected output.
for (int x = 1; x <=5 ; x++) {
for (int y = 1; y <= 5; y++) {
if (y < x) {
cout << " ";
}
else {
cout << setw(3) << y << " x " << setw(4) << x << " = " << setw(4) << x * y << " ";
}
}
cout << endl;
}
Prints out this:
1 x 1 = 1 2 x 1 = 2 3 x 1 = 3 4 x 1 = 4 5 x 1 = 5
2 x 2 = 4 3 x 2 = 6 4 x 2 = 8 5 x 2 = 10
3 x 3 = 9 4 x 3 = 12 5 x 3 = 15
4 x 4 = 16 5 x 4 = 20
5 x 5 = 25
I'll leave it as an exercise for extending this to another set of rows for the 6 through 10 times tables.
I would like to store the smallest value of compute_evaluation_function in current_best_eval, and the corresponding vector that gives that smallest value in ILS_best_p, I've succeeded with the current_best_eval, but can't seem to get it for the ILS_best_p even though they're under the same if statement.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cmath>
using namespace std;
long int **read_matrix(ifstream &input, long int n);
double ran01(long int *idum);
long int *generate_random_vector(long int n);
unsigned long int compute_evaluation_function(long int n);
void first_2_opt_symmetric (long int n);
void swap(long int pos_1, long int pos_2, long int *);
void perturbation(long int pert_size);
long int *p;//the vector generated from generate_random_vector()
long int **d;//one of the matrices read from file
long int **f;//one of the matrices read from file
long int n;
long int actual_solution_value;
long int new_eval;
long int current_eval;
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
int main()
{
string name;
long int optimum;
ifstream infile;
long int initial_eval;
long int *ILS_best_p;
long int new_vs_current;
new_vs_current = INT_MAX;
long int current_best_eval;
current_best_eval = INT_MAX;
long int new_current_eval;
long int best_eval;
long int improvement;
long int i;
long int j;
infile.open("nug12.dat");
infile >> name;
cout << "Name: " << name << "\n";
infile >> n;
cout << "Rows and Columns: " << n << "\n";
infile >> optimum;
cout << "Optimum solution: " << optimum << "\n";
d=read_matrix(infile, n);
f=read_matrix(infile, n);
cout << endl;
p=generate_random_vector(n);
compute_evaluation_function(n);
cout << endl;
first_2_opt_symmetric (n);
cout << endl;
initial_eval = compute_evaluation_function(n);
cout << endl << endl;
for (i = 0; i < 500; i++) //ILS loop
{
if (new_eval < current_eval)
{
new_vs_current = new_eval;
cout << "iteration 1st = " << i+1 << " " << endl;
}
else if (current_eval < new_eval)
{
new_vs_current = current_eval;
cout << "iteration 2nd = " << i+1 << " " << endl;
}
cout << "iteration = " << i+1 << " " << endl;
cout << " Vector before perturbation = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
perturbation(3);
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
cout << " Vector after perturbation = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
first_2_opt_symmetric (n);
new_current_eval = compute_evaluation_function(n);
cout << endl << "current best eval = " << current_best_eval << endl;
cout << endl;
cout << " Vector after local search = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
cout << endl << "current best eval = " << current_best_eval << endl;
cout << " Vector p = ";
for (j = 0; j < n; j++)
{
cout << p[j] << " ";
}
cout << endl << endl;
if (new_current_eval < current_best_eval)
{
new_eval = new_current_eval;
cout << "iteration 3rd = " << i+1 << " " << endl;
}
else if (current_best_eval <= new_current_eval)
{
new_eval = current_best_eval;
cout << "iteration 4th = " << i+1 << " " << endl;
}
if (new_eval < new_vs_current)
{
current_best_eval = new_eval;
cout << "iteration 5th = " << i+1 << " " << endl;
ILS_best_p = p;
}
else if (new_vs_current < new_eval)
{
current_best_eval = new_vs_current;
cout << "iteration 6th = " << i+1 << " " << endl;
ILS_best_p = p;
}
cout << endl << "current best eval = " << current_best_eval << endl;
}
cout << endl << "current best eval = " << current_best_eval << endl;
cout << "ILS best vector = ";
for (i = 0; i < n; i++)
{
cout << ILS_best_p[i] << " ";
}
return 0;
}
long int **read_matrix(ifstream &input, long int n)
{
/*
FUNCTION: read instance matrices
INPUT: instance file name, instance size
OUTPUT: d-matrix and f-matrix
(SIDE)EFFECTS: none
COMMENTS: read the distance matrix and flow matrix
*/
long int i, j;
long int **matrix = new long int *[n];
for (i = 0; i < n; i++)
{
matrix[i] = new long int[n];
for (j = 0; j < n; j++)
{
if( !(input >> matrix[i][j]) )
{
cerr << "Error reading at " << i << j << endl;
exit(1);
}
}
}
return matrix;
}
double ran01(long int *idum)
{
/*
FUNCTION: returns a pseudo-random number
INPUT: a pointer to the seed variable
OUTPUT: a pseudo-random number uniformly distributed in [0,1]
(SIDE)EFFECTS: changes the value of seed
*/
long k;
double ans;
k =(*idum)/IQ;
*idum = IA * (*idum - k * IQ) - IR * k;
if (*idum < 0 )
{
*idum += IM;
}
ans = AM * (*idum);
return ans;
}
long int *generate_random_vector(long int n)
{
/*
FUNCTION: generates a random vector
INPUT: vector dimension
OUTPUT: returns pointer to vector, free memory when vector is not needed anymore
(SIDE)EFFECTS: none
*/
long int i, j, help;
long int *v;
srand(time(0));
long int seed=rand();
v = new long int[ n ];
for ( i = 0 ; i < n; i++ )
{
v[i] = i;
}
for ( i = 0 ; i < n-1 ; i++)
{
j = (long int) ( ran01( &seed ) * (n - i));
assert( i + j < n );
help = v[i];
v[i] = v[i+j];
v[i+j] = help;
}
return v;
}
unsigned long int compute_evaluation_function(long int n)
{
/*
FUNCTION: compute evaluation function
INPUT: pointer to solution
OUTPUT: evaluation function
(SIDE)EFFECTS: none
COMMENTS: none
*/
long int i, j;
unsigned long obj_f_value;
obj_f_value = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
obj_f_value += d[i][j] * f[p[i]][p[j]];
}
}
cout << obj_f_value;
return obj_f_value;
}
void first_2_opt_symmetric (long int n)
{
/*
FUNCTION: first improvement 2-opt local search for symmetric instances
INPUT: pointer to some initial assignment
OUTPUT: none
(SIDE)EFFECTS: initial assignment is locally optimized, dlb is used to increase the search speed, the dlb value is changed to false if item change it's location during perturbation
COMMENT: neighborhood is scanned in random order, use of register for faster computation
*/
long int improvement = 1;
long int improve_item = 0;
long int u, v, i, j, k;
long int tmp;
long int *x;
improvement = 1;
x = generate_random_vector(n);
while (improvement)
{
improvement = 0;
for ( i = 0 ; i < n ; i++ )
{
u = x[i];
improve_item = 0;
for ( j = 0 ; j < n ; j++ )
{
v = x[j];
if (u == v)
continue;
tmp = 0;
for ( k = 0 ; k < n ; k++ )
{
if ( (k != u) && (k != v) )
{
tmp += (d[u][k] - d[v][k]) * (f[p[v]][p[k]] - f[p[u]][p[k]]);
}
}
if (tmp < 0)
{
improvement = 1;
improve_item = 1;
swap (u, v, p);
}
}
}
}
delete []x;
}
void swap(long int pos_1, long int pos_2, long int *p)
{
/*
FUNCTION: swap position of two items in a vector
INPUT: position 1, position 2, pointer to vector
OUTPUT: none
(SIDE)EFFECTS: none
COMMENTS: none
*/
long int tmp;
tmp = p[pos_1];
p[pos_1] = p[pos_2];
p[pos_2] = tmp;
}
void perturbation(long int pert_size)
{
/*
FUNCTION: apply random perturbation
INPUT: pointer to solution, perturbation scheme, perturbation strength, change in perturbation, end perturbation size
OUTPUT: none
(SIDE)EFFECTS: new solution formed from old solution
COMMENTS: none
*/
long int hold_value[n]; //allocate memory for items to be chosen in move/*
int chosen[pert_size]; //*allocate temporary memory to determine items to be moved */*
long int i;
for(i = 0; i < n; i++)
{
hold_value[i] = p[i]; //initialize hold_value with the same value from local search/*
}
int j = n - 1;
int rand_number;
int rand_no;
for(i = 1; i <= pert_size; i++)
{
rand_number = rand();
rand_no = rand_number % j; //choose random number from 1 to size - 1/
chosen[i - 1] = rand_no + i; //copy the value to chosen[i]
j--;
}
long int temp;
for(i = 0; i < pert_size; i++)
{
temp = chosen[i];
swap(i, temp, hold_value); //swap chosen[i] and hold_value[i]; n first item in hold_value[i] is the index array that will be included in perturbation/
}
long int temp1;
long int temp2;
temp1 = p[hold_value[1]];//
temp2 = p[hold_value[0]];
for(i = 0; i < pert_size - 1; i++)
{
p[hold_value[i + 1]] = temp2;
temp2 = temp1;
temp1 = p[hold_value[i + 2]];
}
p[hold_value[0]] = temp2;
actual_solution_value = compute_evaluation_function(n);
new_eval = actual_solution_value;
current_eval = new_eval;
}
This is the file I read from:
Nug12
12
578
0 1 2 3 1 2 3 4 2 3 4 5
1 0 1 2 2 1 2 3 3 2 3 4
2 1 0 1 3 2 1 2 4 3 2 3
3 2 1 0 4 3 2 1 5 4 3 2
1 2 3 4 0 1 2 3 1 2 3 4
2 1 2 3 1 0 1 2 2 1 2 3
3 2 1 2 2 1 0 1 3 2 1 2
4 3 2 1 3 2 1 0 4 3 2 1
2 3 4 5 1 2 3 4 0 1 2 3
3 2 3 4 2 1 2 3 1 0 1 2
4 3 2 3 3 2 1 2 2 1 0 1
5 4 3 2 4 3 2 1 3 2 1 0
0 5 2 4 1 0 0 6 2 1 1 1
5 0 3 0 2 2 2 0 4 5 0 0
2 3 0 0 0 0 0 5 5 2 2 2
4 0 0 0 5 2 2 10 0 0 5 5
1 2 0 5 0 10 0 0 0 5 1 1
0 2 0 2 10 0 5 1 1 5 4 0
0 2 0 2 0 5 0 10 5 2 3 3
6 0 5 10 0 1 10 0 0 0 5 0
2 4 5 0 0 1 5 0 0 0 10 10
1 5 2 0 5 5 2 0 0 0 5 0
1 0 2 5 1 4 3 5 10 5 0 2
1 0 2 5 1 0 3 0 10 0 2 0
I have a basic program down that sums 1 to N.
However, I need to print every line of sums leading up to 'N'.
ex: input -> 3
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
I need to do this through recursion without using any loops in the code.
Any help appreciated. I can't seem to wrap my head around how to do this.
#include <iostream>
using namespace std;
int sumToN(int n, int row);
int input;
int main()
{
cout << "Sum to: ";
cin >> input;
cout << sumToN(input, 1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
See this :
int sumToN(int n, int row);
void out(int n);
int input;
int main()
{
cout << "Sum to: \n";
cin >> input;
out(1);
}
void out(int n)
{
if( n > input) return;
cout << sumToN(n, 1)<<"\n";
out(n+1);
}
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
Output:
You can try something like storing the sum like 1+2.. In a string and keep appending the new number on each call and also output the new sum in each call after the string
Use a internal value prefix_val and prefix_str to store the prefix recursive result. Then we can output the whole recursive workflow.
int sumToN(int n, int row, int prefix_val, const std::string& prefix_str);
int main()
{
// Meanwhile you should void using global variables.
int input;
cout << "Sum to: ";
cin >> input;
sumToN(input, 1, 0, "");
}
int sumToN(int n, int row, int prefix_val, const std::string& prefix_str)
{
string gap;
if (prefix_val == 0) {
gap = "";
} else {
gap = " + ";
}
cout << prefix_str << gap << row << " = " << prefix_val + row << std::endl;
if (row == n) // recursive end
{
return 0;
}
return sumToN(n, row + 1, row + prefix_val, prefix_str + gap + std::to_string(row));
}
DEMO OUTPUT
Sum to: 10
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
With loops you can do something like that:
#include <iostream>
using namespace std;
void displayToN(const int last) {
int sum = 0;
for (int i=1; i<last; sum += i, i++)
cout << i << " + ";
cout << last << " = " << (sum + last) << endl;
}
void sumToN(const int curr, const int last) {
for (int i=curr; i<=last; i++)
displayToN(i);
}
int main() {
int input;
cout << "Sum to: ";
cin >> input;
sumToN(1, input);
}
But with your limits, you have to emulate for loops with recursion like that:
#include <iostream>
using namespace std;
void displayToN(const int curr, const int last, const int sum = 0) {
if (curr < last) {
cout << curr << " + ";
displayToN(curr + 1, last, sum + curr);
} else {
cout << curr << " = " << (sum + curr) << endl;
}
}
void sumToN(const int curr, const int last) {
if (curr <= last) {
displayToN(1, curr);
sumToN(curr + 1, last);
}
}
int main() {
int input;
cout << "Sum to: ";
cin >> input;
sumToN(1, input);
}
This works
#include<iostream>
using namespace std;
int input;
int sumToN(int n, int row)
{
if (row==n) // BASE CASE
{
cout << row << " = ";
//cout<< row<<endl;
return row;
}
else // RECURSIVE CASE
{
cout << row << " + ";
return (row + sumToN(n, row+1));
cout << endl;
}
}
void caller(int n,int current){
if(current==n){
cout<<sumToN(n,1)<<endl;
}
else{
cout<<sumToN(current,1)<<endl;
caller(n,current+1);
}
}
int main()
{
cout << "Sum to: "<<endl;
cin >> input;
caller(input, 1);
}
Output
Sum to:3
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
If my input number is 2...I understand that the function will take the previous answer and multiply by 2 until the number will be greater than 25
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
16 * 2 = 32...program stops since num is 32
but then my final number is 62 how am I getting that number>
#include <iostream>
using namespace std;
int myRecursiveFunction (int num)
{
if (num >= 25) // stopping condition
return num;
else
cout << "number is at " << num << endl;
return num = num + myRecursiveFunction (num * 2);
}
int main()
{
int num, num1;
cout << "Enter a number: ";
cin >> num;
num1 = myRecursiveFunction(num);
cout << "Final number is: " << num1;
return 0;
}
You want to do this:
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
16 * 2 = 32...program stops since num is 32
you are doing
return num = num + myRecursiveFunction (num * 2);
which returns 32+16+8+4+2 = 62
2 + 4 + 8 + 16 + 32 = 62.
The return values are getting added each time.
I used the below code, but my numbers are incorrect & my instructor would rather I use a for loop. It also needs to print out:
The sum of "n" through "n" is " " (The sum of 1 through 1 is 1)
The sum of "n" through "n" is " " (The sum of 1 through 2 is 3)
I've tried using for loops, but can't seem to get the code right to print out the above. I'm lost!
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
const int NUM_LOOPS = 50;
int count = 0;
while (count < NUM_LOOPS)
{
cout << "Sum of 1 through " << count << " is " << (count * (++count)) / 2 << endl;
}
system("pause.exe");
return 0;
}
With a for loop it looks like this:
for (int i = 1; i <= NUM_LOOPS; i++)
{
cout << "Sum of 1 through " << i << " is " << i*(i+1)/2 << endl;
}
You could write it in a while loop just as easily if you wished.
Your problem was that you were initialising count to 0 rather than 1. Presumably to deal with the fact that you modified count in the middle of the long cout. The evaluation of the << operators are unsequenced relative to each other and your code exhibits undefined behaviour, as has been discussed here so many times before.
The bottom line with this is that the pre and post increment operators are dangerous in anything beyond the most simple expressions. Use the sparingly.
for (int count = 1; count <= NUM_LOOPS; ++count)
{
cout << "Sum of 1 through " << count << " is "
<< (count * (count+1)) / 2 << endl;
}
Don't do mix funny increments with mathematical formulas. Your future life will be happier.
I don't think it's a good way to calculate every summary. You just need to maintain one summary currently, and each time just add new value
Since multiple operation will cost more time than a single add.
const int NUM_LOOPS = 50;
int count = 0, sum = 0;
while ( count < NUM_LOOPS )
cout << "Sum of 1 through " << count << " is " << (sum+=(++count)) << endl;
My example is from 1 to 10
int sum=0;
for (int i = 1; i < 11; i++) {
for (int j = 1; j <= i; j++) {
cout << j;
sum=sum+j;
if(j != i){
cout << " + ";
}
}
cout << " = " << sum;
sum=0;
cout <<"\n";
}
Output is:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55