Reverse number function not working properly after first run - c++

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;.

Related

Implementing square() without using the multiplication operator

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.

Return value of a function with a loop?

I have the following code, however i am confused about several things:
Why is the sum inside the loop returning? why not the one outside?
or does the program return will return value encountered and ignore the rest?
#include <iostream>
using namespace std;
int m(int n)
{
int sum = 0;
for(int i =1;i<=2;i++)
{
sum= sum + 10;
return sum+3333; //returns inside loop
}
return sum-10;
}
int main()
{
int n = 1;
cout << m(n) << endl;
return 0;
}
Once the compiler will encounter return it will go back to main; so in this case it will return to main once it encounter it inside the loop

C++ integer digits to line by line

I am working with my project that will convert the integer value to each line.
Example:
23487
Output will be
2
3
4
8
7
I know the code if I will used string, but I think its better if I use integer.
My current code using string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str("23487");
for (int i = 0; i < str.size(); i++){
cout << str[i] << endl;
}
system("pause");
return 0;
}
Can anyone help me if I use int instead of string?
For integer values larger than 0, you can use this:
void Print(int val)
{
if (val > 0)
{
Print(val/10);
cout << val%10 << endl;
}
}
Try this... This code will print as exactly you want... :)
#include <iostream>
#include <string>
using namespace std;
int main() {
int a=23487,ara[10],i=0,j;
while(a)
{
ara[i++]=a%10;
a/=10;
}
for(j=i-1;j>=0;j--)
cout<<ara[j]<<endl;
return 0;
}
Try
#include <stdio.h>
int main(int argc, char * argv[])
{
int value = 23487;
while(value > 0)
{
int d = value % 10;
value /= 10;
printf("d = %d\n", d);
}
return 0;
}
Note that the digits will be printed backwards.

c++ two errors while compiling

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
}
}
}

Print out even number

I just want to ask your help here. I am new beginner in c++ programming. How to print out the even number in range 100 - 200. I tried write some code and it didn't work out. Here is my code. I hope, someone here can help me. Will appreciate that so much. Thanks.
include <stdio.h>
void main()
{
int i;
for (i= 100; i<= 200; i += 2){
print i;
}
}
Well, pretty simple:
#include <iostream> // This is the C++ I/O header, has basic functions like output an input.
int main(){ // the main function is generally an int, not a void.
for(int i = 100; i <= 200; i+=2){ // for loop to advance by 2.
std::cout << i << std::endl; // print out the number and go to next line, std:: is a prefix used for functions in the std namespace.
} // End for loop
return 0; // Return int function
} // Close the int function, end of program
you were using C libraries, not C++ ones, as well as no function that is called print in C++, nor C. Also there is no void main function, use int main() instead. finally, you need to have std:: in front of cout and endl as these lie in the std namespace.
Use the following code:
#include <iostream>
int main()
{
int i;
for (i= 100; i<= 200; i += 2){
std::cout << i << std::endl;
}
return 0;
}
Your code looks good....Only the printing part needs to be changed
#include <stdio.h>
int main()
{
for (int i= 100; i<= 200; i += 2){
printf("%d",i);
}
return 0;
}
This might help!
#include <iostream>
using namespace std;
int main()
{
for (int count = 100; count <= 200; count += 2)
{
cout << count << ", ";
}
cout << endl;
return 0;
}