function

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.
bt what is the algorithm to find this output
if user enter 100 the output will be 100,50,25,......1.
i tried to do this #include<iostream>

using namespace std;


int main(){
int n,sum=1;
cin>>n;

while(n>0){

n=n/2;
sum=n;}

cout<<sum<<endl;

}
bt its wont work
if, not while.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{

int n,sum= 0;
cin>>n;

if(n > 0)
{
n=n/2;
sum=n;
}

cout<<sum<<endl;

}


Thats your algorithm. Now, all you have to do is put it in the function, and call the function from inside.
for your program, you forget to put return 0;

and your program only print out sum once, it is not what you want. So you just need to put cout inside the while loop.
His code, is supposed to be in a function, not main. Also, you dont need to put return 0 anymore. And it should not be a while loop, it should be an if statement. And in that if statement, you have to call the function. So the function will be called and divide the number n, print it out, over and over again until the if statement is false (n is less than 0) and it'll exit.

Its called recursion.

https://www.youtube.com/watch?v=RgCi5s8oITM&ab_channel=CodingMadeEasy
Last edited on
Topic archived. No new replies allowed.