int k; (circled)
bool IsEven(int n); (circled)
k-; <-- incorrect. Closest match is k--; (decrements k by one)
if (k==1) { (circled)
k += 1; (circled)
}
b) State two advantages of using functions in program design.
Functions allow one to decompose a complex program into smaller, more easily understandable pieces. Functions allow code reuse. A function is defined only once, but it can be called (used) multiple times in a program.
bool IsPrime(int n) // Returns true if n>1 and the only divisors of n are 1 and n // Returns false otherwise (function body not shown)fill in the main() function below so that it prints all prime numbers between 1 and 10,000 to the console output cout. A prime number is an integer p for which the function invocation IsPrime(n) returns true. Consecutive numbers should be separated by spaces in the output.
One possibility:
(important point: there should *not* be any commas in 10000 below)
int main() {
for (int i=2; i<=10000; i++) {
if (IsPrime(i))
cout << i << " ";
}
return 0;
}
Another possibility:
int main() {
int i=2;
while (i<=10000) {
if (IsPrime(i))
cout << i << " ";
i++;
}
return 0;
}
a) int i=12;
cout << i%5; output: 2
b) int j=9;
cout << ++j; output: 10
c) int k=1;
while (k/4 < 2)
k*=3;
cout << k; output: 9
d) bool flag=false;
for (int i=1; i<=1000; i++)
if (i%3 == 0)
flag = !flag;
if (flag)
cout << "true";
else if (!flag)
cout << "false"; output: true
e) int lambda = 32;
while (lambda > 0) {
int k=lambda;
while (k > 0) {
cout << "*";
k /= 2;
}
cout << endl;
lambda /= 3; output: ******
} ****
**
*
int main() {
double x error: missing final semicolon
x = 3; warning, but no error: conversion from int to double
y = 4.5; error: object named y has not been declared
cout << the value of x+y equals << x+y; error: missing quotation marks
return 0.0; warning, but no error: conversion from double to int
}
bool UFO(int n)
{
while (n%2 == 0)
n/=2;
return (n==1);
}
Answer: UFO(n) returns true if n is a power of 2, and returns false
otherwise. For example, UFO(32) returns true because 32 equals 2 to
the 5th power, while UFO(7) returns false. By the way, UFO stands
for "Unidentified Function Object".