Schedule‎ > ‎

Key Sample Code


string functions & concatenation (3.2)

/**
    CS-11 Asn 3, Project 2: dragon.cpp
    Purpose: Generates an inner dragon name for the user

    @author Sharon Strelitz
    @version 1.0 02/09/2018
*/
#include <iostream>
using namespace std;

int main() {
    cout << "Want to learn your \"dragon name\"?" << endl;
    string first = "", last = "", mother = "", father = "";
    cout << "Please enter your first and last name: ";
    cin >> first >> last;
    cout << "Please enter your mother's first name: ";
    cin >> mother;
    cout << "Please enter your father's first name: ";
    cin >> father;
    cout << "Your dragon name is: ";
    /*  dragon name algorithm:  
        The first two letters of your last name
        + last two letters of your first name
        + a space
        + the first two letters of your mother's name
        + the last letter of your father's name
    */  
    string dragonName = "";
    dragonName = last.substr(0,2) + first.substr(first.length()-2,2) + " " 
        + mother.substr(0,2) + father.substr(father.length()-1,1);
    cout << dragonName << endl;
    return 0;
}

if Statements (3.3)

/*
    CS-11 Exercise 3.3, selection.cpp
    Purpose: Guessing Game

    @author Sharon Strelitz
    @version 1.0 01/21/2018
*/

#include <iostream>
using namespace std;

int main() {
    int guess = 0;
    cout << "I'm thinking of a number between"
         << " 1 and 10.\nCan you guess it?\n\n"
         << "Enter your guess: ";
    cin >> guess;
    
    if (guess < 1) {
        cout << "Error: guess must be >= 1. \n";
        return -1;    //-1 is often used as an error return code
    }
    
    if (guess > 10) {
        cout << "Error: guess must be <= 10. \n";
        return -1;    //-1 is often used as an error return code
    }
    
    cout << "You entered: " << guess << endl;

    if (7 == guess) {
        cout << "*** Correct! ***" << endl;
    } else {
        cout << "Sorry, that is not correct.\n";
        cout << "Rerun and try again.\n";
    }

    return 0;
}

Nested if-else-if with Relational Operators (3.3.5 & 4.2)

/*
    CS-11 Exercise 4.2a, grader.cpp
    Purpose: Calculate the grade for a score

    @author Sharon Strelitz
    @version 1.0 01/21/2018
*/
#include <iostream>
using namespace std;

int main() {
    double score = 0.0;
    string grade = "";
    cout << "Enter a score: ";
    cin >> score;
    
    if (score >= 90) {   
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else if (score >= 70) {
        grade = "C";
    } else if (score >= 60) {
        grade = "D";
    } else {
        grade = "F";
    }
    cout << grade << endl;
    return 0;
}

while Loop (4.3)

#include <iostream>
using namespace std;


int main() {
    int guess = 0;
    string repeat = "y";
    while ("y" == repeat)  {
        cout << "I'm thinking of a number between"
            << " 1 and 10.\nCan you guess it?\n\n"
            << "Enter your guess: ";
        cin >> guess;

        if (7 == guess) {
            cout << "*** Correct! ***\n";
        } else {
            cout << "Sorry, that is not correct.\n";
            cout << "Try again.\n";
        }
        cout << "\nDo you want to play again? (y/n) ";
        cin >> repeat;
    }
    cout << "Game over\n";
    return 0;
}


while loop with logical operators (4.2.6 and 4.3)

/**
    CS-11 while loops with logical operators
    whileLogical.cpp
    Purpose: practice while loops with logical operators.  Okay will print
             after the user has entered a positive value then a negative value

    @author Sharon Strelitz
    @version 1   12/20/2017
*/

#include <iostream>
using namespace std;

int main() {  
    bool positive = false;
    bool negative = false;
    int value = 0;
    while (!positive || !negative) {  
       cout << "Enter a positive or negative value: " << endl;
       cin >> value;
       if (value > 0) {   
           positive = true;
       }
       if (positive && value < 0) {  
            negative = true;
       }
    }   
    cout << "Okay!" << endl;    
}

do-while loop to validate user input, cin.fail/clear/ignore (5.3.8)

#include <climits>
#include <iostream>
using namespace std;

int main() {
    double input = 0.0;
    bool more = true;
    do {
        cout << "Enter a positive number: ";
        cin >> input;
        if (cin.fail()) {
            cout << "You must enter digits, not words\n";
            cin.clear();
            cin.ignore(1000, '\n');
        } else if (input < 0.0) {
            cout << "You must enter a positive number\n";
        } else {
            more = false;
        }
    } while (more); // test condition
    cout << "You entered: " << input << endl;

    return 0;
}

for loop Bar Chart (5.2)

#include <iostream>
using namespace std;

int main() {
    int num = 0;
    cout << "Enter a number and I will show its"
         << " bar graph.\nEnter your number: ";
    cin >> num;

    cout << "\nBar graph:\n";
    for (int i = 1; i <= num; i++) {
        cout << '*';
    }
    cout << endl;

    return 0;
}

Nested for loop (5.2.3)

#include <iostream>
using namespace std;

int main() {
    cout << "I will print squares for you!\n\n";
    cout << "Enter the width of the square: ";
    int size;
    cin >> size;

    for (int row = 1; row <= size; row++) {
        for (int col = 1; col <= size; col++) {
            cout << "*";
        }
        cout << endl; // newline before next row
    }

    return 0;
}

Finding Minimum & Maximum (5.3.4)

/**
    CS-11 Assn 5 Extra Credit minmax.cpp
    Purpose: Find the minimum and maximum values from a list the user enters.

    @author Sharon Strelitz
    @version 1.0 01/21/2018
*/
#include <iostream>
using namespace std;

int main() {
    double newNum = 0.0, minimum = 0.0, maximum = 0.0;
    cout << "Enter a positive number (0 to stop): ";
    cin >> newNum;
    minimum = newNum;
    maximum = newNum;
    while (newNum > 0) {
        if (newNum < minimum) {
           minimum = newNum;
        } else if (newNum > maximum) {
           maximum = newNum;
        }
        cout << "So far, the lowest value is " << minimum 
             << " and the highest value is " << maximum << endl;
        cout << "Enter the next positive value (0 to exit): ";
        cin >> newNum;
    }
    if (minimum > 0) {
        cout << "Minimum value is: " << minimum 
             << " and maximum value is " << maximum << endl;
    } else {
        cout << "No data!\n";
    }
    return 0;
}

Iterate through a String (6.1.3)

/*
    CS-11 Ex 6.2 iterate.cpp
    Purpose: iterating through a string

    @author Sharon Strelitz
    @version 1.0 01/21/2018
*/
#include <iostream>
using namespace std;

int main() {
    cout << "Enter a word: ";
    string msg;
    cin >> msg;
    for (unsigned int i = 0; i < msg.length(); i++) {
        cout << i << ": " << msg[i] << endl;
    }  //note the last index is msg.length() - 1
    return 0;
}

Using getline() to read text with spaces from the user (6.1.4)

#include <iostream>
using namespace std;

int main() {
    cout << "Enter your age: ";
    int age;
    cin >> age;
    cout << "Enter your full name: ";
    string name;
    cin >> ws; /* clear whitespace from buffer, avoids
                  problems when you mix cin and getline*/
    getline(cin, name);
    cout << "Your age: " << age << endl
         << "Your full name: " << name << endl;
}


Arrays (6.2)

/*
    CS-11 Ex 6.2 myarrays.cpp
    Purpose: sum the values in an array

    @author Sharon Strelitz
    @version 1.0 01/21/2018
*/
#include <iostream>
using namespace std;

int main() {
    const int LENGTH = 5;
    double temp[] = {2.5, 305, 1.0, -43, 1000};
    double total = 0.0;
    cout << temp[0] << endl;
    for (int i = 0; i < LENGTH; i++)  {
        cout << temp[i] << endl;
        total += temp[i];
        
    }
    cout << "total is " << total << endl;
    return 0;
}

Random Numbers (7.1)

#include <iostream>
using namespace std;

int main() {
    const int NUM_ROLLS = 10;
    srand(time(0));
    for (int i = 0; i < NUM_ROLLS; i++) {
        int die1 = rand() % 6 + 1;
        int die2 = rand() % 6 + 1;
        cout << "You rolled a " << die1
             << " and a " << die2 << endl;
    }
    return 0;
}

Functions with an Array Parameter (8.1.4)

/**
    CS-11 Asn 7, toys.cpp
    Purpose: Calculates the most individual toys we can buy
             from a list of prices without duplicating any toy 
             and without going over budget

    @author  Sharon Strelitz
    @version 1.0  01/21/2018
 */
#include <iostream>
#include <iomanip>
using namespace std;

/**
    function toycount:  counts the number of toys that we can buy for a
    given amount of money

    @param budget the amount of money we have to spend
    @param priceArray an array of toy prices
    @param arraySize size of the priceArray
    @return the number of toys we can buy
*/
int toycount(double budget, const double priceArray[], const int arraySize); //function prototype


int main() {
    const int PRICE_ARRAY_SIZE = 8;
    const double toyPrices[] = {1.99, 2.49, 3.98, 4.99, 5.49, 6.98, 7.99, 10.75};
    double budget = 0.0;
    bool done = false;
    cout << "** Toy Maximizer!** " << endl << endl;
    while (!done)  {
        cout << "Enter the amount of money to spend (0 to stop): ";
        cin >> budget;
        if (budget > 0.0) {
            toycount(budget, toyPrices, PRICE_ARRAY_SIZE);
        }  else  {
            done = true;
        }
    }
    cout << "You're the best!" << endl;
    return 0;
}

int toycount(double budget, const double priceArray[], const int arraySize)  {
    int count = 0;
    double moneyLeft = budget;
    for (int i = 0; i < arraySize; i++)  {
        if (priceArray[i] <= moneyLeft) {
            count++;
            moneyLeft -= priceArray[i];
        }       
    }
    cout << "Number of toys: " << count << endl;
    cout << fixed << setprecision(2);
    cout << "Money remaining: " << moneyLeft << endl;
     
    return count;
}









Reference Parameters (8.3)

#include <iostream>
using namespace std;

void swap(int& var1, int& var2);

int main() {
    int num1 = 0, num2 = 0;
    cout << "Enter two integers: ";
    cin >> num1 >> num2;

    swap(num1, num2);

    cout << "After calling function:  "
         << num1 << " " << num2 << endl;
    return 0;
}

void swap(int& var1, int& var2) {
    int temp = var1;
    var1 = var2;
    var2 = temp;
}

Pointer Parameters (8c slides)

#include <iostream>
using namespace std;

void swap(int* var1, int* var2);

int main() {
    int num1 = 0, num2 = 0;
    cout << "Enter two integers: ";
    cin >> num1 >> num2;

    swap(&num1, &num2);

    cout << "After calling function:  "
         << num1 << " " << num2 << endl;
    return 0;
}

void swap(int* var1, int* var2) {
    int temp = *var1;
    *var1 = *var2;
    *var2 = temp;
}

Classes basic (Lesson 9a slides) 

#include <iostream>
using namespace std;

// Code below is the class declaration
class Student {
   public:
      Student(string name, int ID,
              string hobby); //Constructor
   private:
      string _name;
      int _ID;
      string _hobby;
};

//Code below is the definition of the method function prototypes in class declaration above
Student::Student(string name, int ID, string hobby) {
    _name = name;
    _ID = ID;
    _hobby = hobby;
}


int main() {
    //The following statements are creating new instances/objects of class Student
    Student student1("Ennio", 98765, "C++");  //calls the constructor
    Student student2("Sharon", 12345, "Java");  //calls the constructor
}

Classes: multiple constructors, accessors, mutators (Lesson 9b slides)

/**
    CS-11 Ex 9.3, studentConst.cpp
    Purpose: Student class which stores information about a student

    @author Sharon Strelitz
    @version 1.0  12/07/2018
 */
#include <iostream>
using namespace std;

// Code below is the class declaration or INTERFACE
class Student {
  public:
    Student(string name, int ID,
            string hobby);  //3 parameter constructor
    Student();              //default constructor
    Student(string name, string hobby); //2 parameter constructor
    string getName() const;        //accessor
    void setName(string name);     //mutator
    string getHobby() const;       //accessor
    void setHobby(string hobby);   //mutator
    /**
      Method printStudent - prints name & hobby for the student

    @param no parameters
    @return void
    */
    void printStudent() const;
  private:
    string _name;
    int _ID; 
    string _hobby;
};

//Code below is the definition or IMPLEMENTATION of the function prototypes in class declaration above
Student::Student(string name, int ID, string hobby)  {  //3 parameter constructor
  _name = name;
  _ID = ID;
  _hobby = hobby;
}
Student::Student()  {  //default constructor has no parameters
  _name = "";
  _ID = 0;
  _hobby = "";
}
Student::Student(string name, string hobby)  {  //2 parameter constructor
  _name = name;
  _ID = 0;
  _hobby = hobby;
}
string Student::getName() const  {   //accessor
  return _name;
}
void Student::setName(string name)  {  //mutator
  _name = name;
}
string Student::getHobby() const  {    //accessor
  return _hobby;
}
void Student::setHobby(string hobby)  {   //mutator
  _hobby = hobby;
}

void Student::printStudent() const  {   
  cout << "name is " << getName() << " and hobby is " 
       << getHobby() << endl;
  /* notice that when you are inside a method and you call 
     another method, you do not need to use the object.getHobby()
     syntax,  simply call getName() and getHobby() as in the
     cout statement above */     
}

int main() {
    //The following statements are creating new instances/objects of class Student
    Student student3("Ennio",  98765, "C++");  //call 3 parameter constructor
    Student student4("Sharon",  12345, "Python"); //call 3 parameter constructor
    Student student5("Maria",  "studying");   //call 2 parameter constructor
    Student student6;   //call the default constructor with no parentheses!!
    Student student7("Kentaro", "Java");  //call 2 parameter constructor     
    
    //The following statements are using mutators
    student3.setName("Tom");
    student4.setHobby("Java");
    
    /*The following statements are using the printStudent method and 
      the printStudent method calls accessors getName() and getHobby()  */
    cout << "Student 3's ";
    student3.printStudent(); 
    cout << "Student 4's ";
    student4.printStudent();
    cout << "Student 5's ";
    student5.printStudent();
    cout << "Student 6's ";
    student6.printStudent();
    cout << "Student 7's ";
    student7.printStudent();
}

Vectors: basic (10.2.3)

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores(10); //declare a vector of 10 integers named scores

    cout << "Enter 10 scores:\n";
    for (int i = 0; i < 10; i++) {
        cin >> scores[i];  //get user input and put into vector scores
    }

    cout << "You entered:\n";
    for (int i = 0; i < 10; i++) {
        cout << scores[i] << endl; //print out each item in vector scores
    }

    return 0;
}

Vectors: vector parameters and return types (10.2.5)

Computing Test Statistics
#include <iostream>
#include <vector>
using namespace std;

/**
    Returns a vector containing deviations from the mean.

    @param v The values to compare to the average.
    @param avg The average mean value.
    @return A vector containing deviations from avg.
*/
vector<double> diffs(const vector<int>& v, double avg) {
    vector<double> diff(v.size());
    for (unsigned i = 0; i < v.size(); i++) {
        diff[i] = v[i] - avg;
    }
    return diff;
}

int main() {
    vector<int> scores;  //declare a vector of integers named scores

    cout << "Enter scores (x to exit):\n";
    int data = 0;
    while (cin >> data) {
        scores.push_back(data); //put user data into vector scores
    }

    if (scores.size() <= 0) {
        cout << "No data!\n";
        return -1;
    }

    int highest = scores[0];
    int lowest = scores[0];
    int sum = 0;
    for (unsigned i = 0; i < scores.size(); i++) {
        sum = sum + scores[i];
        if (scores[i] > highest) {
            highest = scores[i];   //find highest score
        }
        if (scores[i] < lowest) {
            lowest = scores[i];   //find lowest score
        }
    }
    double average = 1.0 * sum / scores.size(); //calculate average

    cout << "Highest score: " << highest << endl;
    cout << "Lowest score: " << lowest << endl;
    cout << "Average score: " << average << endl;
    cout << "Score differences:\n";
    vector<double> diff = diffs(scores, average); //call diffs & assign results to new vector diff
    for (unsigned i = 0; i < diff.size(); i++) {
        cout << scores[i]
             << " differs from the mean by "
             << diff[i] << endl;
    }

    return 0;
}

Vectors of Objects, non-member functions  (10.4)

/**
    CS-11 Ex 10.4, prodvector.cpp
    Purpose: Explore how to add items to and list items of a vector of objects

    @author Sharon Strelitz
    @version 1.0  12/07/2018
 */
#include <iostream>
#include <vector>
using namespace std;

class Product {
public:
    Product();                       
    Product(string newName, double newPrice);
    void read();
    void print() const;
private:
    string name;
    double price;
};

Product::Product() {
    name = "Unknown";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::read() {
    cout << "Enter the name of the product: ";
    cin >> ws;
    getline(cin, name);
    cout << "Enter the price for a " << name << ": ";
    cin >> price;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

// Add a new product to the store
void addProduct(vector<Product>& store);   //non-member function prototype

// List the products in the store
void listProducts(vector<Product>& store);  //non-member function prototype

int main() {
    const int SIZE = 3; 
    vector<Product> myStore(SIZE);       //vector of Product objects
    myStore[0] = Product("Milk", 3.95);
    myStore[1] = Product("Bread", 2.99);
    myStore[2] = Product("Cheese", 3.95);

    int choice = 1;
    while (choice != 0) {
        cout << "\n0. Exit program\n"
             << "1. Report inventory\n"
             << "2. Add a new product\n"
             << "Choice (0-2): ";
        cin >> choice;
        if (choice == 1) {
            listProducts(myStore);    //call a non-member function
        } else if (choice == 2) {
            addProduct(myStore);      //call a non-member function
        } else if (choice != 0) {
            cout << "\nInvalid choice!\n";
        }
    }
    cout << "\nGoodbye!\n";
    return 0;
}

void addProduct(vector<Product>& store) {   //a non-member function
    cout << "\nAdding a new product:\n";
    Product prod;
    prod.read();                        //call Product member function read()
    store.push_back(prod);
}

void listProducts(vector<Product>& store) {   //a non-member function
    cout << "\nListing products:\n";
    for (unsigned num = 0; num < store.size(); num++) {
        cout << (num + 1) << " ";
        store[num].print();       //call Product member function print()
    }
}

Vector of Cats with printOldest (11.1)

#include <iostream>
#include <vector>
using namespace std;

class Cat {
   public:
      Cat(string name, int age);
      Cat();
      string getName() const;        //accessor
      void setName(string name);     //mutator
      int getAge() const;       //accessor
      void setAge(int age);   //mutator
      /**
      Method printCat - prints name & age for the cat
      @param no parameters
      @return void
      */
     void printCat() const;
   private:
      string _name;
      int _age; 
};

//Code below is the definition of the method function prototypes in class declaration above
Cat::Cat(string name, int age) {
    _name = name;
    _age = age;
}

Cat::Cat() {
    _name = "no name yet";
    _age = 0;
}

string Cat::getName() const  {   //accessor
  return _name;
}
void Cat::setName(string name)  {  //mutator
  _name = name;
}
int Cat::getAge() const  {    //accessor
  return _age;
}
void Cat::setAge(int age)  {   //mutator
  _age = age;
}

void Cat::printCat() const  {   
  cout << "name is " << getName() << " and age is " 
       << getAge() << endl;  
}
void printOldest(const vector<Cat>& cats);
int main() {
    cout << "CATS!" << endl;
    vector<Cat> cats(3);
    cats[0] = Cat("Fluffy", 7);
    cats[1] = Cat("Garfield", 5);
    cats[2] = Cat("Kitty", 3);

    // Uncomment after defining printOldest()
    printOldest(cats);
    return 0;
}
void printOldest(const vector<Cat>& cats)  {
    int maxAgeIndex = -1;
    int maxAge = -1;
    for (int i = 0; i < (int) cats.size(); i++)  {
        if (cats[i].getAge() > maxAge)  {
            maxAgeIndex = i;
            maxAge = cats[i].getAge();
        }
    }
    if (maxAgeIndex != -1)  {
        cout << "Oldest cat is " << cats[maxAgeIndex].getName()
             << " at " << cats[maxAgeIndex].getAge() 
             << " years. " << endl;
    }
}

Simple I/O Read/Write with Files (12.2.4)

#include <iostream>
#include <fstream>  // for file I/O
#include <cstdlib>  // for exit()
using namespace std;

/**
    Reads a line from the istream.

    @param aStream the output stream.
    @return The line of text read.
*/
string readLine(ifstream& aStream) {
    string line;
    getline(aStream, line);
    return line;
}

/**
    Writes a line to the ostream.

    @param aStream the output stream.
    @param line The string to output.
*/
void writeLine(ofstream& aStream, string line) {
    aStream << line << endl;
}

int main() {
    ifstream fin("infile.txt");
    if (fin.fail()) {
        cout << "Input file opening failed.\n";
        exit(-1);
    }

    ofstream fout("outfile.txt");
    if (fout.fail()) {
        cout << "Output file opening failed.\n";
        exit(-1);
    }

    while (fin.good()) {
        string line = readLine(fin);
        if (fin.good()) {
            writeLine(fout, line);
        }
    }

    fin.close();
    fout.close();
    cout << "Done copying file...\n";

    return 0;
}

I/O Read/Write with Files and Vector of Objects (12.3)

/**
    CS-11 Ex 12.3 productfile.cpp
    Purpose: 1)  Read product name+price from a file into a vector
             2)  Print the product info from the vector
             3)  Write the product info from the vector to a file

    @author Sharon Strelitz
    @version 1.0  12/07/2018
 */
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
using namespace std;

class Product {
public:
    Product();
    Product(string newName, double newPrice);
    void print() const;
    void read(ifstream& fin);
    void write(ofstream& fout);
private:
    string name;
    double price;
};

Product::Product() {
    name = "none";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}
void Product::read(ifstream& fin) {
    fin >> ws;
    getline(fin, name);
    fin >> price;
}

void Product::write(ofstream& fout){
    fout << name << endl;
    fout << price << endl;
}

// Read product data from a file.
void readFile(vector<Product>& list, string filename);

// List the products in the store.
void listProducts(const vector<Product>& store);

// Write vector of objects to the file.
void writeFile(vector<Product>& store, string fileName);

int main() {
    vector<Product> list;
    int choice;
    do { // simple menu
        cout << "\nSelect an option:\n";
        cout << "0. Exit program.\n";
        cout << "1. Load data from file.\n";
        cout << "2. Print data in vector.\n";
        cout << "3. Write data to a file.\n";
        cout << "Choice: ";
        cin >> choice;
        if (choice == 1) {
            readFile(list, "products2.txt");
        } else if (choice == 2) {
            listProducts(list);
        } else if (choice == 3) {
            writeFile(list, "saved.txt");  /*often you will write out to the same file that you read from,  
                                             but it's a good idea to write to a different file while debugging*/
        } else if (choice != 0) {
            cout << "Please enter a number from 0 - 3.\n";
        }
    } while (choice != 0);
    cout << "Goodbye.\n";

    return 0;
}

void listProducts(const vector<Product>& list) {
    for (unsigned i = 0; i < list.size(); i++) {
        Product temp = list[i];
        temp.print();
    }
}

void readFile(vector<Product>& list, string filename){
    ifstream fin(filename);
    if (fin.fail()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }
    while(fin.good())  {
        Product temp;
        temp.read(fin);
        if (fin.good())  {
            list.push_back(temp);  /*creates a COPY of temp and pushes it onto the back of vector list*/
        }  
    }
    fin.close();
}

void writeFile(vector<Product>& store, string fileName) {
    ofstream fout(fileName);
    if (fout.fail()) {
            cout << "Input file failed to open.\n";
        exit(-1);
    }
    fout << fixed << setprecision(2); // two decimal places
    for (int i = 0; i < (int) store.size(); i++)  {
      store[i].write(fout);  
    }
    fout.close();    
}

Recursive Wash (14.3.2) 

#include <iostream>
using namespace std;

void wash(int count);

int main() {
    int count;
    cout << "How many dishes to wash? ";
    cin >> count;
    wash(count);
}

void wash(int count) {
    if (count == 0) { // stopping condition
        cout << "Done washing dishes\n";
        return;
    }
    cout << count << " dishes to wash." << endl;
    wash(count - 1); // recursive step
    cout << "Washed " << count << " dishes so far." << endl;
    return; // optional for void functions
}

Recursive Exponentiation (14.3) recursive function returns a value

#include <iostream>
using namespace std;

int power(int x, int y);

int main() {
    int x = 0, y = 0;
    cout << "Enter the base: ";
    cin >> x;
    cout << "Enter the exponent: ";
    cin >> y;
    cout << x << "^" << y << " = " << power(x, y) << endl;
    return 0;
}

int power(int x, int y) {
    if (y == 0)
    {
        return 1;
    }
    else
    {
        y = y - 1;
        long result = power(x, y);
        result = result * x;
        return result;
    }
    return 0;
}

Comments