Hello all!
I want to share my solution to the beginner problem Fun with Functions.
I hope that someone will find it helpful!
Any suggestion for improvement are welcomed as well!
Requires: variables, data types, and numerical operators
basic input/output
logic (if statements, switch statements)
loops (for, while, do-while)
functions
Write a function titled say_hello() that outputs to the screen "Hello"
★ Modify the function so that it takes an integer argument and says hello a number of times equal to the value passed to it.
★★ Make another function that takes two integers arguments and then returns an integer that is the product of the two integers.
(i.e., integer1: 4, Integer2: 5 returns: 20)
★★★ 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <conio.h>
using namespace std;
void say_hello(int);
int product(int, int);
void half(int number);
int main()
{
int n;
cout << "n="; cin >> n;
say_hello(n);
cout << endl;
int a, b;
cout << "a="; cin >> a;
cout << "b="; cin >> b;
cout << product(a,b);
cout << endl;
int number;
cout << "number="; cin >> number;
half(number);
_getch();
}
void say_hello(int n)
{
for(int i=0; i<n; i++)
{
cout << "Hello ";
}
}
int product(int a, int b)
{
int result;
result = a * b;
return result;
}
void half(int number)
{
if(number == 0)
{
cout << "Program will exit!";
return;
}
do
{
cout << number << endl;
number = number / 2;
} while(number != 0);
}
|