Basic Programming Elements
In this tutorial we overview the basic elements of a programming language such as decisions, loops, and functions.
Tasks
Write a single program for each of the following:
- Difficulty: L0 Decision: Read in a number, determine if it is even or odd and output it on the screen.
- Difficulty: L1 Loops: Read in an integer and compute the factorial of this number.
- Difficulty: L1 Functions: Rewrite the program from the previous example (loops) to use a function which computes the factorial of the given number. The function should return the factorial.
Issues
Write mechanisms for each program to verify the input and output.
C++ Reference Implementation
#include<iostream> #include<cmath> long factorial(long number) { long result = 1; for (long i =1 ; i <= number; ++i) { result *= i; } return result; } int main() { long a; std::cout << "Please enter a: " ; std::cin >> a; std::cout << "the factorial of " << a << " is: " << factorial(a) << std::endl; return 0; }