C++: When entering numbers into array first number is 0 - c++

Trying to make a calculator that calculates values in an array based on input from user. But the first value in the array is always 0 when I leave 'p undefined or p = 1 will have give me the same problem. It should be whatever the user enters for the first value and so on.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
The sum should be 3 not 4.
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4

The program is invalid and has undefined behavior.
For starters variable length arrays is not a standard C+ feature
int p = 1, y = 0;
double sum = 1;
int many[p];
And in any case you defined an array with one element. So the only valid index to access elements of the array is 0.
Even in the first statement that uses the array
cin >> many[p];
it is accessed outside its bounds.
You should use the standard class template std::vector. Or as in fact you are dealing with one value then there is even no sense to use a container, Define a scalar object instead of the array.

The initial value of the sum is 1, that's why it is adding 1 more. We can't keep it 0 either, because then it will mess up the '*' and '/' cases.
I have added the initial sum value for all the cases.
Also, I would suggest you, to use switch cases instead of if, else statements.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
if (y == 0) {
sum = 0;
}
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
if (y == 0) {
sum = 0;
}
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
if (y == 0) {
sum = 1;
}
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
if (y == 0) {
sum = 1;
}
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}

There are a lot of things here that don't make sense.
You are starting with sum = 1. this is why the value is always +1
many is an array of size 1, can be changed to single int.
you are accessing many[p] which is many[1] which is out of bounds. you can only access many[0]
the rest I leave it to you to find,

Related

While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0

While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.

C++ if statement not printing desired output

Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.
REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}
Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}

maximum power a number can be raised to with out exceeding y recursion

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.

Classifying digits of an integer value

I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks

Vectors to find Median - homework

I'm a relatively new learner to C++ and I've been having some trouble. If you guys read the title, this is a homework problem (just letting you guys know out there) and I'm not really sure as to where my error is. Using GIT Bash, I can't see why this isn't compiling (or maybe i just don't know how to read it). I feel like i've touched upon all the bases and would appreciate a quick look over to see if my mistake is blaringly obvious. I've done a couple looks through stackoverflow and so the inputting values into a vector was used from another post but i've modified it a bit. In addition, I added in a sort for the vector from smallest to largest.
Also, how can I change the for statement to allow for variable #'s in the vector?
#include <iostream>
#include <vector>
using namespace std;
double showMedian(const vector<int> & vecmedian, int size)
{
int middle;
double average, median;
middle = size / 2.0;
if (size % 2 == 0)
{
median = (vecmedian[middle] + vecmedian[middle + 1]) / 2.0;
cout << "The median is: " << average << endl;
}
else
{
median = vecmedian[middle + 0] / 1.0;
cout << "The median is: " << median << endl;
}
return median;
}
int main()
{
int n,input, i;
vector<int> vecmedian;
vector<int>::iterator itr;
cout << "Enter the amount of numbers: ";
cin >> n;
cout << "Enter your numbers to be evaluated: " << endl;
while (vecmedian.size() < n && cin >> input){
vecmedian.push_back(input);
}
for(i = 1; i < 10; ++i){
for(itr = vecmedian.begin(); itr != vecmedian.end(); ++itr){
if(vecmedian[i] < *itr){
vecmedian.insert(itr, vecmedian[i]);
break;
}
}
if(itr == vecmedian.end())
vecmedian.push_back(vecmedian[i]);
}
showMedian();
return 0;
}
Point 1
When making function prototypes, you need to keep them consistent with the actual definition of the function.
You have:
void showMedian();
As a function-prototype but you have:
double showMedian(int *vecmedian, int size)
As the actual definition. They both need to be consistent.
Since you have not declared an array, maybe change the parameters of showMedian to:
double showMedian(const vector<int> & vecmedian, int size)
Point 2
if(nums[i] < *itr)
Where is nums declared?
Point 3
If you want to use the definition of showMedian, then use the parameters that it uses assuming you made the changes above (and assuming n is size).
showMedian(vecmedian, n);
Edit
With all the consulting in the comment section and the new updated OP Question, here is a fairly solid program which finds the median in a vector:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double showMedian(const vector<double> & vecmedian, int num);
int main()
{
unsigned int n;
double input;
vector<double> vecmedian;
// cout << "Enter the amount of numbers: ";
do {
cout << "Enter the amount of numbers: ";
while(!(cin >> n)){
cout << "Wrong input" << endl;
cout << "Enter the amount of numbers: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (n == 0)
{
cout << "Invalid, size must be greater than 0" << endl;
}
} while (n == 0);
// cout << "Enter your numbers to be evaluated: " << endl;
for (int i = 1; i <= n; ++i)
{
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
while(!(cin >> input)){
cout << "Wrong input" << endl;
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
vecmedian.push_back(input);
}
// while (vecmedian.size() < n && cin >> input){
// vecmedian.push_back(input);
// }
sort(vecmedian.begin(), vecmedian.end());
showMedian(vecmedian, vecmedian.size());
return 0;
}
double showMedian(const vector<double> & vecmedian, int num)
{
int middle;
double median;
middle = (num / 2);
if (num % 2)
median = vecmedian[middle];
else
median = (vecmedian[middle - 1] + vecmedian[middle]) / 2.0;
cout << "The median is: " << median << endl;
return median;
}