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.
Related
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.
Here is my code:
#include <iostream>
using namespace std;
int rev(int i) {
int ret;
while (i >= 1) {
ret += i%10;
i /= 10;
ret *= 10;
}
return ret/10;
}
int main() {
//rev(4);
cout << rev(123) << endl;
return 0;
}
When I run it, I get "321", as I should.
But when I un-comment the line above it, I get "4321"!
Why is this?
Uninitialized ret. You have a pre-existing garbage value getting mixed in with your computation.
Give
int ret = 0;
a go.
The initial value of int ret; is undefined (any value). Replace it with int ret = 0;.
I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:
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().
Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:
int square(int x)
{
int i = 0;
for(int counter = 0; counter < x; ++counter)
{
i = i + x;
}
return i;
}
But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?
Mats Petersson stole the idea out of my head even before I thought to think it.
#include <iostream>
template <typename T>
T square(T x) {
if(x < 0) x = T(0)-x;
T sum{0}, s{x};
while(s) {
if(s & 1) sum += x;
x <<= 1;
s >>= 1;
}
return sum;
}
int main() {
auto sq = square(80);
std::cout << sq << "\n";
}
int square(int x) {
int result = { 0 };
int *ptr = &result;
for (int i = 0; i < x; i++) {
*ptr = *ptr + x;
}
return *ptr;
}
I am reading that book atm. Here is my solution.
int square(int x)
{
int result = 0;
for (int counter = 0; counter < x; ++counter) result += x;
return result;
}
int square(int n)
{
// handle negative input
if (n<0) n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i=1; i<n; i++)
res += n;
return res;
}
//Josef.L
//Without using multiplication operators.
int square (int a){
int b = 0; int c =0;
//I don't need to input value for a, because as a function it already did it for me.
/*while(b != a){
b ++;
c = c + a;}*/
for(int b = 0; b != a; b++){ //reduce the workload.
c = c +a;
//Interesting, for every time b is not equal to a, it will add one to its value:
//In the same time, when it add one new c = old c + input value will repeat again.
//Hence when be is equal to a, c which intially is 0 already add to a for a time.
//Therefore, it is same thing as saying a * a.
}
return c;
}
int main(void){
int a;
cin >>a;
cout <<"Square of: "<<a<< " is "<<square(a)<<endl;
return 0;
}
//intricate.
In term of the running time complexity,your implementation is clear and simply enough,its running time is T(n)=Θ(n) for input n elements.Of course you also can use Divide-and-Conquer method,assuming split n elements to n/2:n/2,and finally recursive compute it then sum up two parts,that running time will be like
T(n)=2T(n/2)+Θ(n)=Θ(nlgn),we can find its running time complexity become worse than your implementation.
You can include <math.h> or <cmath> and use its sqrt() function:
#include <iostream>
#include <math.h>
int square(int);
int main()
{
int no;
std::cin >> no;
std::cout << square(no);
return 0;
}
int square(int no)
{
return pow(no, 2);
}
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.
I'm a beginner in c++ and I'm getting two errors in my code and I don't know how to fix them...
the first one
illegal indirection
and the second one is
'=' left operand must be a I-value. (in the line: ((ArrayPtr +i)+j)=rand()%55+1 )
Does anyone have an idea how to fix them? That's my code:
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 6;
void FillingRandomly(int (*)[AS]);
void printing(int (*)[AS]);
int c;
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
FillingRandomly(Array);
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
printing(Array);
system("PAUSE");
return 0;
}
void FillingRandomly(int *ArrayPtr)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
*(*(ArrayPtr +i)+j)=rand()%55+1;
}
}
}
void printing(int *Array)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS*AS;j++)
{
int counter = 0;
cout<<((Array[i] +j))<<setw(5);
if ((Array[i] +j)%AS == 0)
cout << endl << endl;
}
}
}
void forsorting(int *Brray, int funny)
{
int dice = 0;
int super = 0;
int space=0;
//Sorting Array[][] which is treated like Array[]
{
for (int pass = 0; pass < AS - 1; pass++) {
for (int k = 0; k < AS - 1; k++) {
int temp;
if(*(Brray+k)==*(Brray+k+1))
{
temp=*(Brray+k);
*(Brray+k)=*(Brray+k+1);
*(Brray+k+1)=temp;
}
}
}
}
}
By
*(*(ArrayPtr +i)+j)=rand()%55+1;
it seems you want
ArrayPtr[i][j] = (rand() % 55) + 1;
You can try something along the line of
int const offset = AS * i + j;
int const elem = (rand() % 55) + 1;
*(ArrayPtr + offset) = elem;
Your function signature is:
void FillingRandomly(int *ArrayPtr)
where you are telling to compiler that you are passing a simple pointer, but in the line:
*(*(ArrayPtr +i)+j)=rand()%55+1;
you are doing a double derreference, which is illegal and causing the compiler to complain
COMPLEMENT
I was seeing the comments in the other answer and, as what I need to write is bigger than the reserved commentary space, I decided to complement my own answer.
You defined Array as:
int Array[AS][AS];
Indeed, what you are doing is a promise to compiler that you will use Array as defined, but the compiler doesn't believe in you too much, so that any time you use Array the compiler will make sure that it is being used as declared.
The problem arises when you declare your FillingRandomly function. Here you are broking your promise and are trying to use Array by declaring a differente type. Note how you declare your function:
void FillingRandomly(int *ArrayPtr)
Due the fact that c++ supports function overloading, the compiler doesn't warn you until it initiate the linking phase, when it is unable to find a function whose signature is:
void FillingRandomly(int ArrayPtr[][AS])
note that both are different.
Once you are a beginner, the best way to keep your programs correctly is to keep your promise immutable. Bellow I show you a piece of your own code, correcting those issues for FillingRandomly function (you have to correct it for the others functions too):
const int AS = 6;
void FillingRandomly(int [][AS]); // Note that I've changed your prototype here
....
void FillingRandomly(int ArrayPtr[][AS]) // Keep your function signature the same as your prototype signature
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
ArrayPtr[i][j]=rand()%55+1; // Note how ArrayPtr is being used exactly as your promised early
}
}
}