Using --a vs a-1 in recursion [duplicate] - c++

This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 2 years ago.
I was trying to calculate a factorial using recursion like this:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(--a);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
and it wasn't working. Then, I made a small change:
#include <iostream>
using namespace std;
int factorial(int a)
{
if(a == 0)
{
return 1;
}
return a*factorial(a-1);
}
int main()
{
int a;
cin >> a;
cout << factorial(a) << endl;
return 0;
}
... and it started working!
The problem is that I don't see any difference between these codes: Why didn't it work in the first code?

In your first code sample, the following line has undefined behaviour:
return a * factorial(--a);
This is because there is nothing in the C++ Standard that dictates whether or not the 'old' or 'new' (decremented) value of a is used to multiply the return value of the factorial function.
Compiling with clang-cl gives the following:
warning : unsequenced modification and access to 'a' [-Wunsequenced]
In your second code sample, there is no such ambiguity, as a is not modified.

Related

How to return nothing from an integer function in C++? [duplicate]

This question already has answers here:
In a non-void function I want to return nothing
(2 answers)
When and how should I use exception handling?
(7 answers)
Closed 6 months ago.
Consider the following code:
#include <iostream>
int test(int a){
if (a > 10){
return a;
}
else{
std::cout << "Error!";
return nothing;
}
}
int main(){
std::cout << test(9);
return 0;
}
What I want is that The integer function test(int a), return a if a > 10, otherwise return Error!. but since this is an integer function, it must return an integer value, but I want that it print Error and return nothing. Is there a way for do this? (Also note that I don't want to use a void function)
#include <stdexcept>
int test(int a){
if (a > 10){
return a;
}
else{
throw std::invalid_argument( "a is smaller or eq than 10" );
}
}

This simple code should work but I am getting warning [duplicate]

This question already has answers here:
Code outside functions
(3 answers)
Closed 2 years ago.
#include <iostream>
using namespace std;
int *i = new int;
*i = 0;
int &j = *i;
j++;
//cout << *i << endl;
I have a code like that, and I know this syntax is true but it gives warning in Visual Studio Code like this:
quiz2_q8.cpp:5:4: error: expected constructor, destructor, or type conversion before '=' token
*i = 0;
^
quiz2_q8.cpp:7:1: error: 'j' does not name a type
j++;
Am I missing a library to include? I thought iostream is enough for this quiz code.
You can't have arbitrary statements in the global namespace. You need to put it into a function, e.g. like this:
int main() {
int *i = new int;
*i = 0;
int &j = *i;
j++;
}
Most programs have a starting point, which is the main method/function/procedure whatever you want to call it. Each function has a scope given by { // fun scope }. A good tutorial series on C++ might come to your aid, or perhaps a book. With that said here's a template for such a program.
#include <iostream>
using namespace std;
int main(){
return 0;
}
Statements for being executed must be inside functions.
#include <iostream>
using namespace std;
int main(void) { // add this
int *i = new int;
*i = 0;
int &j = *i;
j++;
//cout << *i << endl;
} // add this

Function to find largest number

I'm learning C++ through Sololearn. Below is a code to find the largest of two numbers.
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
return b;
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Result - 7
But shouldn't it return b also since there's return b in function????
Only one return statement will execute within a function. As soon as the code encounters the first return it will immediately leave the function and no further code will execute.
The answer of CoryKramer says it all.
Still, to avoid the confusion you bumped into, I would prefer:
#include <iostream>
using namespace std;
int max(int a, int b){
if (a > b) {
return a;
}
else {
return b;
}
}
int main() {
cout << max(7, 4) << endl;
return 0;
}
Alternatively you could use:
return a > b ? a : b;
The latter line is a so called 'conditional expression' (or 'conditional operator'). If the phrase before the ? is true, it returns the part between the ? and the :, else it returns the part after the : .
It is explained in detail here.
if (a > b) (7>4) ==> Condition becomes True so return a executed and max function return from there only, its not reach to return b, that's why its not execute return b.
You can use in return a > b ? a : b operator.
Operator return will
terminate the current function and returns the result of the expression to the caller
http://en.cppreference.com/w/cpp/language/return
After you passed the condition
if (a>b)
edited -> thanks to athul
return will evaluate a and put it as result of function.
If a is lesser then b - you will not meet this condition and you will hit
return b;
To understand it, you may add:
cout << max(2, 4) << endl;
cout << max(2, 1) << endl;
into the main section.
PS it is better to use at least codeblocks, which is advised in LearnC++ to enter their examples

Why it doesn't show me the greatest common divison?

When i try to start the program it doesn't work and doesn't show me any error. Why?
#include <iostream>
using namespace std;
int main()
{
unsigned a,b;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
{
while(a!=b)
{
if(a>b)
(a==a-b);
else
(b==b-a);
}
}
cout<<"cmmdc=",a;
return 0;
}
Replace a==a-b with a=a-b.
Replace b==b-a with b=b-a.
The operator == is comparison, it doesn't modify its arguments. The operator = is assignment, it modifies its left argument to the value of its right argument.
Replace cout<<"cmmdc=",a with cout<<"cmmdc="<<a, otherwise a won't be printed.
Even after changing the ==s to =s, you'll get an infinite loop if any but not both of a and b is 0. To avoid that, use this loop instead:
while (b != 0) {
const unsigned olda = a;
a = b;
b = olda % b;
}
// GCD is now in a.
It is the simplest way to find gcd of two numbers :
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a,b;
cout<<"a = ";
cin>>a;
cout<<"b = ";
cin>>b;
cout<<"GCD = " << __gcd(a,b);
}

Code Crashes Immediately After Running

Even at the bare minimum of 10 numbers to input, I get no errors but my code crashes immediately on running. I was also wondering, what should I do if I have a question similar to another question that I've already asked, but on another new problem?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
I get no errors but the compiled code crashes immediately.
I changed it to
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a.push_back(2);
for (double i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
}
I addressed all of your problems. It still returns no errors and still crashes.
What makes you think you can do this?
vector<int> a;
a[1]=2;
vector<int> a;
a[1]=2;
You can't access a[1] until you've reserved space for it. You should probably use a.push_back(2) to append 2 to the end of a.
You have declared primer to return int, yet it returns nothing. Either make it void or return the number of primes.
i/a[ii]==floor(i/a[ii]) isn't going to do what you expect. i/a[ii] performs integer division. You should cast i to double before dividing.
if (prime==true) can be changed to simply if (prime), no need to compare a boolean to true.
Please improve your coding style. Use proper indentation and more commonly used variable names: i, j, k instead of i, ii, iii.
Here is another bug:
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
return a.size();
}
My understanding is that you can only return once from a function, main included. The execution will not loop here because of the return statement.
Did you really want a return statement inside a for loop?