fork download
  1. // If you are not sure what some lines of code do, try looking back at
  2. // previous example programs, notes, or ask a question.
  3.  
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. int addFrom(int);
  9.  
  10. int main() {
  11.  
  12. char selection;
  13.  
  14. // A simple do/while loop, where the loop will continue asking the user
  15. // to continue until they enter something that is not 'y'
  16. do {
  17. cout << "Continue? (y/n): ";
  18. cin >> selection;
  19. } while(selection == 'y');
  20.  
  21. cout << endl << endl;
  22.  
  23. // A nested for loop, will run the inner loop 10 times. Each time the outer
  24. // loop is run, i is incremented, and hence the first output number goes up
  25. // every ten outputs. Within each run of the outer loop, the inner loop sets
  26. // j to 0, and counts it up to 10, which produces each pair of output numbers.
  27. for(int i = 0; i < 10; i++) {
  28. for(int j = 0; j < 10; j++) {
  29. cout << i << "-" << j << " ";
  30. }
  31. cout << endl;
  32. }
  33.  
  34. cout << endl << endl;
  35.  
  36. // This calls the recursive function
  37. cout << "Recursion example: " << addFrom(5) << endl << endl;
  38.  
  39. system("pause");
  40.  
  41. return 0;
  42. }
  43.  
  44. // This is a recursive function. See the notes for how it works.
  45. int addFrom(int x) {
  46.  
  47. if(x == 1)
  48. return 1;
  49. else
  50. return x + addFrom(x - 1);
  51.  
  52. }
  53.  
Success #stdin #stdout #stderr 0s 3464KB
stdin
y
y
y
n
stdout
Continue? (y/n): Continue? (y/n): Continue? (y/n): Continue? (y/n): 

0-0 0-1 0-2 0-3 0-4 0-5 0-6 0-7 0-8 0-9 
1-0 1-1 1-2 1-3 1-4 1-5 1-6 1-7 1-8 1-9 
2-0 2-1 2-2 2-3 2-4 2-5 2-6 2-7 2-8 2-9 
3-0 3-1 3-2 3-3 3-4 3-5 3-6 3-7 3-8 3-9 
4-0 4-1 4-2 4-3 4-4 4-5 4-6 4-7 4-8 4-9 
5-0 5-1 5-2 5-3 5-4 5-5 5-6 5-7 5-8 5-9 
6-0 6-1 6-2 6-3 6-4 6-5 6-6 6-7 6-8 6-9 
7-0 7-1 7-2 7-3 7-4 7-5 7-6 7-7 7-8 7-9 
8-0 8-1 8-2 8-3 8-4 8-5 8-6 8-7 8-8 8-9 
9-0 9-1 9-2 9-3 9-4 9-5 9-6 9-7 9-8 9-9 


Recursion example: 15

stderr
sh: 1: pause: not found