Ben Ben - 2 months ago 9
C++ Question

For loop not running under a void - fight scenario

I'm new to C++ and I am having some trouble with an assignment. Here is my program so far:

#include "stdafx.h"

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

void fight(string heroName, int arrowCount, int enemyCount);
int main(int argc, char** argv) {

string heroName = "Legolas";
int arrowCount = 3;
int enemyCount = 3;

cout << "Welcome to the Arena, the battle will begin shortly." << endl;
system("pause");
cout << "\nToday's competitors: " << "\n" << heroName << "\n" << "3 Orcs" << endl;

system("pause");

cout << "\n" << heroName << " will be given 3 arrows" << "\n" << "3 Orcs will be given daggers. \n";

system("pause");

cout << "\nThe battle begins in...\n 3...\n 2...\n 1..." << endl;

system("pause");

fight(heroName, arrowCount, enemyCount);
}

void fight(string heroName, int arrowCount, int enemyCount) {

for (int x = arrowCount; x <= 0; x--) {

if (arrowCount == 3) {
cout << "\n" << heroName << " fires arrow at Azog." << "\nAzog has fallen due to lobotomy by arrow." << "\nLegolas notices he has 2 arrows remaining." << endl;
system("pause");
}

if (arrowCount == 2) {
cout << "\n" << heroName << " fires arrow at Dular." << "\nDular has taken an arrow to the knee and is now longer an adventurer." << "\nLegolas notices he has 1 arrow remaining." << endl;
system("pause");
}

if (arrowCount == 1) {
cout << "\n" << heroName << " fires arrow at Nagrub." << "\nNagrub has lost his testicles." << "\nLegolas notices he is out of Arrows." << endl;
system("pause");
}
}
}


The issue that I'm having is it seems that the for loop isn't initializing. Everything runs fine up to the "void fight" part of the program. How can I correct this?

Answer

Did you mean for (int x = arrowCount; x >= 0; x--) {? Note that the for loop conditional check is evaluated before the loop body is ran.

Currently your loop will terminate if x is positive, which judging from your variable name, is most likely to be the case.

Also note that the body of the for loop depends on neither x, nor enemyCount, which seems odd.

Comments