Function to find largest number - c++

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

Related

Why did my code cannot check if the word is a palindrom?

The title pretty much describes my question. I cannot recall what is wrong with my code, can you help me with it?
#include <bits/stdc++.h>
using namespace std;
int p(string &s, int f, int l){
if(s[f] == s[l]){
return(s, f +1, l-1);
}
else{
return 0;
}
if(f-l == 1 || f == l){
return 1;
}
}
int main(){
string s;
cin >> s;
int f = 0;
int l = s.length()-1;
if(p(s, f, l)){
cout << "YA";
}
else{
cout << "BUKAN";
}
}
I choose to answer the question in the body, instead of the question in the title (in line with How do I ask and answer homework questions? which I also appy to "competetive programming" questions).
Some things wrong with your code:
Your third return in p() can never be executed, because both branchs of the if-then-else structure before already contain a return.
And if it could, there would also be a path without a return through that function.
What jkb and 273k hint at in the comments return(s, f +1, l-1); is probably a doomed attempt to call p() recursively, returning instead a the result of the , operators and the - calculation.

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

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.

How to decrement several variables in C++in a single line statement?

Edit: I replaced the phrase 'in one line' by 'in a single line statement' since this is what I was looking for
Let's say we have the following variables at hand:
int a = 5;
int b = 9;
Is there a way to compress this ...
a--;
b--;
... into in a single line statement??
The question is not about decrementing multiple variables in a for loop,
since this seems to be a common yet unrelated question.
You probably mean "in a single statement", not just "in a single line".
Then you can use the comma-operator:
(a--,b--);
// use a template
template<class ... Args>
void decr(Args& ... args){
(... , --args);
}
decr(a,b,c);
// or, in C++20, auto
void decr(auto& ... args){
(... , --args);
}
You could just write the statements in one single line, like this :
a--, b--;
(thanks to #Aziz for the improvement with the comma instead of the semicolon)
You can do like :
int a = 5;
int b = 4;
(a -= 1), (b -= 1);
std::cout << a << b;
Output: 43
You can try something like :
#include <iostream>
using namespace std;
main ()
{
int a = 5, b = 9;
a--, b--;
cout << a;
cout << b;
return 0;
}
Output:
48

Returning the complete value in recursions

I've written a C++ code to convert a base 10 number into base two, but don't want the function to print it, but to return the value since I'll later need to use it in another function. The problem with returning is that the first time it returns it'll break out of the function, so it won't finish the process of converting and instead of returning '101' for '5', it will simply return '1' and that's it. Any ideas to fix this? I appreciate in advance.
Here's also my code:
int two;
int base(int a)
{
if(a==1)
{
two=a%2;
}
else
{
base(a/2);
two=a%2;
}
return two;
}
Note: Of course the code works pretty well if I change the return type into void and simply print the value. But I want to RETURN the value.
Implementation of summing up (in fact it can be implemented iteratively but it seems you need to apply recursion so I provided recursive solution):
int baseHelper(int a, int factor)
{
int returnedValue = 0;
if(a==0 || a==1)
returnedValue = factor * a;
else
{
int addend = factor * (a%2);
returnedValue = addend + baseHelper(a/2, factor*10);
}
return returnedValue;
}
int base(int a)
{
return baseHelper(a, 1);
}
int main()
{
for(int i=0; i<=256; i++)
cout << "i=" << i << " " << base(i) << endl;
return 0;
}
If you want to use recursion, you can return std::string like this:
std::string base(int a)
{
if (a == 0)
return "0";
else if (a == 1)
return "1";
else
return base(a / 2) + ((a % 2) ? "1" : "0");
}
Using std::to_chars or std::from_chars from <charconv> is also an alternative.

Recursive (sum of even numbers from 2 to (2 times n) ex: input : n=6, output : 2+4+6

Can anyone fix this code to make it right?
I think it's almost right but the last number is correct number but followed by random number.
#include <iostream>
using namespace std;
int jumlah(int a, int b){
if(a*2==b){
cout<<b;
}else{
cout<<b<<"+";
cout<<jumlah(a, b+2);
}
}
int main(){
int a, b;
b=2;
cin>>a;
jumlah(a, b);
return 0;
}
Your function never returns anything, so printing the result of the recursion is undefined.
Remove the result from the function and recurse without printing.
void jumlah(int a, int b){
if(a*2==b){
cout<<b;
}else{
cout<<b<<"+";
jumlah(a, b+2);
}
}
Your code has undefined behavior since the function does not return anything.
Change it to:
int jumlah(int a, int b){
if ( a*2 == b){
return b;
}
cout << b << "+";
return jumlah(a, b+2);
}
and change the call in main to:
cout << jumlah(a, b);