The code is below. Please explain and also give the output.
#include <iostream>
#include <conio.h>
using namespace::std;
int main() {
// clrscr();
int sum(int(*)(int), int);
int square(int);
int cube(int);
cout << sum(square, 4) << endl;
cout << sum(cube, 4) << endl;
getch();
// return 0;
}
int sum(int(*ptr)(int k), int n){
int s = 0;
for(int i =1; i <= n; i++){
s +=(*ptr)(i);
}
return s;
}
int square(int k){
int sq;
sq =k *k;
return k*k;
}
int cube(int k){
return k*k*k;
}
No clue what's happening ! Please help me understanding this code. Specially in function
int sum(int(*)(int), int);
Not able to understand the above syntax in particular. But it would be help full to explain the whole code.
The following is what your program actually does:
When n = 4, the function sum(square, 4) is invoked.
This in turn calls the square() method and computes the value of
*ptr as 1 and then s will become 1 adding 0+1. *ptr was
assigned the value as 1 by calling the square() method which
returns the value 1*1 which in turn gets assigned to *ptr.
When i = 2, again the square() method is invoked and the value of
4 gets assigned to (*ptr)(2) since it's 2*2 that's returned by
the method square() in this case. The value 4 gets added up to the value in s which was 1 and the value of s becomes 1+4=5.
When i = 3, again the square() method is invoked and the value of
9 gets assigned to (*ptr)(3) since it's 3*3 that's returned by
the method square() in this case. The value 9 gets added up to the value in s which was 5 and the value of s becomes 5+9=14.
Finally, when i = 4, again the square() method is invoked and the value of
16 gets assigned to (*ptr)(4) since it's 4*4 that's returned by
the method square() in this case. The value 9 gets added up to the value in s which was 14 and the value of s becomes 14+16=30.
The value 30 is returned by the function and this is obtained by
the main() where this method was invoked.
The working of the call sum(cube, 4) is quite similar to the above explanation. The only difference is that its the cube(int) method is being invoked and the value that gets assigned to (*ptr)(i) will be i*i*i which gets returned from the cube() method. The value of s will initially be zero which gets added up to s = 1 (0+1), s = 9 (1+8), s = 36 (9+27) and finally s=100 (36+64) which is returned to main() method where it was invoked.
In other words, your program will work similar to the following code:
#include <iostream>
int sum(std::string, int);
int square(int);
int cube(int);
int main() {
std::cout << sum("square", 4) << std::endl;
std::cout << sum("cube", 4) << std::endl;
return 0;
}
int sum(std::string value, int n) {
int s = 0;
for (int i = 1; i <= n; i++) {
if (value == "square") {
s = s + square(i);
} else if (value == "cube") {
s = s + cube(i);
}
}
return s;
}
int square(int k) {
return k*k;
}
int cube(int k) {
return k * k * k;
}
I suggest that you use a std::cout in the for loop inside the sum() method of your program to see and analyze the results yourself. You can also use a debugger to see the workflow of your program if your IDE supports that.
Related
Task:
Implement square() without using the multiplication operator; that is, do the
x*x by repeated addition (start a variable result at 0 and add x to it x times).
Then run some version of "the first program" using that square().
Solution #1:
#include <iostream>
int square(int x){
int result = 0; // same output of we declare result without initializing
for (int i = 0; i < x; i++) {
result += x;
}
}
int main() {
std::cout << square(19);
}
Output: 19.
Solution #2:
#include <iostream>
int square(int x){
int result = 0;
for (int i = 0; i < x; i++) {
return result += x;
}
}
int main() {
std::cout << square(19);
}
Output: 19.
Solution #3:
#include <iostream>
int square(int x){
int result;
for (int i = 0; i < x; i++) {
return result += x;
}
}
int main() {
std::cout << square(19);
}
Output: 22006.
Why does only the third one work?
Solution #1
You don't return result, thus you calculate it but never return it
i.e.
#include <iostream>
int square(int x){
int result = 0; // same output of we declare result without initializing
for (int i = 0; i < x; i++) {
result += x;
}
return result;
}
int main() {
std::cout << square(19);
}
Solution #2
You return the result after the first iteration, this will always return x's value.
#include <iostream>
int square(int x){
int result = 0;
for (int i = 0; i < x; i++) {
result += x; // remove "return" here
}
return result;
}
int main() {
std::cout << square(19);
}
Solution #3
This is an interesting one. With languages like C++, you need to initialize your variables such as integers, see this for more info. Since you don't initialize it, your the integer gets a memory allocation and what ever is in memory at that point is what your int value is now. Since you only add to it, it will add the calculation to that value.
Thus, you need:
#include <iostream>
int square(int x){
int result = 0; // initialize values
for (int i = 0; i < x; i++) {
result += x; // remove return here
}
return result; // return result here
}
int main() {
std::cout << square(19);
}
This is invalid code: the function square is declared as int, but doesn't return anything.
You return prematurely, during the first iteration of the loop.
Same as #2, but with unitialized variable result - garbage.
You seem to have understood the task you have to accomplish. And you're very close to the result. But there's several major issues, which is why none of the provided solutions work.
Solution 1
You seem to be doing the task correctly, but never return the result. The fact that the output returns 19 in your case is surprising, but it won't always be like that. See here
Solution 2
You might to read up again on return. It returns the value immediately. So in essence, you're only doing one pass inside the loop, so you're only returning the parameter of the function, which in this case is 19.
Solution 3
This one has the same issue with return than the previous one. But you're also adding to an uninitialised value of result, and because of that can have litterally any possible value inside of it. Which is why you're getting a weird number as a result.
For Solution 1, never returning a value inside a function that expects a return value, and in Solution 3, accessing the value of an uninitialised value, are called undefined behaviours. In short, never have undefined behaviour in your code, it might work some times on some machines/compilers, but most of the time it will simply not work, or worse, "work" but in unpredictable ways, causing major issues and bugs.
#include"std_lib_facilities.h"
int main()
{
int i = 0;
int x = i + 2;
while(i<10){
++i;
}
cout<<x<<'\n';
}
I am a beginner and I want the result to print: after every loop i should get incremented by 1 which it does but the problem is if we print x it is still 2. Please provide an answer.
Your variable i is already incremented but but the problem was, the x is already assigned previously by 0 + 2 (i + 2) and loop executed later, therefore the value was unchanged. Consider the following code:
#include <iostream>
int main(void)
{
int i = 0;
int x;
for (; i < 10; i++) // same algorithm as per of your requirement in FOR loop
{
x = i + 2;
std::cout << x << std::endl; // x will be incremented each time
}
return 0;
}
I'm currently learning C++ and wrote an Array Reverse Function for learning purposes only.
Everything works fine. But if i want to write back my value from my stack into my array.. it fails.
#include "iostream"
#include <stack>
using namespace std;
void reverseArray(int *a, int s) {
stack<int> stack;
register int i;
for (i = 0; i < s; i++) { // iterates from 0 to 5
stack.push(*a);
a++; // pointer adress + 4 byte
}
for (i = 0; i < s; i++) { // iterates from 0 to 5
a = &stack.top(); // this fails!!
printf("%i\n", *a); // Here ist the right output
stack.pop();
a++; // pointer adress + 4 byte
}
}
int main() {
const int SIZE = 5;
int array[SIZE] = {1, 2, 3, 4, 5};
reverseArray(&array[0], SIZE);
printf("This should be 5: %i\n", array[0]);
return 0;
}
This creates following output:
5
4
3
2
1
This should be 5: 1
With the statement
a = &stack.top();
you have two problems:
You assign to a local variable. That assignment will not outlive the life-time of the variable, which is until the function returns.
You make the variable point to data that will no longer exist once you pop the element.
The solution to both of these issues is to save the value of a into a temporary variable that you use for the first loop. Then you can use a in the second loop much like you do in the first loop currently, and assign to its dereferenced value (like e.g. *a++ = stack.top()).
On an unrelated note, the register keyword has been deprecated since C++11 and will be removed in C++17. It will most certainly not do anything.
I just solved the problem.
*arrayin this case is always pointing to the first item in array -> array[0]
I don't need array++, because i calculate it with *(array + i)
void reverse(int *array, const int s) {
stack<int> stack1;
for (int i = 0; i < s; i++) {
stack1.push(*(array + i));
}
for (int i = 0; i < s; i++) {
*(array + i) = stack1.top();
stack1.pop();
}
}
void base(int n,int b)
{
int x[20],k=0;
while(n!=0)
{
x[k]=n%b;
n=n/b;
k=k+1;
}
for(int i=0;i<=k;i++)
{
cout<<x[k-i];
}
return ;
}
int main()
{
int number,baise;
cin>>number;
cin>>baise;
base(number,baise);
return 0;
}
It is program of base expansion. I wrote a function for that and in main() I call it with 2 parameters (that I want to convert into another base) and baise (that is a base value into which a number is converted). The program runs and it also gives output but with the input it gives some undesirable values, which is 6295648 in this case.
Input:
241
2
Output
629564811110001
But the output should be 11110001 only. I don't understand why the value 6295648 comes.
for(int i=0;i<=k;i++)
{
cout<<x[k-i];
}
At the first iteration of the loop, the executed statement is:
cout << x[k];
where x[k] is never assigned, which is an UB.
Changing the loop initialization statement to x = 1 solves this problem. Or more clearly,
for(int i = k-1; i >= 0; i--)
{
cout << x[i];
}
The issue with your code is that k gets incremented post the assignment in the x[] array i.e. In the last iteration k gets incremented to 8. Then in case of k-i when the value of i is 0 .. x[k-i] goes out of bounds.
#include <iostream>
using namespace std;
void base(int n,int b)
{
int x[20],k=-1;
while(n!=0)
{
x[++k]=n%b; //pre increment
n=n/b;
}
for(int i=0;i<=k; i++)//now k contains the index of the last element
{
cout<<x[k-i];
}
return ;
}
int main()
{
int number,baise;
cin>>number;
cin>>baise;
base(number,baise);
return 0;
}
I have a code that searches for a given entry in an array, and returns the position in the array of that entry, provided one knows the array contain that number. However, a strange thing happens. When I try to test the code with some concrete arrays, the code works well for some entries, and it does not work for others. The code is this:
#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
int a = (n/2);
int b = n;
int tmp = 0;
while (x != data[a])
{
if (x > data[a])
{
tmp = a;
a = (b+a)/2;
b = b;
}
if (x < data[a])
{
a = tmp;
b = a;
}
}
return a;
}
(in a previous version I was using the floor function to round the numbers contained in a to their integer parts, but I understand this is not necessary.)
I have tested the program for example for the following array in this main:
int main()
{
int n = 6; int x = 12;
int array1[] = {3,12,5,9,7,11};
cout << "The entry " << x << " is found at position "
<< 1+Find_entry(array1, n, x) << endl;
return 0;
}
When I type as in this example x=12, the program gives the correct answer 1. Same thing for x=3, x=11 and x=9. But if I type x=7 or x=5, the program refuses to give an output and I get a message like
"Process terminated with status -1073741510 (0 minute(s), 9 second(s))".
Can anybody explain what's the problem here? How can be the code fixed?? Thank you all for your answers.
You cannot use binary search for unsorted array. Use linear search.
int Find_entry(int data[], int n, int x)
{
int a = 0;
while (a < n && x != data[a]) a++;
return a;
}
Binary search only works on sorted inputs.