I was just wondering why playerHp doesn't stay at it's value but resets to 30 each time I call the function. Is it because the variable is local, and if so how do I make it go global from within the function?
I'm new to programming so easy explanations would be nice.
I'm also aware this is "spaghetti code", but if you have the time and energy, cleaning it up would be much appreciated.
#include <iostream>
#include <string>
#include <cstdlib>
//RETURN CODES 1=WON 2=RAN AWAY 3=SLAIN 4=globalWin 5=GlobalLose
using namespace std;
int playerHp;
int enemyHp;
string enemyName;
int dmg()
{
int modifier = rand() % 10 ; // 0-9
return 15 + modifier;
}
int playerDmg()
{
int modifier1 = rand() % 10 ; // 0-9
return 15 + modifier1;
}
int enemyDmg()
{
int modifier2 = rand() % 10 ; // 0-9
return 10 + modifier2;
}
int fight(int playerHp, int enemyHp, string enemyName)
{
int constwhile = 1;
string input;
cout << "You encountered a ";
cout << enemyName <<"\n";
while (constwhile = 1) {
cout << "What will you do?\n";
cout << "Options Fight or Flee: " << flush;
cin >> input;
cin.ignore();
cin.get();
if (input == "Fight" || input == "fight") {
int damageDone = playerDmg();
int finalEnemyHp = enemyHp - damageDone;
cout << "You did ";
cout << damageDone;
cout << " damage" << "\n";
enemyHp = finalEnemyHp;
if (enemyHp < 0) {
cout << "Congratulations! You won!"<<"\n";
return 1;
}
cout << "The monster now has ";
cout << enemyHp;
cout << " health"<<"\n";
} else if (input == "Flee" || input == "flee") {
cout << "You ran away...";
return 2;
} else {
cout<<"Invalid Input"<<"\n";
}
cout << "The enemy fights back!"<< "\n";
int damageDone = enemyDmg();
int finalPlayerHp = playerHp - damageDone;
cout << "It did ";
cout << damageDone;
cout << " damage" << "\n";
playerHp = finalPlayerHp;
if (playerHp < 0) {
cout << "You have been slain...";
return 3;
}
cout << "You now have ";
cout << playerHp;
cout << " health"<<"\n";
}
}
int main()
{
int playerHp = 30;
while(playerHp > 1) {
int fightOutcome = fight(playerHp, rand() % 30, "monster");
if (fightOutcome == 3) {
return 5;
} else if (fightOutcome == 2) {
return 5;
}
}
return 4;
}
The problem are that your global variable are shadow by local defined on function
int fight(int playerHp, int enemyHp, string enemyName)
A fast way to fix your problem is to pass the variables as reference if you want yo keep the value assigned inside function fight
int fight(int &playerHp, int &enemyHp, string &enemyName)
If you want to use a global variable, there must be no local variable or parameter with the same name.
The following will always change the local variable:
int myVar = 0;
void foo(int myVar)
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//0
return 0;
}
Now you could either accept a pointer instead of a value, or you could remove the parameter entirely. But I don't really like global pollution, so I would prefer the pointer:
with pointer:
int myVar = 0;
void foo(int* myVar)
{
*myVar = 100;
}
int main()
{
foo(&myVar);
cout << myVar;//100
return 0;
}
without pointer:
int myVar = 0;
void foo()
{
myVar = 100;
}
int main()
{
foo(myVar);
cout << myVar;//100
return 0;
}
Related
I've been making my C++ text game. Gone fairly well so far. I had a few delays with some mistakes I have made. Got most of that fixed up. Now I am working on the level up and experience points system. And IDK how to keep that number updated so it's knowns that it reaches level 55. Here's the code:
(first program ever)
//#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string.h>
using namespace std;
bool gameRunning = true;
char Yarra = 'P';
char Dragon = 'D';
char map[28];
class Player;
class Enemy {
private:
int lvl;
public:
int health;
Enemy() {
int randomNumber = rand();
int enemy_life = (randomNumber % 7) + 2;
health = enemy_life;
lvl = 1;
}
void attack(Player& p);
friend class Player;
};
class Final_dragon {
public:
int lvl;
int health;
Final_dragon() {
health = 10;
lvl = 2;
}
void attack(Player& p);
friend class Player;
};
class Player {
private:
public:
int health;
int exp;
int lvl;
Player(bool hero) {
if(hero) {
health = 100;
lvl = 1;
exp = 0;
} else {
health = 1;
}
}
void attack(Enemy& e);
void lvlUp(Player& p);
friend class Enemy;
friend class Final_boss;
};
void Player::attack(Enemy& e) {
int randomNumber = rand();
int dmg = (randomNumber % 2) + 0;
cout << "\nYou've done " << dmg << " damage!" << endl;
e.health -= dmg;
}
void Enemy::attack(Player& p) {
// int randomNumber = rand();
// int dmg = (randomNumber % 20) + 0;
int dmg = 2;
cout << "\nThe Enemy does " << dmg << " damage to you!\n" << endl;
p.health -= dmg;
}
void Player::lvlUp(Player& p) {}
int main() {
int display;
char playerInput{};
char move;
char action;
map[0] = Yarra;
map[27] = Dragon;
cout << "Map: " << map[0];
for(display = 1; display < 27; display++) {
map[display] = '*';
cout << map[display];
}
cout << map[27];
cout << endl
<< endl
<< "Press '1' Travel to another space on the board \n"
<< "Press '2' Dismount and explore the current space " << endl;
display = 0; // Start at map[0]
while(gameRunning == true) {
Player p(true);
do {
cin >> move; // Get user input
if(move == '1') // If input is '1'
{
srand(time(0));
int dice = (int)(1 + rand() % 6);
cout << "You moved: " << dice << " steps" << endl;
map[display] = '*'; // Remove old location of player
display = display + dice; // Increase display location
map[display] = 'P'; // Insert player in new map array location
cout << "Your current location: " << display
<< endl; // Player current location
}
if(move == '2') // If input is '2'
{
cout << "Your current location: " << display
<< endl; // Player current location
srand(time(0));
int monster_dice = (int)(1 + rand() % 14); // Random monster
cout << "Monster location: " << monster_dice << endl
<< endl; // monster location
if(display == monster_dice) {
cout << "You've encountered a Enemy! Press \"a\" to attack"
<< endl
<< endl;
Enemy e;
cout << "HP of the monster you encounter: " << e.health << endl;
cin >> action;
if(action == 'a' || action == 'A') {
do {
p.attack(e);
cin.ignore(1);
if(p.health <= 0) {
system("CLS");
cout << "\t\n\nYou have died..." << endl;
cout << "\t\nGAME OVER!" << endl << endl;
return 0;
}
if(e.health >= 1) {
e.attack(p);
cin.ignore(1);
}
} while(e.health >= 0);
if(e.health <= 0) {
cout << "\n\nYou defeat the Enemy! *Vistory Music*\n"
<< endl;
cout << "You gained " << 100
<< " experience from the Boar." << endl;
p.exp += 100;
}
if(p.exp >= 200 && p.exp <= 300) {
cout << "\nYou've gone up to level 2!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 300 && p.exp <= 400) {
cout << "\nYou've gone up to level 3!" << endl;
p.lvl++;
p.health += 40;
}
if(p.exp >= 400 && p.exp <= 500) {
cout << "\nYou've gone up to level 4!" << endl;
p.lvl++;
p.health += 50;
}
if(p.exp >= 600 && p.exp <= 700) {
cout << "\nYou've gone up to level 5!" << endl;
p.lvl++;
p.health += 50;
}
}
}
}
} while(move != '1');
for(int x = 0; x <= 28; x++) {
cout << map[x];
}
if(display == 27 || display > 27) // If player at end of map array, end game
{
Final_dragon d;
if(p.lvl == 2) {
cout << "Ready for the fight" << endl;
} else {
system("CLS");
cout << "\nAlas, the dragons eyes stare at you and places you "
"under his spell. You try to move but fail to do so and "
"find yourself torched by the dragons fire.If only you had "
"more experience, you could have seen it coming."
<< endl;
cout << "\t\nGAME OVER!" << endl
<< endl; // Show text explaining why game ended
}
}
}
}
while(gameRunning == true) {
Player p(true);
You create a new hero player in each iteration. All experience and levels gained will be reset back to a newly created Player.
Create the Player before the loop:
Player p(true);
while(gameRunning == true) {
If you want the player to be able to fight the dragon if he/she is at least at the same level as the dragon, change the condition from if(p.lvl == 2) to if(p.lvl >= d.lvl).
You should seed the pseudo random number generator, i.e., call srand(), only once during the programs execution. Call it once when the program starts and never again.
If you are using C++11 or newer, you should use the <random> library instead of srand() and rand(). The same rule applies for those modern generators. Only seed them once.
A function to create a random number could look like this:
#include <random>
// A function to return a random number generator.
inline std::mt19937& generator() {
// the generator will only be seeded once since it's static
static std::mt19937 gen(std::random_device{}());
return gen;
}
// A function to generate int:s in the range [min, max]
int my_rand(int min, int max) {
std::uniform_int_distribution<int> dist(min, max);
return dist(generator());
}
I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:
I recently received an assignment to create a bowling program in C++ that simulates two people bowling and outputs the correct score for each frame. My program works by first generating all the throws for each frame and then accumulating the score afterwards in a separate method. I was able to get the program to work when the player bowls a non-perfect game and a perfect game, but I am having problems with when a player bowls all spares. I rigged the code to make it so I have 9 for a first throw and 1 for the second throw (this is in frame.cpp). The total should be 190, but I am getting 191 and I can't seem to find the error. Each bowling class contains an array of 11 frames. I know there are only 10 frames but this is to account for if the player gets a strike on the tenth frame. Any help would be appreciated, thanks.
Here is the frame. h file
#ifndef FRAME_H
#define FRAME_H
#include<iostream>
using namespace std;
class Frame
{
private: int throw1;
int throw2;
int score;
bool spare;
bool strike;
public: Frame();
int genThrow(int size);
int getFirstThrow();
int getSecondThrow();
int getScore();
void setScore(int);
void setFirstThrow(int value1);
void setSecondThrow(int value2);
void setStrike(bool value);
void setSpare(bool value);
bool getStrike();
bool getSpare();
};
#endif
Here is the frame.cpp file
#include "Frame.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
Frame::Frame()
{
spare = false;
strike = false;
throw1 = 0;
throw2 = 0;
score = 0;
}
//generates a random throw
int Frame::genThrow(int size)
{
int randomNumber = 0;
if (size < 10 || throw1 != 10)
{
randomNumber = 0 + rand() % (11 - throw1); //generate a number between 0 and 10
}
else
{
randomNumber = 0 + rand() % (11);
}
//cout << randomNumber << endl;
return randomNumber;
}
//get first throw
int Frame::getFirstThrow()
{
return throw1;
}
//get second throw
int Frame::getSecondThrow()
{
return throw2;
}
//get the score of both throws
int Frame::getScore()
{
return score;
}
//set the score
void Frame::setScore(int value)
{
score = value;
}
//set the first throw
void Frame::setFirstThrow(int value1)
{
//throw1 = genThrow(value1); //normal generator
//throw1 = 10; //strike game rigged
throw1 = 9; //spare game rigged
}
//set the second throw
void Frame::setSecondThrow(int value2)
{
//throw2 = genThrow(value2); //normal generator
throw2 = 1; //spare game rigged
//throw2 = 10; //strike game rigged
}
//set the strike
void Frame::setStrike(bool value)
{
strike = value;
}
//set the spare
void Frame::setSpare(bool value)
{
spare = value;
}
//get the strike
bool Frame::getStrike()
{
return strike;
}
//get the spare
bool Frame::getSpare()
{
return spare;
}
Here is the bowling.h file
#ifndef BOWLING_H
#define BOWLING_H
#include "Frame.h"
#include<iostream>
using namespace std;
class Bowling
{
private: Frame a[11];
public: void accumulateScore();
void bowl();
void printData();
};
#endif
Here is the bowling.cpp file
#include "Bowling.h"
#include<iostream>
using namespace std;
//takes all of the throw values after bowling and accumulates the correct score
void Bowling::accumulateScore()
{
int totalSum = 0;
for (int x = 0; x < 10; x++)
{
if (a[x].getFirstThrow() + a[x].getSecondThrow() < 10) //not a strike or spare
{
totalSum += a[x].getFirstThrow() + a[x].getSecondThrow();
a[x].setScore(totalSum);
}
else if (a[x].getFirstThrow() == 10) //throws a strike
{
if (x < 9)
{
totalSum += 10 + a[x + 1].getFirstThrow() + a[x + 1].getSecondThrow();
if (a[x + 2].getStrike() == true)
{
totalSum += 10;
}
a[x].setScore(totalSum);
}
}
else if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10) //throws a spare
{
if(x < 10)
{
totalSum += 10 + a[x + 1].getFirstThrow();
a[x].setScore(totalSum);
}
}
}
//player got the 11th frame
if (a[9].getStrike() == true)
{
totalSum += 10 + a[10].getFirstThrow() + a[10].getSecondThrow();
a[9].setScore(totalSum);
}
else if (a[9].getSpare() == true)
{
totalSum += 10;
a[9].setScore(totalSum);
}
}
void Bowling::bowl()
{
//generate all throws and store them in the frames
for (int x = 0; x < 10; x++)
{
a[x].setFirstThrow(x);
if (a[x].getFirstThrow() == 10)
{
a[x].setStrike(true);
}
if (a[x].getStrike() == false)
{
a[x].setSecondThrow(x);
if (a[x].getFirstThrow() + a[x].getSecondThrow() == 10)
{
a[x].setSpare(true);
}
}
a[x].setScore(a[x].getFirstThrow() + a[x].getSecondThrow());
}
//play the 11th frame if they got a strike on the tenth frame
if(a[9].getStrike() == true)
{
a[10].setFirstThrow(10);
if (a[10].getFirstThrow() == 10)
{
a[10].setStrike(true);
}
a[10].setSecondThrow(10);
cout << "The second throw is this value: " << a[10].getSecondThrow() << endl;
if (a[10].getSecondThrow() == 10)
{
a[10].setStrike(true);
}
else if (a[10].getFirstThrow() + a[10].getSecondThrow() == 10)
{
a[10].setSpare(true);
}
a[9].setScore(a[10].getFirstThrow() + a[10].getSecondThrow());
}
}
void Bowling::printData()
{
for (int x = 0; x < 10; x++)
{
cout << "*****************************" << endl;
cout << "Frame " << x + 1 << endl;
cout << "First throw: ";
if (a[x].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[x].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[x].getStrike() == false)
{
if (a[x].getSpare() == true)
{
cout << "Spare!" << endl;
}
else if(a[x].getSpare() == false)
{
cout << a[x].getSecondThrow() << endl;
}
else
{
cout << endl;
}
}
cout << "Score: " << a[x].getScore();
cout << endl;
}
if (a[9].getStrike() == true)
{
cout << "*****************" << endl;
cout << "Frame 11" << endl;
cout << "First throw: ";
if (a[10].getStrike() == true)
{
cout << "Strike!" << endl;
}
else
{
cout << a[10].getFirstThrow() << endl;
}
cout << "Second throw: ";
if (a[10].getStrike() == false)
{
if (a[10].getSpare() == true)
{
cout << "Spare!" << endl;
}
else
{
cout << a[10].getSecondThrow() << endl;
}
}
else
{
cout << "Strike!" << endl;
}
//cout << "Score: " << a[10].getScore();
cout << endl;
}
}
Here is where I test it in main
#include "Bowling.h"
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int dummy = 0;
//create two players that can bowl
Bowling player1;
Bowling player2;
int player1Score = 0;
int player2Score = 0;
//have the players bowl their throws before accumulating score
player1.bowl();
player2.bowl();
//accumulate the score after all of the throws have been done
player1.accumulateScore();
player2.accumulateScore();
//print player 1 data
cout << "Here are the throws and score for the first player: " << endl;
player1.printData();
//spacing
cout << endl << endl;
//print player 2 data
cout << "Here are the throws and score for the second player: " << endl;
player2.printData();
cout << "Enter a dummy number:" << endl;
cin >> dummy;
return 0;
}
Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}
i am relatively new to programming, i just learned c++ and i am getting 2 errors for a HW assignment from school;
Error 2 error C4700: uninitialized local variable 'searchValueptr' used Line 83
and
Error 3 error C4703: potentially uninitialized local pointer variable 'createdArray' used
Line 70
I cannot for the life of me figure out why or how to fix it can some one help me please.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// prototypes
int *createArray(int &size);
void findStats(int *arr, int size, int &min, int &max, double &average);
int *searchElement(int *arr, int size, int *element);
int main ()
{
int choice, size;
bool menuOn = true;
while (menuOn == true)
{
cout << "1 - Create and initialize a dynamic array.\n";
cout << "2 - Display statistics on the array.\n";
cout << "3 - Search for an element.\n";
cout << "4 - Exit.\n";
cout << "Enter your choice and press return: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
int *createdArray;
cout << "Please enter a size for the array: ";
cin >> size;
createdArray = createArray(size);
for (int x=0; x < size; x++)
{
cout << "Value of array at index " << x << ": " << createdArray[x] << endl;
}
cout << endl;
break;
case 2:
int minNum;
int maxNum;
double avgNum;
findStats(createdArray, size, minNum, maxNum, avgNum);
cout << endl << "The maximum number is: " << maxNum;
cout << endl << "The minimum number is: " << minNum;
cout << endl << "The average number is: " << avgNum;
cout << endl << endl;
break;
case 3:
int *searchValueptr;
int searchValue;
cout << "Enter a value to search for: ";
cin >> searchValue;
*searchValueptr = searchValue;
searchElement(createdArray, size, searchValueptr);
break;
case 4:
cout << "Thanks for using this program";
menuOn = false;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
cout << endl;
system("pause");
return 0;
} // end function main ()
int *createArray(int &size)
{
unsigned seed = time(0);
srand(seed);
int *randArray = new int [size];
for (int x=0; x < size; x++)
{
randArray[x] = rand();
}
cout << endl;
return randArray;
}
void findStats(int *arr, int size, int &min, int &max, double &average)
{
min = arr[0];
max = arr[0];
double sum = 0;
for (int count = 0; count < size; count++)
{
if (min >= arr[count])
{
min = arr[count];
}
if (max <= arr[count])
{
max = arr[count];
}
sum += arr[count];
}
average = sum/size;
}
int *searchElement(int *arr, int size, int *element)
{
bool match = false;
for (int count = 0; count < size; count++)
{
if (arr[count] == *element)
{
match = true;
}
}
if (match)
{
cout << "Match Found at: " << element;
return element;
}
else
{
cout << "No Found";
return 0;
}
}
either use
searchValueptr = &searchValue;
or send the pass the address of searchValue
searchElement(createdArray, size, &searchValue);
break;