Return Types
Part of the Fundamentals section of Coddy's C++ journey. Lesson 53 of 74.
The return statement in a function is used to specify the value or values that the function should produce as its output. For example, the following function will output 100:
int functionName() {
return 100;
}To pass the value to a variable, write:
int number = functionName();Now the number variable will hold 100 because this is what the function returned.
Note that the return type of the function (int in this case) must match the data type of the variable where you're storing the returned value.
Challenge
EasyEach test case has three inputs.
The first input indicates how many times to do iterations, and the last two inputs are numbers that we will do operations on.
Create a function that receives two arguments and returns the bigger number of the two. if both are equal then return one of them.
Iterate iterations times and for each iteration do:
- Call the function with
num1,num2, and save the result in a variable. - Divide the bigger number of the two by
2, and then replace the original larger variable with the new result value. - print the new value.
- Continue doing it until the program iterated
iterationstimes or one of the numbers is smaller than 2.
Remember: The bigger number can change! Every time you divide a number, it gets smaller. In the next iteration of the loop, the number that was previously smaller might now be the larger one. Your code should check which number is currently larger at the start of every iteration.
Note you already have the skeleton of the code!
Try it yourself
#include <iostream>
double bigger(double arg1, double arg2) {
// Complete the function
}
int main() {
int iterations;
double num1, num2;
std::cin >> iterations >> num1 >> num2;
for (int i = 0; i < iterations; i++) {
// Write your code below
}
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - ElsePractice on your own: Online C++ compiler