Error in displaying the largest and smallest number - c++

I was attempting to write a program for exercise 2.19 in How to Program, but I ran into some difficulties.
The program is supposed to have the user enter three integers and then display the sum, average, and product of those integers.
The only problem I am having is with displaying the largest and smallest. When I ran the program and entered three integers (8, 9, and 10), the output read Smallest is 8 AND Smallest is 9.
I was hoping you could tell me why.
#include <iostream>
using namespace std;
int main ()
{ int x, y, z, sum, ave, prod;
cout << "Input three different integers ";
cin >> x >> y >> z;
sum = x + y + z;
cout << "\nThe sum is " << sum;
ave = (x + y + z) / 3;
cout << "\nThe average is " << ave;
prod = x * y * z;
cout << "\nThe product is " << prod;
if (x < y, x < z)
{cout << "\nSmallest is " << x;}
if (y < x, y < z)
{cout << "\nSmallest is " << y;}
if (z < x, z < y)
{cout << "\nSmallest is " << z;}
if (x > y, x > z)
{cout << "\nLargest is " << x << endl;}
if (y > x, y > z)
{cout << "\nLargest is " << y << endl;}
if (z > x, z > y)
{cout << "\nLargest is " << z << endl;}
return 0;
}
P.S. I am doing this to study, this is not homework.

You need to rewrite this if condition
if (x < y, x < z)
to be
if (x < y && x < z)
and do the same for all of the remaining if conditions you have.
Edit:
All experssions seperated by comma will be evaluated so if you have something like that
x = 5, y = 6; it will evaluate both of them and set x to 5 and y to 6
but
z = (x=5, y=6); this will cause z to be set to 6 just like y as y=6 was the last term in the list of comma separated terms.

int main() {
std::cout << "Enter three numbers: ";
int sum = 0;
double avg = 0.;
int product = 0;
int smallest = std::numeric_limits<int>::max();
int largest = std::numeric_limits<int>::min(); // the initializers here might not be correct, but the gist is in place...
for (int i = 0; i < 3; ++i) {
int val = 0;
std::cin >> val;
sum += val;
avg += val;
product *= val;
if (val < smallest) smallest = val;
if (val > largest) largest = val;
}
avg /= 3.; // This can also be done in the for loop, I just forget how.
std::cout << "Sum: " << sum;
// etc... The calculations are all done.
}

Replace your commas, with && for an AND operator, meaning both of the conditions have to be true, or || which is an OR operator, if you want any or both conditions to be satisfied.
from C++ docs:
The comma operator (,) is used to separate two or more expressions that are included
where only one expression is expected. When the set of expressions has to be evaluated
for a value, only the rightmost expression is considered.

Instead of comma, you want &&
i.e.
if (x < y , x < z)
{cout << "\nSmallest is " << x;}
should be
if (x < y && x < z)
{cout << "\nSmallest is " << x;}

Use && in place of , inside your if conditions.

By now you realize that && is for AND and that you should use this operator instead of the comma, ,. But did you know you can also use they keyword and in place of its symbol equivalent?:
if ( x < y and x < z ) {
}

Related

How to print inverted half-star pyramid pattern next to each other?

I want to display an inverted half-star pyramid pattern next to each other.Here's the desired output
And here's my code:
#include <iostream>
using namespace std;
int main()
{
int n, x, y, k;
cout << "Enter Number of Rows: ";
cin >> n;
for (x = n; x >= 1; x--)
{
for (y = 1; y <= x; y++)
{
if (y <= x)
cout << "*";
else
cout << " ";
}
for (y = n; y >= 1; y--)
{
if (y <= x)
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Here's the output I got after running the code.
The number of rows desired is 10.
After running my code, the output isn't like what I expected. Please tell me how to make it right.
Thank you.
I saw some symmetries in the problem
for n rows, we're printing 2*n+1 characters
for the yth row, we're printing an asterisk if x is less than n-y or more than n+y
So I coded a single double loop with the more complex if statement. I had to adjusted the if statement until it worked.
#include <iostream>
using namespace std;
int main()
{
int n, x, y;
cout << "Enter Number of Rows: ";
cin >> n;
for (y = 0; y < n; y++)
{
for (x = 2*n+1; x > 0; x--)
{
if ((x > n+y+1) || (x < n-y+1))
cout << "*";
else
cout << " ";
}
cout << "\n";
}
return 0;
}
Well, you need to change your logic a little bit rest all is fine.
Here is the code:-
#include <iostream>
using namespace std;
int main()
{
int n, x, y, k;
cout << "Enter the number of Rows: ";
cin >> n;
for(x = 1; x <= n; x++)
{
for(y = n; y >= 1; y--)
{
if(y <= x)
cout << " ";
else
cout << "*";
}
for(y = 1; y <= n; y++)
{
if(y <= x)
cout << " ";
else
cout << "*";
}
cout << "\n";
}
return 0;
}
Explanation:- I am starting from row 1 and going till row "n". Now I need to print two different inverted flags so I used two for loops for that. In one loop I am starting from column "n" and going till row >1 and in the other loop, I am doing the just opposite of that so that both flags will be opposite to each other. Just try to understand this code by taking X as row and Y as column.

Why do my if statements not work in for loops?

So this is my second program I've tried writing an if statement in a for loop. The first one was unnecessary, but this one "needs" it. I put needs in quotes because I'm new to C++ and have not learned/thought of another method.
My program:
int main()
{
int x, z;
cout << " x | z | y\n"
<< "---------------------------\n";
for (x = 1; x <=5; x++)
{
for (z = 2; z <= 6; z++)
{
double y = x*z/(x-z);
if (x - z == 0)
{
cout << setw(2) << x << setw(4) << z << setw(21) << "Function Undefined\n";
}
else if (x - z != 0)
{
cout << setw(2) << x << setw(4) << z << setw(21) << y << endl;
}
}
}
return 0;
}
When I run this, I get a table with the first loop sequence (x = 1) completed, but then it crashes (Windows is looking for solution box pops up). It writes out the correct values only for x = 1 (the outer loop does not repeat to x = 2 and so on).
Why is this happening?
«whisper»...hey...you are dividing by 0 boy...
You put the if statement just before the actual math. If you divide by zero, an error will occur.
Put the math in the else if block.

Find numeric substring with integers only

The Question :
If the sequence of digits in X forms a substring of the sequence of digits in Y, it outputs "X is a substring of Y"; otherwise, if the sequence of digits in X forms a subsequence of the sequence of digits in Y, then it outputs "X is a subsequence of Y"; otherwise, it outputs "X is neither substring nor subsequence of Y".
DO NOT use arrays or strings in this program
The output should be as follows
Enter Y : 239847239
Enter X : 847
X is substring of Y
Enter Y : 239847239
Enter X : 3923
X is subsequence of Y
Enter Y : 239847239
Enter X : 489
X is neither substring nor subsequence of Y
And below is what I got so far... (haven't coded anything for subsequence as i was clueless)
I know my coding is very unefficient and is only suitble to use for the above model output. Any improvements or comments how to fix this would be greatly appreciated.
#include <cmath>
#include <iostream>
using namespace std;
int main() {
cout << "Enter Y: " ;
int Y;
cin >> Y;
cout << "Enter X: ";
int X;
cin >> X;
if (Y >= X){ // Below are all the possibilities of substrings up to 9 decimal places.
if( X == (Y % 10)) cout << "X is substring of Y";
else if (X == (Y % 100)) cout << "X is substring of Y";
else if (X == (Y % 1000)) cout << "X is substring of Y";
else if (X == (Y % 10000)) cout << "X is substring of Y";
else if (X == (Y % 100000)) cout << "X is substring of Y";
else if (X == (Y % 1000000)) cout << "X is substring of Y";
else if (X == (Y % 10000000)) cout << "X is substring of Y";
else if (X == (Y % 100000000)) cout << "X is substring of Y";
else if (X == (Y % 1000000000)) cout << "X is substring of Y";
else cout << "X is neither substring nor subsequence of Y";
}
else cout << "neither subsequence nor subset"; // prints out when Y is less than X.
return 0;
}
This what i got by far:
Substring
bool substring(long x, long y){
double auxX = x;
int power = 0;
while (auxX >= 1){
auxX /= 10;
++power;
}
int mask = pow(10, power);
int reminder;
while (y > 0){
reminder = y % mask;
if (reminder == x){
return true;
}
y /= 10;
}
return false;
}
Subsequence
bool subsequence(long x, long y){
int lastX;
int lastY;
while (y > 0){
lastX = x % 10;
lastY = y % 10;
if (lastX == lastY){
x /= 10;
if (x <= 0){
return true;
}
}
y /= 10;
}
return false;
}
Main
int main()
{
long x = 21;
long y = 469721481;
if (substring(x, y)){
cout << x << " is substring of " << y << std::endl;
}
else if (subsequence(x, y)){
cout << x << " is subsequence of " << y << std::endl;
}
else{
cout << x << " is neither substring nor subsquence of " << y << std::endl;
}
return 0;
}
I've tested some cases and it seems to work fine, but you should test with edge cases (multiple repetitions of the same pattern, one digit numbers, zeros, etc) and retouch this snippet

My c++ code for factoring isn't working

I am trying to create a c++ program that when I input two numbers (num1, combinationNum), it finds two numbers that multiply together to equal num1, but add together to equal combinationNum. It currently works for positive integers, but not negative. How do I make it work with negative integers? Also, If the equation isn't solvable, I would like it to print an error of some sort. Thanks!
Code:
//
// main.cpp
// Factor
//
// Created by Dani Smith on 2/13/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void factors(int num, int comNum){
int a, b;
cout<<"The factors are ";
bool isPrime = true;
int root = (int)sqrt((double)num);
for(int i = 2; i <= root; i++){
if(num % i == 0 ){
isPrime = false;
//cout<<i<<",";
for(int x = 0; x<3; x++){
if(x==1){
a = i;
}
else if(x == 2){
b = i;
}
if(a + b == comNum){
cout << a << ", and " << b << ".";
}
}
}
}
//----------------------------------------
if(isPrime)cout<<"1 ";
cout<<endl;
}
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, multiple = 0, combinationNum = 0, output1 = 0, output2 = 0;
cout << "What number do you want to factor?\n";
cin >> num1;
cout << "What do you want them to add to?\n";
cin >> combinationNum;
factors(num1, combinationNum);
return 0;
}
To solve:
x + y == a
x * y == b
You have to solve
y == a - x
x * x - a * x + b == 0
So with delta == a * a - 4 * b, if delta positive, the solutions are
x1 = (a + sqrt(delta)) / 2
x2 = (a + sqrt(delta)) / 2
The code : (https://ideone.com/qwrSwa)
void solve(int sum, int mul)
{
std::cout << "solution for x + y = " << sum << std::endl
<< " x * y = " << mul << std::endl;
const int delta = sum * sum - 4 * mul;
if (delta < 0) {
std::cout << "No solution" << std::endl;
return;
}
const float sqrtdelta = sqrtf(delta);
const float x1 = (sum + sqrtdelta) / 2.f;
const float x2 = (sum - sqrtdelta) / 2.f;
std::cout << "x = " << x1 << ", y = " << sum - x1 << std::endl;
if (delta != 0) {
std::cout << "x = " << x2 << ", y = " << sum - x2 << std::endl;
}
}

How to get the largest and smallest of 3 values with fewest comparisons?

This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.
I need to only use if statements.
This is what I tried so far: which required 4 comparisons.
int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;
smallest = x;
largest = x;
if (y > largest)
largest = y;
if (z > largest)
largest = z;
if (y < smallest)
smallest = y;
if (z < smallest)
smallest = z;
cout << "largest: " << largest << ", and smallest: " << smallest << endl;
My question is: Is it possible to only use 3 comparisons, or less? I think when y > largest, it also tells us something else as well?
The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example
if (y > largest)
don't just treat the true case. Also try to reason about the case when the condition doesn't hold.
if ( x < y )
{
smallest = x;
biggest = y;
}
else
{
smallest = y;
biggest = x;
}
if ( z < smallest )
smallest = z;
else if ( z > biggest )
biggest = z;
This contains only 3 comparisons.
Why are you checking if (y < smallest)? At this point in the flow, smallest must be x, but you've already checked if y > x in the first condition (if (y > largest)), so the third condition is redundant.
The question is finding the largest or smallest by only if else statements, and we have three variables to use, so we only need two comparisons.
{
int valueOne,
valueTwo,
valueThree,
smallest;
//User input for valueOne, valueTwo, valueThree.
smallest = valueOne;
if (smallest < valueTwo)
{
smallest = valueTwo;
}
if (smallest < valueThree)
{
smallest = valueThree;
}
//No matter what happens, smallest will have the smallest value now.
//Use >, rather than <, and "largest" rather than "smallest" for finding largest value.
//With this logic, you always will have one less comparison than the total number or variables to compare
//i.e. 7 variables means 6 comparisons.
//This contains only 2 comparisons.
In general you can determine a sort for three numbers x, y, and z using at most 3 comparisons:
if (x < y)
if (y < z)
//x,y,z -> x min
else if (x < z)
//x,z,y -> x min
else
//z,x,y -> z min
else
if (z >= x)
//y,x,z -> y min
else if (z >= y)
//y,z,x -> y min
else
//z,y,x -> z min
So getting the min can also be done with 3 comparisons.
You can get the min in 2 comparisons by doing:
m = x;
m = min(m,y);
m = min(m,z);
where min(a,b) is a < b ? a : b.
In general you can get the min of N numbers using N - 1 comparisons.
I find this easiest to understand for you.
a = 5;
b = 10;
c = 15;
//FIND MAX
if (a >= b && a >= c)
{
max = a;
} else
{
if (b >= c)
max = b
else
max = c;
}
//FIND MIN
if (a <= b && a <= c)
{
min = a;
} else
{
if (b <=c)
min = b;
else
min = c;
}
This one is just for fun and I believe the myabs function is actually supposed to be undefined behaviour, but I've only ever seen places that it works as expected.
double myabs(double x)
{
int64_t * p = (int64_t*)&x;
//clear sign bit
*p &= 0x7fffffffffffffff;
return x;
}
int main()
{
double x = 0, y = 1, z = 2;
//find max/min of first two numbers
double min = (myabs(x+y)-myabs(x-y))/2;
double max = (myabs(x+y)+myabs(x-y))/2;
//find max/min of previous max/min and third number
min = (myabs(min+z) - myabs(min-z))/2;
max = (myabs(max+z) + myabs(max-z))/2;
std::cout << min << ' ' << max << std::endl;
return 0;
}
Which outputs 0 2 correctly with 0 comparisons in total.
int a; int b; int c;
cin >> a >> b >> c;
if ( a > b && b > c ){ cout << a << " MAIXM \n" << b << " MEDIU \n" << c << " MINIM \n"; }
if ( b > a && a > c ){ cout << b << " MAIXM \n" << a << " MEDIU \n" << c << " MINIM \n"; }
if ( c > b && b > a ){ cout << c << " MAIXM \n" << b << " MEDIU \n" << a << " MINIM \n"; }
if ( a > c && c > b ){ cout << a << " MAIXM \n" << c << " MEDIU \n" << b << " MINIM \n"; }
if ( b > c && c > a ){ cout << b << " MAIXM \n" << c << " MEDIU \n" << a << " MINIM \n"; }
if ( c > a && a > b ){ cout << c << " MAIXM \n" << a << " MEDIU \n" << b << " MINIM \n"; }