I have a problem with my histogram program, I am getting it to print out the exact thing that I want it to, however it has some unusual spacing problems and I was wondering if anyone could help me out with how to avoid it.
this is what my output looks like, as you can see it has wrong spacing in all the ones before the 90-100 bracket.
What I want it to look like so there is no space at the bottom between the numbers and the asterisk:
*
*
* *
* *
* *
* *
* *
* *
* * *
* * * *
* * * *
0 1 2 3
also can anyone recommend something to use instead of system("Clear") or system("PAUSE")?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
void readExamMarks(int examMarks[], int sizeOfArray, int& counter1, int& counter2, int& counter3, int& counter4,int& counter5, int& counter6,int& counter7, int& counter8, int& counter9, int& counter10){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
if((x >=0) && (x <= 100)){
x = x/10;
switch(x){
case 1:
counter1++;
break;
case 2:
counter2++;
break;
case 3:
counter3++;
break;
case 4:
counter4++;
break;
case 5:
counter5++;
break;
case 6:
counter6++;
break;
case 7:
counter7++;
break;
case 8:
counter8++;
break;
case 9:
counter9++;
break;
case 10:
counter9++;
break;
}
examMarks[idx] = x;
}
else{
cout << "ERROR: Value must be in range [0...100], please enter a valid value\n";
}
}
}
void printExamMarksDecade(){
cout << setw(5) << "10-20 " << "21-30 " << "31-40 " <<"41-50 " << "51-60 " << "61-70 " << "71-80 " << "81-90 " << "91-100 ";
}
void printHisto(int examMarks[], int sizeOfArray,int counter1, int counter2, int& counter3, int& counter4,int& counter5, int& counter6,int& counter7, int& counter8, int& counter9, int& counter10){
system("cls");
while(counter1 != 0 ){
cout << setw(3) << "*" << endl;
counter1--;
}
while(counter2 != 0 ){
cout << setw(10) << "*" << endl;
counter2--;
}
while(counter3 != 0 ){
cout << setw(17) << "*" << endl;
counter3--;
}
while(counter4 != 0 ){
cout << setw(24) << "*" << endl;
counter4--;
}
while(counter5 != 0 ){
cout << setw(31) << "*" << endl;
counter5--;
}
while(counter6 != 0 ){
cout << setw(38) << "*" << endl;
counter6--;
}
while(counter7 != 0 ){
cout << setw(45) << "*" << endl;
counter7--;
}
while(counter8 != 0 ){
cout << setw(52) << "*" << endl;
counter8--;
}
while(counter9 != 0 ){
cout << setw(59) << "*" << endl;
counter9--;
}
}
int main()
{
int examMarks[30];
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
readExamMarks(examMarks, 30, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9, counter10);
printHisto(examMarks, 30, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9, counter10);
printExamMarksDecade();
system("PAUSE");
}
A variable counter for each range is not really what you want to be doing, you just want one array:
#include <iostream>
using namespace std;
int main() {
// count array for brackets 0 to 10
int *count = new int[11];
// variable to store each mark read
int mark;
// Read in marks
while (cin >> mark) {
// Increment the count for the bracket the mark falls in
count[mark/10]++;
}
for (int i=0;i<11;i++) {
cout << i << "\t| " << string(count[i],'*') << endl;
}
}
This plots a horizontal histograms but shows the much simple way it should be done.
$ ./histogram.out < marks
0 | ******
1 | *********
2 | **********
3 | ************
4 | *********
5 | *****************
6 | ********
7 | *********
8 | ***
9 | ****
10 | *
You will have less headaches modifying this code, try increasing the number of brackets to 1000 in original code!
Related
I am working on a program in which I have a function and I am hoping to time it. Currently, I considered clock_t in the ctime module to be useful, but when I entered the code for timing, I got (I used Dev-C++ to edit) "permission denied". Below is my code:
#include <iostream>
#include <vector>
#include <ctime>
// Initialization
const int maxN = 99999;
int tokens[maxN] = {}; // All the tokens at mission 1
bool use[maxN] = {}; // Status of the tokens (used or not used)
int bag[maxN]; // Bag to put the tokens into
using namespace std;
int ansIdx = 1; // Answer number
char menu() {
// Print menu
cout << "0: terminate\n";
cout << "1: mission 1 - permutations from 1 ~ N\n";
cout << "2: mission 2 - permutations from input\n";
// Ask for input
cout << "Please input a choice (0 ~ 2): ";
char choice;
cin >> choice;
// Valid command?
if (choice >= '0' and choice <= '2') {
return choice;
}
return '\0';
}
int permutations(int depth, int n, int l) {
if (depth == n) {
// Arranged all elements, so cout each of the elements.
cout << "[" << ansIdx << "] ";
for (int i = 0; i < n; i++) cout << bag[i] << " ";
cout << "\n";
ansIdx++;
return l;
}
for (int i = 0; i < n; i++) {
// Else, for each UNUSED element at this layer:
if (use[i] == 0) {
// Put it into bag[i].
bag[depth] = tokens[i];
// Set the status of it used.
use[i] = 1;
// Call recursion.
permutations(depth + 1, n, l+1);
// Backtrack.
use[i] = 0;
}
}
}
int main() {
// Print menu.
cout << "PERMUTATION GENERATOR\n";
char executionMode;
while (executionMode != '0') {
executionMode = menu();
while (executionMode == '\0') {
executionMode = menu();
}
int layers;
clock_t start;
double ms;
switch (executionMode) {
case '1':
cout << "Enter N: ";
int N;
cin >> N;
for (int i = 0; i < N; i++) {
tokens[i] = i + 1;
}
start = clock();
layers = permutations(0, N, 0);
ms = ((double)(clock() - start)) / CLOCKS_PER_SEC;
cout << "L = " << layers << "\n";
cout << "Mission 1: " << ansIdx - 1 << " permutations\n";
cout << "Used: " << ms << "ms\n";
ansIdx = 1;
break;
case '2':
int M = 0;
while (M < 2 or M > 9) {
cout << "Enter length of input (2 ~ 9): ";
cin >> M;
}
for (int i = 0; i < M; i++) {
cout << "Enter a number: ";
cin >> tokens[i];
}
start = clock();
layers = permutations(0, M, 0);
ms = ((double)(clock() - start)) / CLOCKS_PER_SEC;
cout << "L = " << layers << "\n";
cout << "Mission 2: " << ansIdx - 1 << " permutations\n";
cout << "Used: " << ms << "ms";
ansIdx = 1;
break;
}
}
return 0;
}
Can anyone help me? Any suggestions are appreciated.
I am a student in c++, we have started 3 weeks ago. Our assignment is to make a Base Converter without using stoi or atol. We are using a site called Repl.it. I am getting an error called Segmentation Error with doesn't make sense. It started with stringToDecmial. We are referring to the Ascii Table by the way.
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int strToDecimal(int base, string num);
string decimalToBase(int number, int base);
int main()
{
int menuChoice;
int startBase;
int numberInDecimal;
string number;
cout << "NUMBER BASE CONVERTER 2019" << endl;
cout << "By: Suraj Joshi" << endl << endl;
cout << "Enter number to convert: ";
cin >> number;
cout << "Choose your starting base: " << endl
<< "1. Binary" << endl
<< "2. Octal" << endl
<< "3. Decimal" << endl
<< "4. Hex" << endl;
cin >> menuChoice;
switch (menuChoice)
{
case 1: {
startBase = 2;
break;
}
case 2: {
startBase = 8;
break;
}
case 3: {
startBase = 10;
break;
}
case 4: {
startBase = 16;
break;
}
default: {
startBase = 0;
cout << "Invalid Choice..." << endl;
break;
}
}
numberInDecimal = strToDecimal(startBase, number);
cout << "Binary: " << decimalToBase(numberInDecimal, 2) << endl;
cout << "Decimal: " << numberInDecimal << endl;
cout << "Octal: " << decimalToBase(numberInDecimal, 8) << endl;
cout << "Hex: " << decimalToBase(numberInDecimal, 16) << endl;
return 0;
}
// This is where the problem starts(I Believe) I never experianced the problem
// when this wasnt here
int strToDecimal(int base, string num)
{
int sum = 0;
for (int i = 0; num.length() - 1; ++i) {
if (num[i] > 64)
sum += (num[i] - 55) * pow(base, num.length() - 1 - i);
else
sum += (num[i] - 48) * pow(base, num.length() - 1 - i);
}
return sum;
}
// this can be ingored, This isnt what is causing the problem but feel free to
// look at it, it isnt complete yet
string decimalToBase(int number, int base) {
int rem;
string tempStr(1, number % base + 48);
while (number != 0) {
rem = number % base;
number = number / base;
// str.insert(0, string(1, num % base + 48))
// or string tempStr (1, num % base + 48);
// str.insert(0, tempStr);
switch (rem) {} // switch
} // while
return " ";
}
The segmentation fault is because you're reading past the end of the num string. In your strToDecimal function this line
for (int i = 0; num.length() - 1; ++i) {
does not perform the right termination check. As long as num.length() - 1 contains a non-zero value the loop will continue indefinately. You probably want to change it to:
for (int i = 0; i < num.length(); ++i) {
i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.
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;
I am new to posting and relatively new to coding in c++.
My question involves:
Handling decimal values in evaluating postfix using stacks in c++. This is a homework assignment, but I have already gotten my code to work for the basic requirement. I am not asking for help with my homework. My professor wants us to brute force the assignment, so I have avoided many shortcuts using special header files such as <stack>.
I have researched the question and was not satisfied with the answers given. No one else seems to have split up their code like mine. I am having an issue passing a value from the inner loop which detects the decimal values to the rest of the main function. The code compiles and runs, but my final result is gibberish. I found a post which states multiple values cannot be passed from a function with 'return', but I do need at least two values returned from the inner decimal function. I do not understand the 'tuple' or 'pair' commands.
I know this is a wordy prelude, but I do want any readers to understand I have read pre-requisite materials and did lost of research. Personally, I hate brute force methods. I understand that a response may not be in time to help with my project, but I have been working on this for weeks. I would like to get the satisfaction of seeing this method work as conceived. Suggestions and pointers are very much welcome.
Here is the link to my code:
link
Here is my code:
//*****************************************************************************
// Postfix expression evaluation
// 11/13/2012
// by DJH
//
// all applicable copyrights apply
//
// this program evaluates an input postfix string
//
// created using Dev-C++ 5.2.0.3
//*****************************************************************************
// ----------------------------------libraries---------------------------------
#include <iostream> // For cin, cout and endl
#include <string>
#include <cctype>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
using namespace std;
// ------------------------------ Globals -------------------------------------
string postfix;
// --------------------------- stack class ------------------------------------
class Stack {
public:
enum {MaxStack = 50};
void init() {top = -1;}
void push( double p ) {
if ( isFull() ) {
cerr << "Full Stack. DON'T PUSH\n";
return;
}
else {
arr[ ++top ] = p;
cout << "Just pushed " << p << endl;
return;}
}
int pop() {
if (isEmpty() ) {
cerr << "\tEmpty Stack. Don't Pop\n\n";
return 1;
}
else
return arr[top--];
}
bool isEmpty() {return top < 0 ? 1 : 0;}
bool isFull() {return top >= MaxStack -1 ? top : 0;}
void dump_stack() {
cout << "The Stack contents, from top to bottom, from a stack dump are: " << endl;
for (int s = top; s >= 0; s--)
cout << "\t\t" << arr[s] << endl;
}
private:
int top;
double arr[MaxStack];
} pStack;
// ------------------------------ end stack class -----------------------------
// -----------------------------function prototypes----------------------------
void evalPostfix( string);
double decimalEvaluate( string, int, double);
// ----------------------------------------------------------------------------
// -----------------------------------Main()-----------------------------------
int main() {
cout << "Enter a postfix expression\n\t (without spaces - using '_' for delimiters):\n\t";
cout << "For example: 8_5_3_+_*_2_/_5_+\n" << endl;
getline(cin, postfix);
// postfix = "7_2_*_5_+_2_*";
cout << "You entered: " << postfix << endl;
int c = 0;
while (postfix[c] != '\0') {
// this loop counts the characters in the input string including
// whitespace
++c;
}
cout << "\tThe string length is:\t" << c << endl;
evalPostfix(postfix);
int result = pStack.pop();
cout << "The result of the postfix expression is: " << result << endl;
/*
stack commands:
Stack a_stack; // creates new stack
a_stack.init(); // initializes top element
a_stack.pop(); // pops top of stack
a_stack.push(n); // push element to top of stack
a_stack.dump_stack(); // displays the contents of the stack from top to bottom
*/
return 0;
cin.get();
}
// --------------------------------end of Main()-------------------------------
// ------------------------------functions follow------------------------------
void evalPostfix( string) {
double ch = 0, dc = 0, b = 0, a = 0, d = 0;
double tempDC = 0;
double tempDCD = 0;
char op;
int i = 0, j = 0, k = 0, m = 0, n = 0, q = 0;
while (postfix[i] != '\0') {
if (postfix[i] == '_') {
i++;
} else if (isdigit(postfix[i])) {
ch = postfix[i] - '0'; // for numbers only
j = i + 1;
while (postfix[j] != '_') {
if (isdigit(postfix[j])) {
ch = ch * 10 + (postfix[j] - '0');
k = j + 1;
// this accounts for decimals by skipping the '.' and
// conducting operations on trailing numbers
if (postfix[k] == '.') {
dc = 0;
decimalEvaluate(postfix, k, dc);
dc = tempDC / tempDCD;
d = ch + dc;
k++;
}
j = k - 1;
j++;
}
}
cout << "Post decimal function k: " << k << endl;
cout << "Post decimal function dc: " << setprecision(12) << dc
<< endl;
cout << "Post decimal function d: " << d << endl;
pStack.push(d);
i = j - 1;
i++;
} else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*'
|| postfix[i] == '/' || postfix[i] == '^') {
b = pStack.pop();
a = pStack.pop();
op = postfix[i]; // for operators only
switch (op) {
case '+':
pStack.push(a + b);
break;
case '-':
pStack.push(a - b);
break;
case '*':
pStack.push(a * b);
break;
case '^':
pStack.push(pow(a, b));
break;
case '/':
if (b == 0) {
cout << "Division by zero not allowed!" << endl;
cin.get();
exit(0);
}
pStack.push(a / b);
default:
cout << "Invalid Operation" << endl;
}
i++;
}
}
}
// ----------------------------------------------------------------------------
double decimalEvaluate(string postfix, int k, double dc) {
dc = 0;
double tempDC = 0;
double tempDCD = 0;
int n = 0, m = 0, lenDC = 0;
n = k;
while (postfix[n] != '_') {
if ((isdigit(postfix[n])) == false) {
n++;
}
cout << "This step (1) n: " << n << endl;
if (isdigit(postfix[n])) {
m = n;
// assumes characters between a '.' and '_' are all digits
// (may need to check)
while (postfix[m] != '_') {
lenDC++;
// this loop counts the digits in the input trailing a decimal
// point
m++;
}
cout << "This step (2) m: " << m << endl;
cout << "This step (2) lenDC: " << lenDC << endl;
while ((postfix[n]) != '_') {
tempDC = tempDC * 10 + (postfix[n]) - '0';
n++;
}
cout << "This step (3) n: " << n << endl;
cout << "This step (3) tempDC: " << tempDC << endl;
}
k = n;
tempDCD = pow(10, lenDC);
dc = tempDC / tempDCD;
cout << "This step (4) k: " << k << endl;
cout << "This step (4) tempDCD: " << tempDCD << endl;
cout << "This step (4) tempDC: " << tempDC << endl;
cout << "This step (4) dc: " << dc << endl;
}
return dc, k, tempDC, tempDCD;
}
Pass the variables by reference:
void decimalEvaluate (string postfix, int& k, double& dc, double& tempDC, double& tempDCD)
{
tempDC = 0.0;
//...
}