I have a 2 part question. I am showing a user defined array. User input is # of rows, columns, and at what interval in the array to put a symbol.
I cannot get an output of the default symbol ****.
Where do I need to insert the interval input to adjust the array accordingly? Inside the function itself or define another function to do this?
I am looking for this result. Input = 1 (row), 4 (columns), 2 (interval). Output would be **?*.
Here is what I have so far.
#include <iostream>
using namespace std;
int rows = 0, columns = 0, interval = 0;
char symbol;
void Display(int rows = 0, int columns = 0, int interval = 0, char symbol = ('*'));
int main()
{
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> columns;
cout << "Enter the number of the question mark interval: ";
cin >> interval;
cout << "\n";
cout << "How many rows do you want? " << rows << "\n";
cout << "How many columns do you want? " << columns << "\n";
cout << "How far between question marks? " << interval << "\n";
Display(rows, columns, interval, symbol);
return 0;
}
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
cout << symbol;
}
cout << endl;
}
system("pause");
}
The problem is you never assigned * to symbol.
Change
char symbol;
to
char symbol = '*';
Did you know about the disadvantages of global variables. The sooner you learn about the cons the better. Here is a starting point.
Modify the Display function as below:
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
if ((x % (interval + 1)) == 0) //<--since you want after every intervals, just do a mod operation
cout << "?";
else
cout << symbol;
}
cout << endl;
}
system("pause");
}
Here is the working example.
Related
I am still a beginner in c++ programming and I have already tried searching, but another problem arises.
So I want the user to input the student's name and 4 quizScore. I want the names I inputted to be sorted alphabetically, and I still haven't solved that yet.
Furthermore, another problem arises: if I sort my variable names, the quiz score will not be sorted the way my name variables were arranged.
So basically, if I sort my variable name, I want the array quizeScores to be arranged in the same element as how the user inputted the data. I really need your help. I know my code is not the best and do love to have it revised. Thank you so much. Please help me...
#include <iostream>
#include <string>
using namespace std;
struct studen_grades {
string name;
int studentQuiz [1][4];
}records[5];
int main () {
double average = 0.0;
int x = 0, y = 0, recountFlag = 0, flag = 0;
bool repeat = true;
char addStudent = 'y';
string tempt;
cout << "Enter the number of students to input : ";
cin >> flag;
//input
for (x = 0; x < flag; x++) {
cout << "Enter student name (all-cap) : ";
cin >> records[x].name;
for (y = 0; y < 4; y++) {
cout << "Enter score in quiz " << y + 1 << " : ";
cin >> records[x].studentQuiz[x][y];
}
}
//sort the variable alphabetically
//Display the data
cout << "=============================================================================" << endl;
printf ("%-40s%-10s%-10s%-10s%-10s\n", "Student Name", "Quiz1", "Quiz2", "Quiz3", "Quiz4");
cout << "=============================================================================" << endl;
for (x = 0; x < flag; x++) {
printf ("%-40s", records[x].name.c_str());
for (y = 0; y < 4; y++) {
printf ("%-10d", records[x].studentQuiz[x][y]);
}
cout << "\n";
}
}
ask yourself (or you rubber duck https://en.wikipedia.org/wiki/Rubber_duck_debugging)
"if this struct holds the information for one student why is the studentQuiz a 2d array?"
struct studen_grades {
string name;
int studentQuiz [1][4]; <<<===?
}records[5];
surely you mean
struct studen_grades {
string name;
int studentQuiz [4]; <<<===
}records[5];
Now you can see why this blows up
for (x = 0; x < flag; x++) {
printf ("%-40s", records[x].name.c_str());
for (y = 0; y < 4; y++) {
printf ("%-10d", records[x].studentQuiz[x][y]); <<== x is > 0
}
cout << "\n";
}
should be
for (x = 0; x < flag; x++) {
printf ("%-40s", records[x].name.c_str());
for (y = 0; y < 4; y++) {
printf ("%-10d", records[x].studentQuiz[y]);
}
cout << "\n";
}
and here too
cin >> records[x].studentQuiz[x][y];
-----------------------------+++
Also this is c++ code why arent you using cout instead of printf
Of course there is no sort here. But at least you now have code that loads the data and prints it correctly.
Finally, note that you should really be using std::vector for the students rather than a fixed array
I am new to C++ (so, please forgive me for my C++ atrocities) and am asking for help once again to the helpful people at stack Overflow. I have to create a 2D Array program that reads from 2 files, one named after the Months of the year, and the other being a table of integer values.
I have four functions that break off of main in a switch menu. Function One should display the whole chart with the months going down the first column.
Months && Values. So, basically the months are all in the first column[0] and the values line up adjacent to the months (there will be some added flair to the top most row to give a description of what the values are, but I am sure I can figure that part out)
Then the second function takes all the values in column 1 & 2 (so not [0] because that's the months).
Then my third function takes columns [4] & [5] and adds them up and displays the totals, with the months to left of the values.
My fourth and final function will allow a user to input a given month and display the value display in the 1 first column after the months.
All of my output is never ending 0's.
Please if you could give me any tips/advice/code examples/anything would be greatly appreciated, and I thank you for taking your time to read this garbage code, so that I can hopefully get better at programming! Here is my code, I have not finished it yet since I keep having loop errors that display 0's when I try to ask the program to display one of the four options.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// Global Array Size
const int ROWS = 12, COLUM = 9;
int parkChart[ROWS][COLUM];
//Function Prototypes
void displayCodes(const int[][COLUM], int);
int totalRecNonRec(const int[][COLUM], int rows, int total);
int tentRvByMonth(const int[][COLUM], int);
int displayMonth(const int[][COLUM], int, string);
int main()
{
// Define variables
const int DISPLAY = 1, REC_NONREC = 2, TENT_RV = 3, PER_MONTH = 4;
int response, total = 0;
string month;
ifstream inputFile;
inputFile.open("Months.txt");
ifstream inputFile2;
inputFile2.open("Vistors.txt");
cout << "Visitors to National Park" << endl;
// Do While Loop to display the menu
cout << "Enter 1 to display data" << endl;
cout << "Enter 2 to display total number of recreation and non-recreational visitors" << endl;
cout << "Enter 3 to display total tent and RV campers by month" << endl;
cout << "Enter 4 to display the number of recreational visitors for a certain month" << endl;
cout << "Enter any other number to exit" << endl << "\n";
cin >> response;
do
{
switch (response)
{
case(DISPLAY):
{
inputFile;
inputFile2;
displayCodes(parkChart, ROWS);
break;
}
case(REC_NONREC):
{
totalRecNonRec(parkChart, ROWS, total);
break;
}
case(TENT_RV):
{
tentRvByMonth(parkChart, ROWS);
break;
}
case(PER_MONTH):
{
displayMonth(parkChart, ROWS, month);
break;
}
default:
{
// Closes the file and exits
inputFile.close();
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3|| response == 4);
system("pause");
return 0;
}
// Four Functions
// Display Function
void displayCodes(const int parkChart[][COLUM], int ROWS)
{
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLUM; col++)
{
cout << parkChart[row][col] << "\t ";
}
cout << endl;
}
}
// Totals/Display Rec. & Non Rec. Visitors to the park + adds all months for visitors (must equal 3,350,493)
int totalRecNonRec(const int parkChart[][COLUM], int rows, int total)
{
// for loop that adds all the elements in [0-11,1]&&[0-11,2]
for (int col = 0; col < 1; col++)
{
total = 0;
for (int row = 0; row < ROWS; row++)
total += col;
cout << "The total number of recreational and non-recreational visitors: " << total << endl;
}
return total;
}
// Totals/Display Number of Tent & RV Campers by month (needs to add rv + tent) and show all months
int tentRvByMonth(const int parkChart[][COLUM], int rows)
{
for (int row = 0; row < ROWS; row++)
{
int total = 0;
for (int col = 4; col < 5; col++)
{
total += parkChart[row][col];
cout << parkChart[row][col] << " " << (col + 1) << endl;
}
cout << endl;
}
return 0;
}
int displayMonth(const int parkChart[][COLUM], int rows, string month)
{
// Prompt the user to enter a month/Display the number of Rec. Visitors for that month + Failsafe of non-months
// Need a for loop to search for the user given month, and then display the [month, 1]
cout << "Enter the month you want the number of recreational visitors\n";
getline(cin, month);
// search in first column of array
cout << "For the month of " << month << " there were " << " recreational visitors" << endl;
return 0;
}
So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}
Create a function that prints the array to the screen as a table with the appropriate rows and columns. Use setw() to ensure the numbers have enough room. You may assume the numbers are no more than 3 digits each. Include the row and column labels.
In main, ask the user to supply a row and column and a value (no more than 3 digits), then put the value into the array at that row and column. Print the result and ask the user for another row, column and value. Repeat until the user is finished.
Once finished, compute and print the total of the values in the array.
#include <iostream>
#include <iomanip>
using namespace std;
const int ROWS= 4;
const int COLS = 3;
const int WIDTH = 4;
const char YES = 'y';
int total = 0;
void print(int arr[ROWS][COLS]);
int main()
{
int arr[ROWS][COLS];
char ans = YES;
int val;
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++)
arr[r][c] = 0;}
while (tolower(ans) == YES){
int row = -1;
int col = -1;
cout << "Row? ";
cin >> row;
cout << "Columns? ";
cin >> col;
while (row < 0 || row >=ROWS){
cout << "Only value under " << ROWS << " is accepted, try again: ";
cin >> row;
}
while (col < 0 || col >= COLS){
cout << "Only value under " << COLS << "is accepted, try again: ";
cin >> col;
}
cout << "Value? ";
cin >> val;
arr[row][col] = val;
print(arr);
cout << "Again (y/n)? ";
cin >> ans;
}
for (int r = 0; r < ROWS; r++){
for (int c = 0; c < COLS; c++){
total += arr[r][c];
}
}
cout << "Sum of all values is " << total << endl;
// Print array with labels
// get input from user
// print array again - repeat until user wishes to quit
return 0;
}
void print (const int arr[ROWS][COLS])
{
cout << endl << endl;
for (int i = 0 ; i < COLS; i++)
cout << setw(WIDTH) << i;
cout << endl;
for (int r = 0; r < ROWS; r++)
cout << setw(WIDTH) << r << "|";
for (int r = 0; r < ROWS; r++)
for (int c = 0; c< COLS; c++)
cout << setw(WIDTH) << arr[r][c];
cout << endl << endl;
}
I dont know where I did wrong on this one but when I complie, I got the LD return 1 exit status error, Can you please help?
The definition and the declaration of your print function are different.
Change the declaration of your print() function.
void print(int arr[ROWS][COLS]);
to
void print(const int arr[ROWS][COLS]);
Hello I had recently asked a question about how to do the following:
Write a function that sums all the integers in a matrix of integers using the following header:
const int SIZE = 4;
double sumMatrix (const double m [] [SIZE] , int rowSize, int columnSize) ;
Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements. Heres a sample run:
Enter a 4by4 matrix row by row:
1 2 3 4 [Enter]
5 6 7 8 [Enter]
9 10 11 12 [Enter]
13 14 15 16 [Enter]
Sum of the matrix is 136
I tried to use all the suggestions I could but the problem maybe that I just need to go back to the basic and learn some basic things I have skipped over, but heres what I have so far. Corrections and solutions, and help in any form would be highly appreciated.
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
cout<< "Sum of the matrix"<< sum(m,4) << endl;
return 0;
}
The read function that you need will look almost the same as your print function:
void read(const int a[] [COLUMN_SIZE], int rowSize)
{
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
cout << "Enter number for [" << row << "][" << column << "]: ";
cin >> a[row][column];
}
}
}
(As a footnote: if you can generalise the looping and have one function that you pass 'read' or 'sum' to you're well on your way to being awesome)
edit: guess I didn't read the 'row by row' bit of the question. shrug.
Three years later, haha, but you can enter cols elements separating them with spaces and use enter to get elements of other row.
Improving your code. Just see and understand. A didactic program is better than a thousand words :p
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
void showmatrix(const int a[] [COLUMN_SIZE], int rowSize, const char *name)
{
int row_index, col_index;
cout<< name << " [" << rowSize << "][" << COLUMN_SIZE << "] =" << endl;
for(row_index = 0; row_index < rowSize; row_index++)
{
for(col_index = 0; col_index < COLUMN_SIZE; col_index++)
{
if(col_index == 0)
{
if(row_index ==0)
{
cout<< "\t /";
}
else if(row_index == rowSize - 1)
{
cout<< "\t \\";
}
else
{
cout<< "\t|";
}
}
cout<< "\t" << a[row_index][col_index];
if(col_index == 3)
{
if(row_index ==0)
{
cout<< "\t\\";
}
else if(row_index == rowSize - 1)
{
cout<< "\t/";
}
else
{
cout<< "\t |";
}
}
}
cout<< endl;
}
cout<< endl;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
int row_index, col_index;
cout<< "There is a stored matrix on that program. It is shown below: " << endl << endl;
showmatrix(m, 4, "Stored_Matrix");
cout<< "The sum of elements of that stored matrix is: "<< sum(m,4) << endl << endl;
cout<< "Now, let's enter another 4 x 4 matrix." << endl << endl;
cout<< "(Note: You can use <space> character to separate column elements or <enter>" << endl;
cout<< "key to enter a new row.)" << endl;
cout<< "(Note 2: Really, you can use both to separate each one of the 16 matrix" << endl;
cout<< "elements, but do not enter more than that or the program will do some error)." << endl << endl;
for(row_index = 0; row_index < 4; row_index++)
{
for(col_index = 0; col_index < 4; col_index++)
{
cin>> m[row_index][col_index];
}
}
cout<< endl;
cout<< "The entered matrix is below:" << endl << endl;
showmatrix(m, 4, "Entered_Matrix");
cout<< "The sum of elements of that entered matrix is: "<< sum(m,4) << endl << endl;
//only to do not close console window on Windows
cout<< "Program ended." << endl << endl << "Press something to exit.";
cin.get();
cin.get();
return 0;
}
I hope you can use it on your reborn or after developing a time machine to use that idea on your 2010 homework.
As you use C++ Builder tag for that question, you can create a new console application and copy-paste the code above overwriting generated one. Use F9 to compile and run.