Lab 05
Lab 05
Lab 05
Lab 05 Functions
Learning Objectives/Outcomes:
"Upon completion of this lab, the student should be able to:"
i. define a function prototype
ii. define function header and parameters
iii. call a function and pass arguments correctly
"iv. differentiate local and global variable's scope, as well as pass arguments
correctly between the functions."
v. apply the top-down algorithm and divide-and-conquer approach in solving the
complex programming problems
INSTRUCTION: ANSWER ALL QUESTIONS
ANSWER:
PRACTICE 1:
#include <iostream>
using namespace std;
int getMinimum(void);//function prototype
"int getMaximum(void); void findEven(int, int);"
int main()
{
int min = getMinimum();
"int max = getMaximum(); findEven(min, max); return 0;"
}
"//12,14,16,18"
"void findEven(int min, int max) {"
"cout << ""The even numbers between"" << min << ""and"" << max << ""are : "" <<
endl; if (min % 2 != 0) {"
min = min + 1;
}
else {
}
min = min + 2;
while (min < max) {
cout << min; min += 2;
}
if (min < max) {
"cout << "", "";"
}
}
int getMinimum(void) {
int input;
"cout << ""Enter a minimum value >> ""; cin >> input;"
return input;
}
int getMaximum(void) { int input;
"cout << ""Enter a maximum velue >> ""; cin >> input;"
return input;
}
PRACTICE 2:
#include <iostream>
using namespace std;
"void sort3(int, int, int);"
int main() {
"int a, b, c;"
"cout << ""int a = ""; cin >> a;"
"cout << ""int b = ""; cin >> b;"
"cout << ""int c = ""; cin >> c;"
"sort3(a, b, c);"
return 0;
}
"void sort3(int a, int b, int c) {"
if (a > c)
"swap(a, c); if (a > b)"
"swap(a, b); if (b > c)"
"swap(b, c);"
"cout << a << "" "" << b << "" "" << c;"
return;
}
PRACTICE 3:
#include <iostream>
using namespace std;
int sumDigits(int y)
{
"int x, sum = 0;"
while (y > 0)
{
x = y % 10;
sum = sum + x; y = y / 10;
}
return sum;
}
int main()
{
"cout << ""This program calculates the average of three test scores."" << endl;"
long int number;
"cout << ""Enter a credit card number as a long integer: ""; cin >> number;"
"int sum1 = 0, sum2 = 0;"
bool flag = false;
long int temp = number;
while (temp != 0)
{
if (flag)
{
sum1 += sumDigits((temp % 10) * 2);
}
flag = !flag;
temp = temp / 10;
}
temp = number;
flag = true;
while (temp != 0)
{
if (flag) {
sum2 += temp % 10;
}
flag = !flag;
temp = temp / 10;
}
if ((sum1 + sum2) % 10 == 0)
"cout << number << "" is valid"" << endl; else"
"cout << number << "" is invalid"" << endl; return 0;"
}