I am writing a program that will tally votes from each counties up to 4 for two candidates. Basically it will ask you to add the votes in each counties for each candidate. Then it will tally the votes and display the winner. This mostly works but It won't add up the votes and declare the winner correctly? I suspect it is something wrong with the loop at line 37 to line 40.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[7];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}
Let me know if there is any other revision that I should do!
Thanks!
Your votes array is short.
It seems you have 4x2 entries, but the array is only 7 elements.
Here's a version that I could live with:
Live On Coliru
#include <iostream>
#include <numeric>
using namespace std;
int tier1();
int main(void) {
return tier1();
}
static int getnumber(std::string prompt) {
if (!std::cin)
return 0;
int i;
std::cout << prompt;
std::cin >> i;
while(!std::cin) {
if (std::cin.eof()) {
exit(1);
}
std::cin.clear();
std::cin.ignore(1<<30, '\n');
std::cout << prompt;
std::cin >> i;
}
return i;
}
#include <map>
#include <algorithm>
int tier1() {
using namespace std;
using county = int;
static constexpr int number_of_counties = 4;
static constexpr int number_of_candidates = 2;
map<county, size_t[number_of_candidates]> votes;
for (int cty = 0; cty < number_of_counties; cty++) {
for (int cand = 0; cand < number_of_candidates; cand++) {
votes[cty][cand] = getnumber("How many votes did the candidate " + to_string(cand) + " get in county " + to_string(cty) + "? ");
}
if (std::accumulate(begin(votes[cty]), end(votes[cty]), 0u) > 100)
cout << "County has too many votes. Exiting!\n"; // Print an error
}
size_t totals[number_of_candidates] = { 0 };
for(auto& cty: votes) {
for (auto in = begin(cty.second), accum = begin(totals); accum < end(totals);) {
*accum++ += *in++;
}
}
auto winner = max_element(begin(totals), end(totals));
cout << "The winner of the election is candidate " << distance(totals, winner) << "\n";
cout << "Here is the voting results:\n";
for (int cand = 0; cand < number_of_candidates; cand++) {
cout << "candidate " << cand << " got " << totals[cand] << " votes\n";
}
return 0;
}
In addition to sehe's observation, I also see you have the following:
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
This should probably be (after you make your array size 8):
// Loop through all countries
for (i = 0; i < 8; i = i + 2)
{
// Print out the candidate's votes per country
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
Here is an improved suggestion which structures the code in a way that makes more sense (altough my original suggestion is probably easier):
You could use a two dimensional array as follows:
int votes[2][4]; //Store the votes in the format [candidate 0 or 1][country 0 to 3]
The loop in question would then become:
// Loop through all countries
for (i = 0; i < 4; i++)
{
// Print out the candidate's votes per country
cout << votes[0][i] << "\n";
cout << votes[1][i] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[0][i];
candidate1Votes += votes[1][i];
}
The rest of the code would need to be modified to adapt to that structure as well. Since this could be a bit confusing, I left it as a separate answer. It is probably a bit better way to structure the program, but my original answer should fix the problem.
I think this is what you want. The array size was changed to 8, and the for loop in line 37 to 40 was also modified.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[8];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 8; i+=2)
{
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}
Related
I'm new to programming is there a way to solve this:
Take 10 integer inputs from user and print the following
number of positive numbers.
number of negative numbers.
number of odd numbers.
number of even numbers
#include <iostream>
using namespace std;
int main()
{
int numArray[10];
cout<<"Enter Number :";
for(int i=0; i<10; i++)
{
cin>>numArray[i];
}
for(int i=0; i<numArray[i]; i++)
{
if(numArray[i]>0)
{
cout<<"Positive Number "<<numArray[i] <<endl;
}
else
{
cout<<"Negative Number "<<numArray[i]<<endl;
}
if(numArray[i]%2==0)
{
cout<<"Odd number "<<numArray[i]<<endl;
}
else
{
cout<<"even number "<<numArray[i]<<endl;
}
}
return 0;
}
You could do this without arrays but I'm just gonna stick with your original intent for clarity.
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> numArray; //an array of ints, size 10. this is CPP style array, it is 'safer' than C-style array. (someone correct me)
//get your 10 inputs.
cout << "Enter Number :";
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
}
int positive_count = 0;
int negative_count = 0;
int even_count = 0;
int odd_count = 0;
//loop thru your 10 inputs, increment counters accordingly.
for(size_t i = 0; i < numArray.size(); i++)
{
if (numArray[i] < 0)
{
negative_count += 1;
}
if (numArray[i] > 0)
{
positive_count += 1;
}
if (numArray[i] % 2 == 0)
{
even_count += 1;
}
else
{
odd_count += 1;
}
}
cout << "Positive Number " << positive_count << endl;
cout << "Negative Number " << negative_count << endl;
cout << "even number " << even_count << endl;
cout << "Odd number " << odd_count << endl;
return 0;
}
You could do it in input loop:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
odds += numArray[i] & 0x1;
// odds += numArray[i] % 2;
// increment number of positives
positives += (numArray[i] > 0);
// positives += (numArray[i] > 0 ? 1 : 0);
// increment zeros
zeros += !(numArray[i] | 0);
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positive count " << positives << endl;
cout << "Negative Number " << negatives << endl;
cout << "Even number " << evens << endl;
cout << "Odd number " << odds << endl;
and here is newbie friendly version:
int positives = 0, zeros = 0, odds = 0;
int negatives = 0, evens = 0;
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
// increment number of odds
if (numArray[i] % 2 == 1)
odds++;
if (numArra[i] == 0)
zeros++;
else if (numArray[i] > 0)
positives++;
}
evens = 10 - odds;
negatives = 10 - zeros - positives;
cout << "Positives " << positives << '\n';
cout << "Negatives " << negatives << '\n';
cout << "Evens " << evens << '\n';
cout << "Odds " << odds << '\n';
Currently I have a pre-made 6X6 matrix in a text file like this:
2 6 3 1 0 4
4 2 7 7 2 8
4 7 3 2 5 1
7 6 5 1 1 0
8 4 6 0 0 6
1 3 1 8 3 8
and I made a code that is reading from a file i have made. However I want to have user make a grid for themselves (i.e. 3X3 or 10X10). Which then writes to a text file automatically like in similar fashion and then have that read-in instead. It is a basic memory match card game, so I need to have rand() which generates equal pair so the game can be over when every pair in the grid has been found. Thank you so much for your time!
/*Here are the snippets of my code*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <string>
#include <numeric>
#include <limits>
using namespace std;
//global 2d vectors that are associated with the game
vector<vector<int> > game_grid;
vector<vector<int> > hidden_grid;
vector <vector<int> > guessed;
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
for (int i = 0; i < 6; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < 6; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
return;
}
void print_grid() {
cout << "Game grid" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
cout << game_grid[i][j] << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
}
void print_hidden_grid(int r1 = -1, int r2 = -1, int c1 = -1, int c2 = -1) {
cout << "Attempt:" << endl;
if (r1 != -1) {
hidden_grid[r1][c1] = game_grid[r1][c1];
}
if (r2 != -1) {
hidden_grid[r2][c2] = game_grid[r2][c2];
}
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
if (r1 != -1) {
if (game_grid[r1][c1] == game_grid[r2][c2]) {
guessed[r1][c1] = 1;
guessed[r2][c2] = 1;
cout << "You have a match!" << endl << endl;
}
else {
hidden_grid[r1][c1] = -1;
hidden_grid[r2][c2] = -1;
}
}
cout << endl << endl;
}
void print_current_grid() {
cout << "Current Grid:" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl << endl;
}
.......
If I well understand you want to auto detect the size of the matrix when you read it ? If yes you can do something like that in initialize_grid :
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
// detect size
int size = 0;
string line;
if (!getline(input_file, line))
return;
istringstream iss(line);
while (iss >> num)
size += 1;
input_file.clear();
input_file.seekg(0);
for (int i = 0; i < size; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < size; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
}
and else where you replace 6 by game_grid.size() (using size_t rather than int to type the indexes)
This is a problem given to me by my computer mentor and I am trying to explain the problem in simple words(I must remind you that my mentor has only taught me loops array structure. I cannot use class for this problem)
Take two matrix
Print the name of n students in one matrix
Print the id, marks in 5 subject of the students in another 2d
matrix (n*6)
Find the student who got the highest in the total of 5 subject and
print the student name with marks of each subject and his total
marks.(i think we have to us a structure)
For example: The highest marks is secured by :
Name;
id no;
marks in sub 1;
marks in sub 2;
marks in sub 3;
marks in sub 4;
marks in sub 5;
total;
Then print the id and the name of the student who got highest in
each subject
For example:
Subject 1 ID name
Subject 2 ID name .....
I have being able to solve it fully till point (3). but unable to print the person who got the highest in each subject ; and I am facing problem to print the person who got highest in each subject as I have to use many variables(I'm not using structure)
What I have tried so far:
#include <iostream>
using namespace std;
int main()
{
//making 1st array to print the names of the students
char x[500][1000];
int num, i;
cout << "Enter the number of student's data you want to input" << endl;
cin >> num;
cout << endl;
cout << "NAME LIST" << endl;
cout << endl;
for(i = 0; i < num + 1; i++)
{
cin.getline(x[i], 1000);
}
//making a 2nd array to print the id, marks in 5 subjects of the students
int y[num][6];
int a, b;
cout << endl;
cout << endl;
cout << "DETAILS OF THE STUDENT" << endl;
cout << endl;
for(int a = 0; a < num; a++)
{
cout << "ID no of student " << a + 1 << ":";
cin >> y[a][0];
cout << "Marks in subject 1:";
cin >> y[a][1];
cout << "Marks in subject 2:";
cin >> y[a][2];
cout << "Marks in subject 3:";
cin >> y[a][3];
cout << "Marks in subject 4:";
cin >> y[a][4];
cout << "Marks in subject 5:";
cin >> y[a][5];
cout << endl;
}
cout << endl;
cout << "The data you inputed:";
cout << endl;
for(a = 0; a < num; a++)
{
for(b = 0; b < 6; b++)
{
cout << y[a][b] << " ";
}
cout << endl;
}
cout << endl;
cout << endl;
//finding the member who got the highest marks
int s = 0;
int largestSum = 0;
for(a = 0; a < num; i++)
{
for(b = 0; b<6; b++)
{
s += y[a][b];
}
// check to see if we have computed a new larger sum and save it if we have.
if(s > largestSum)
{
largestSum = s;
}
}
cout << "largest sum: " << largestSum << endl;
return 0;
}
int s = 0; <- s needs to be reset to zero in each loop
int largestSum = 0;
for(a = 0; a<num; i++) <- loop doesn't break
{
for(b = 0; b<6; b++) <- b should start at 1
{
s += y[a][b];
}
if(s > largestSum)
{
largestSum = s;
}
}
i is incremented while a remains constant and the loop goes forever.
s is not reset to zero, so you sum all the values.
The first index at b = 0 is supposed to be student id, it should be skipped. Try instead:
int largestSum = 0;
for(a = 0; a < num; a++)
{
int s = 0;
for(b = 1; b < 6; b++)
s += y[a][b];
if(s > largestSum)
largestSum = s;
}
Here's something to go off of.
Note that I only made one matrix and put the Student objects in it.
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
const std::vector<std::vector<std::string>> names = {
{"Ralph", "Gerald", "Henry", "Jessica", "Bob"},
{"Tara", "Tami", "Mike", "Loretta", "Jean"},
{"Jesse", "John", "Carl", "Josh", "Abby"},
{"Carson", "Don", "George", "Hillary", "David"},
{"Micah", "Charlie", "Maximus", "Leonidas", "Xerxes"}
};
int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int)seconds);
struct Subjects
{
unsigned int subject[5] = {};
};
struct Student
{
Subjects sub;
std::string name;
int id;
Student() : name("nobody"), id(-1) {};
Student(const std::string& name, const unsigned int& id) : name(name), id(id) {}
};
Student stud_matrix[5][5] = {};
int count = 0;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].name = names[i][j];
stud_matrix[i][j].id = count;
++count;
}
}
std::cout << "All student names:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].name << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "All student IDs:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].id << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].sub.subject[0] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[1] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[2] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[3] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[4] = (rand() % 100 + 1);
}
}
Student best_student;
unsigned int highest_grade = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[0];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[1];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[2];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[3];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[4];
best_student = stud_matrix[i][j];
}
}
}
std::cout << "The highest scoring student in any one subject is: " << best_student.name << std::endl;
std::cout << "ID: " << best_student.id << std::endl;
std::cout << "Marks in sub1: " << best_student.sub.subject[0] << std::endl;
std::cout << "Marks in sub2: " << best_student.sub.subject[1] << std::endl;
std::cout << "Marks in sub3: " << best_student.sub.subject[2] << std::endl;
std::cout << "Marks in sub4: " << best_student.sub.subject[3] << std::endl;
std::cout << "Marks in sub5: " << best_student.sub.subject[4] << std::endl;
std::cout << "Total: " << best_student.sub.subject[0] + best_student.sub.subject[1] + best_student.sub.subject[2] +
best_student.sub.subject[3] + best_student.sub.subject[4] << std::endl;
std::cout << std::endl;
Student stud_sub1;
Student stud_sub2;
Student stud_sub3;
Student stud_sub4;
Student stud_sub5;
unsigned int high_sub1 = {};
unsigned int high_sub2 = {};
unsigned int high_sub3 = {};
unsigned int high_sub4 = {};
unsigned int high_sub5 = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > high_sub1)
{
high_sub1 = stud_matrix[i][j].sub.subject[0];
stud_sub1 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > high_sub2)
{
high_sub2 = stud_matrix[i][j].sub.subject[1];
stud_sub2 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > high_sub3)
{
high_sub3 = stud_matrix[i][j].sub.subject[2];
stud_sub3 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > high_sub4)
{
high_sub4 = stud_matrix[i][j].sub.subject[3];
stud_sub4 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > high_sub5)
{
high_sub5 = stud_matrix[i][j].sub.subject[4];
stud_sub5 = stud_matrix[i][j];
}
}
}
std::cout << "Best of subject:\n";
std::cout << "Subject 1:\nID: " << stud_sub1.id << ' ' << stud_sub1.name << " Score: " << high_sub1 << std::endl;
std::cout << "Subject 2:\nID: " << stud_sub2.id << ' ' << stud_sub2.name << " Score: " << high_sub2 << std::endl;
std::cout << "Subject 3:\nID: " << stud_sub3.id << ' ' << stud_sub3.name << " Score: " << high_sub3 << std::endl;
std::cout << "Subject 4:\nID: " << stud_sub4.id << ' ' << stud_sub4.name << " Score: " << high_sub4 << std::endl;
std::cout << "Subject 5:\nID: " << stud_sub5.id << ' ' << stud_sub5.name << " Score: " << high_sub5 << std::endl;
system("pause");
return 0;
}
Sample Output:
All student names:
Ralph Gerald Henry Jessica Bob
Tara Tami Mike Loretta Jean
Jesse John Carl Josh Abby
Carson Don George Hillary David
Micah Charlie Maximus Leonidas Xerxes
All student IDs:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The highest scoring student in any one subject is: Bob
ID: 4
Marks in sub1: 77
Marks in sub2: 67
Marks in sub3: 7
Marks in sub4: 99
Marks in sub5: 66
Total: 316
Best of subject:
Subject 1:
ID: 23 Leonidas Score: 95
Subject 2:
ID: 18 Hillary Score: 92
Subject 3:
ID: 19 David Score: 98
Subject 4:
ID: 4 Bob Score: 99
Subject 5:
ID: 22 Maximus Score: 98
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'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}