My solution to 3rd problem in Fun with Functions, any critic welcome
Task Description:
★★★ Make a function called half() that takes an integer argument. The function must print the number it received to the screen, then the program should divide that number by two to make a new number. If the new number is greater than zero the function then calls the function half() passing it the new number as its argument. If the number is zero or less than the function exits
Call the function half() with an argument of 100, the screen output should be
100
50
25
...
...
1
#include <iostream>
#include <string>
usingnamespace std;
//Function declared as requested in question
void half(int x=100){
cout<<x<<endl;
//Loop created to pass new value
for (;x>0;){
if (x/2>0){
//New value pasted to function argument to continue calculations
x = x/2;
cout<<x<<endl;
}else{
//Stopping program according to conditions specified in loop
break;
}
}
}
int main()
{
//Calling Function as requested by task
half();
}
We will never get zero as this is clearly division so any number being constantly divided by 2 will go in to decimals.
So I have taken approach that when the function calculates and the division is zero with reminder then it stops at 1 at least that was what the task was showing in expected result.
I do not know recursive yet so will dig into other code presented in comments later today and see how it works.
Thanks for commenting :)