C++ a program to calculate the greatest profit [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This program accepts input of the everyday prices of a good and then calculates the greatest profit. And the list of prices will end with -1.
for example, if I input 20,30,10,50,-1 , it means at the first day the good is $20,in the second day is $30,etc. The greatest profit output will be $40 since I could buy it on the third day at $10 and sell it in the fourth day at $50.
This is a school assignment and the teacher do not allow me to use array.
Now my program is fine except in this case e.g.
if I input 20 30 10, the greatest profit will be $(30-10) how could I fix it so if will not store the number after the maximum number e.g. 10 as the minimum number? Or any other codes to fulfil the purpose of my program?
#include<iostream>
using namespace std;
int main() {
int c(0), r(0), n1(0), min(0), max(0), l(0), s(0);
cout << "Please enter the prices: ";
while (n1 != -1) {
cin >> n1;
if (min == 0 && n1>0)
{
min = n1;
}
c++;
if (n1 <= 0 && n1 != -1) { cout << "Invalid. Input again. Please make sure it's a positive number!" << endl; r++; }
else {
if (n1<min && n1 != -1) { min = n1; s++; }
if (n1 >= max && (c - r)>(s + 1)) { max = n1; l = c; }
cout << c << s + 1 << l << endl;
}
}
cout << max << min;
cout << endl << "Largest amount earned: " << (max - min) << endl;
return 0;
}

You can simply calculate maximum profit by using the lowest price from now and not in the future.
#include <iostream>
int main(void) {
int lowestPrice = -1;
int highestProfit = 0;
int price, maxProfit;
while (std::cin >> price) {
if (price < 0) break;
if (lowestPrice < 0 || price < lowestPrice) lowestPrice = price;
maxProfit = price - lowestPrice;
if (maxProfit > highestProfit) highestProfit = maxProfit;
}
std::cout << highestProfit << std::endl;
return 0;
}

Related

I need to know how to add using an increment value up to a certain number in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having a hard time trying to add the starting value with the increment value up until it reaches the ending value or it cant add again because it would exceed the max value(the end value).
Ok I am just going to get straight to it, here is my assignment.
In this assignment, you will complete a C++ program that sums up the integers in a range of values and prints the result. This will be done two different ways: using a while loop and using a for loop.
For this assignment, you have more freedom in choosing the local variables that you need to declare and in figuring out what source code to write. However, your program needs to follow the coding standards of this course and fulfill the software requirements described in the next section.
Below is an example execution of the program. In this case, the program added up the numbers 8, 25, 42, 59, 76, 93, and 110. Your program shall follow the same format shown below for prompting the user and printing the results.
Enter a starting integer value: 8
Enter an ending integer value: 121
Enter a positive increment: 17
Sum (using a while loop): 413
Sum (using a for loop): 413
Here is what I have for code so far
#include <iostream>
using namespace std;
int main(){
//while loop sum
int sumw = 0;
//for loop sum
int sumf = 0;
//starting integer
int nums;
//ending integer
int nume;
//increment integer
int numi;
cout <<"Please enter a starting value: " << endl;
cin >> nums;
cout <<"Please enter an ending value: " << endl;
cin >> nume;
cout <<"Please enter a positive increment value: " << endl;
cin >> numi;
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
for (int i = 1; i <= numi; i++){
sumf =+ numi;
}
cout << "Sum(using for loop): " << sumf;
return 0;
}
If someone could help me with this that would be great!!! Thank you!!
This is probably what you are looking for
for (int i = nums; i <= nume; i = (i + numi)){
sumf += i;
}
Start with nums until you are less than or equal to nume and increment i in steps of numi i.e. i = i + numi
Additionally, you can combine:
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
to
if (numi <= 0 || nums > nume){
cout << "Error ";
return 0;
}
Assumed the starting number as greater than or equal to 1(>=1).
Using while loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
totalSum = startingNumber;
while ((startingNumber + positiveIncrement) <= endingNumber)
{
startingNumber += positiveIncrement;
totalSum += startingNumber;
}
cout << "Total Sum = " << totalSum;
return 0;
}
Using for loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
for ((totalSum = startingNumber);((startingNumber + positiveIncrement) <= endingNumber);(startingNumber += positiveIncrement))
{
totalSum += (startingNumber+positiveIncrement);
}
cout << "Total Sum = " << totalSum;
return 0;
}
See definition of for statement in a good reference:
for ( initializer, terminating condition, increment)
The third parameter is the increment.
You could do something like:
for (int i = nums; i < nume; i = i + numi)
{
}
Inside the loop, you'll have figure out what you need to sum and how to do it.
welcome to the world of computer science and programming :)
several points:
it is unclear what it is you need help with, posting your assignment is not a good way to get help. with your next question, try using this as a guide line on how to ask a question: https://stackoverflow.com/help/how-to-ask
here is a list of operators in C++, and how to use them, https://www.geeksforgeeks.org/operators-c-c/ you will notice =+ is not there, becuase it is not a valid operator.
what you do have, is:
“+=”:This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the
value on right and then assigns the result to the variable on the
left.
Example: (a += b) can be written as (a = a + b)

CODE is not executing in c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
TASK 2 remains un-executed. Task 1 works fine, I input the yield values of the cows; but then the code stops running. A warning says that Herdtotalweek may be uninitialized. But I don't know how to fix that. There are no other warnings or errors.
#include <iostream>
#include <string>
using namespace std;
int main() { //Task 1
int Herdsize;
int Day;
float MilkYield1;
float MilkYield2;
int count;
cout << "Please input herd size" << endl;
cin >> Herdsize;
while (Herdsize < 1 || Herdsize > 900) {
cout << "Please re-input herdsize between 1 and 900" << endl;
cin >> Herdsize;
}
int CowID[Herdsize + 1];
float DailyYield[Herdsize * 7];
float WeeklyYieldpercow[Herdsize * 14];
for (count = 1; count < Herdsize + 1; count++) {
cout << "Input 3 digit cow id ";
cin >> CowID[count];
while (CowID[count] < 1 || CowID[count] > 999) {
cout << "Please re-input cow a 3 digit cow id " << endl;
cin >> CowID[count];
}
for (Day = 1; Day < 8; Day++) {
cout << "Please input first milk yield of cow,day";
cout << Day;
cout << endl;
cin >> MilkYield1;
cout << "Please input second milk yield day:";
cout << Day;
cout << ", if there is a second yield if not enter 0";
cout << endl;
cin >> MilkYield2;
}
DailyYield[((count - 1) * 7) + Day] = MilkYield1 + MilkYield2;
WeeklyYieldpercow[count] = WeeklyYieldpercow[count] +
DailyYield[((count - 1) * 7) + Day];
}
// TASK 2
int count2 = 1;
float Herdtotalweek;
float Averagevolume;
for (count = 1; count2 < Herdsize + 1; count++) {
Herdtotalweek = Herdtotalweek + WeeklyYieldpercow[count];
}
Averagevolume = Herdtotalweek / Herdsize;
int Herdtotalweekwhole = int(Herdtotalweek + 0.5);
int Averagevolumewhole = int(Averagevolume + 0.5);
cout << "Total weekly volume=";
cout << Herdtotalweekwhole;
cout << "Average volume =";
cout << Averagevolumewhole;
}
instead of float Herdtotalweek; try using float Herdtotalweek = 0; ?
also, in your second for statement, instead of for (count=1;count2<Herdsize+1;count++) try for (count=1;count<Herdsize+1;count++) (you were using count2 instead of count, which was probably a copy/paste error)
The for loop after task2 never completes. It is an infinite loop as you are not updating count2.

C++ - Check if there are no even numbers in given interval

I have to write a program on C++ which finds all even numbers in range given by user. Here's the code I have written so far:
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
void main() {
int m, n, j = 1; // m and n- numbers entered by user, j- product of all even numbers in interval
char atbilde; // A letter entered by user, of which system decides wether to continue or to stop programme
do {
j = 1;
cout << "Enter the min number of interval! ";
cin >> n;
cout << "Enter the max number of interval! ";
cin >> m;
if (n > m) { // Detects wether „n” is larger than „m”
cout << "Max number of interval has to be larger than min number!";
do { // If max number is larger than min number, screen is cleared
cin.clear();
cin.ignore();
cout << "Enter the numbers again!";
cout << "\n Enter the min number of interval! ";
cin >> n;
cout << "\n Enter the max number of interval! ";
cin >> m;
}
while (n > m);
}
cout << "Even numbers in given interval: ";
for (; n <= m; n++)
{
if (n % 2 == 0)
{ // Detects, wether there are even numbers in given interval
if (n != 0) {
cout << n << " ";
j *= n;
}
if ((n == m) && (n % 2 != 0)) {
j=0;
}
}
}
cout << "\n The product of found even numbers: " << j << " ";
cout << "\n Repeat? (Y/N) ";
cin >> answer;
system("cls");
}
while (tolower(answer) != 'n');
}
But I have a small problem, so I can't get the program 100% done because of the problem.
Like, user enters range, whose min and max number is the same and it's odd. In that case program has to print out a sentence "there were no even numbers in interval" in place of "The product of found even numbers:". I have searched the solution in internet, but haven't found it.
I hope you'll know the right solution.
Some hints to help you along the way: If there was no even number in the range, you will not enter into the loop. What will j be then? How do you react on that value?
I tried to fix your code, I did the best I could from what I understood you were tring to do.
I cleaned it up, fixed spelling and grammer, I deleted unnecessary stuff, I also made it more compact and nice to look at.
#include <iostream>
int main() {
int max=0, min=1, sum=0; product = 1, amount = 0; // max, min - entered by user, product - product of all even numbers in interval, sum - sum of all even numbers in interval. amount - amount of even numbers in interval
char x=Y; // Entered by user to know if to quit or continue to continue.
while ((x == Y) || (x == y))
{
while (min > max) { // System detects whether minimum is bigger than maximum
cin.clear(); // Clears screen so if this part runs again it wouldn't get messy.
cin.ignore();
cout << "Max has to be larger than min!";
cout << "\n Enter the min number of interval! ";
cin >> min;
cout << "\n Enter the max number of interval! ";
cin >> max;
}
for (; min <= max; min++)
{
if (min % 2 == 0)
{
sum+=n;
count++;
product*=n;
}
}
if (count == 0)
{
product=0;
cout << "There are no even numbers in interval!";
}
else
{
cout << "\n The amount of the even numbers in interval: " << amount << ",the product of the even numbers: " << product << ",the sum of the even numbers: " sum << "\n\n";
}
cout << "Repeat? (Y/N) ";
x=getchar;
system("cls");
}
return 0;
}

While & If loop expected error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I need to write a program that would read in numbers from the keyboard, compute the average of the numbers, and display it. The sequence of numbers are to be terminated with a zero.
Here is my code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int count;
double number, sum, average;
count = 0;
sum = 0;
average = 0;
cout << "\nEnter Number (0 to terminate): ";
cin >> number;
while(number! = 0.0)
{
sum = sum + number;
count = count + 1;
cout << "\nEnter Number: ";
cin >> number;
}
if(count! = 0.0);
{
average = sum/count;
}
cout << "\nThe average of the" << count << "number is" << average << endl;
return 0;
}
However, I am getting two errors:
expected ')'
and
if statement has empty body
if(count! = 0.0);
Get rid of semicolon
There are three errors:
The != operator is mis-spelled ! = in two places.
The if has a semicolon after the closing parentheses.
Please do not insert any whitespaces between your comparators.
You wrote (number! = 0.0), but the correct one should be: (number != 0.0).
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int count;
double number, sum, average;
count = 0;
sum = 0;
average = 0;
cout << "\nEnter Number (0 to terminate): ";
cin >> number;
while(number != 0.0)
{
sum = sum + number;
count = count + 1;
cout << "\nEnter Number: ";
cin >> number;
}
if(count != 0.0)
{
average = sum/count;
}
cout << "\nThe average of the" << count << "number is" << average << endl;
return 0;
}
You have a semi-colon (;) right after the if statement. Remove it :)
if(count! = 0.0)
while(number! = 0.0) should be while(number != 0.0)
and
if(count! = 0.0) should be if(count != 0.0)
Note != is an operator but ! = is not - attention to the details!

Main not returning 0 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
So I have this exercise, I need to ask the user for 2 inputs (grades >0 <10) and then I have to print the average and then ask the user if they want to insert more grades 1-yes 2-no; if it's 1 then the program runs again, if it's 2 the program quits. But I'm having trouble to make the program quit.
// ConsoleApplication7.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "stdafx.h"
int main()
{
using namespace std;
float n1;
float n2;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
int g;
cin >> g;
if (g = 1) {
main();
}
else if (g = 2) {
return 0;
}
}
return 0;
}
The problem is to test for equality you need two =, not one so your two checks are actually assigning values to g not comparing with g
if (g == 1) {
main();
}
else if (g == 2) {
return 0;
}
Any modern compiler should have given you a compiler warning about that assignment. You should always try to pay attention to compiler warnings.
Also your logic of
if ((n1 || n2) > 10)
and
else if ((n1 || n2) < 0)
is incorrect, but I will leave it to you to figure out what is wrong (this is homework afterall).
Lastly you may want to look in to doing a do-while loop instead of calling main() over and over.
Your ifcondition is wrong:
if (g = 1)
sets g to 1, and is always true. What you want to do is:
if (g == 1)
And as Scott said in his comment, you shouldn't call main but rather use a while loop.
Please look at these modifications.
float n1;
float n2;
int g = 1;
while (g != 2)
{
cout << "Please enter two grades: " << endl;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
cin >> g;
}
}
return 0;
}
Also note that I moved using namespace outside of main.