Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
im really new to programming and really want some help:). I have made a program that finds the average out of 5 numbers. I was wondering i i could get some help to make this program more efficient. Im using c++.
#include <iostream>
using namespace std;
int main()
{
int num1;
int num2;
int num3;
int num4;
int num5;
int Anum;
int AAnum;
cout << "pick your first number";
cin >> num1;
cout << "pick your second numer";
cin >> num2;
cout << "pick you third number";
cin >> num3;
cout << "pick your forth number";
cin >> num4;
cout << "pick you fifth number";
cin >> num5;
Anum = num1 + num2 + num3 + num4 + num5;
AAnum = Anum / 5;
cout << "the average number is " << AAnum;
return 0;
}
Welcome to programming! How about something like this?
#include <iostream>
using namespace std;
int main() {
double average = 0.0;
const int num_to_average = 5;
for (int i = 0; i < num_to_average; ++i)
{
cout << "Pick number " << i << ": ";
double num;
cin >> num;
average += num;
}
average /= num_to_average;
cout << "the average number is " << average << end;
return 0;
That way the loop does all the heavy lifting for you so instead of 5 separate variables, you can add them all into a single variable (and then computes the average at the end).
Edit: included #tadman's double instead of float suggestion.
The runtime for this program is going to be as good as it's going to get. Each statement will be executed in O(1) time and the runtime performance probably isn't going to improve unless you change the way you prompt for the numbers (i.e. "Enter 5 numbers separated by spaces" and then do cin >> num1 >> num2 >> ...)
Now if you want a better way to write your algorithm, try an array.
At the top:
#define NUMBEROFNUMBERS 5
int inputArray[NUMBEROFNUMBERS];
for(int i = 0; i < NUMBEROFNUMBERS; i++) {
cout << "Pick #" << i + 1 << ": ";
cin >> inputArray[i];
}
And then calculate your average by looping through the array and outputting the result.
It's a short and elegant way to do that if you exactly know the elements of your array.
#include<iostream>
int main()
{
double result = 0;
const double myFirstArray[5] = { 5, 10, 22, 44, 5 };
for (int i = 0; i < std::size(myFirstArray); i++) {
result+=myFirstArray[i];
}
std::cout << "Average: " <<result/ std::size(myFirstArray);
return 0;
}
Related
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 2 years ago.
Improve this question
#include <iostream>
using namespace std;
int funky(int stuff)
{
int number;
number = 10;
cout << "Please enter a number \n";
cin >> number;
stuff = number + 777;
cout << "The result is " << stuff << endl;
return 0;
}
int main()
{
int num1, num2;
funky(num1);
funky(num2);
cout << num1 << " and " << num2;
return 0;
}
I am trying to learn to use functions in C++, but i cannot figure out why this code returns a very long negative number at the end . can someone tell me why num2 returns a very long number? it doesnt make sense to me at all
Apparently, your intention was to assign stuff inside the function and use as num1 and num2 in main(). To do it, you need to change your parameter type from int to int&, i.e. pass by reference. Your function declaration should be int funky(int& stuff).
The way you defined the function, variables num1 and num2remain uninitialized, that's why cout << num1 << " and " << num2; is printing garbage.
There are a few things that are wrong with your code . For one, you do not need a value-returning function. You could instead use void.
You also are getting Undefined Behavior by not initializing your variables int num1 and int num2.
Now, an alternative to your problem would be using void. (If you only need two numbers.) Other than that I suggest using #Eugene's answer.
Replace:
int funky(int stuff) to void funky(int stuff).
For Example:
#include <iostream>
using namespace std;
void funky()
{
int num1 = 0;
int num2 = 0;
cout << "Please enter a number \n";
cin >> num1;
int Res1 = num1 + 777;
cout << "The result is " << Res1 << endl;
cout << "Please enter one more number \n";
cin >> num2;
int Res2 = num2 + 777;
cout << "The result is " << Res2 << endl;
cout << num1 << " and " << num2;
}
int main()
{
funky();
return 0;
}
I want to use C++ to make a calculator, so that I can enter an expression and calculate the result.
For example,
input
(5.2+4)*ln3.4+sin3
output
11.39985
The problem is that I don't know how to separate the number and the operator from the string. For the length of the operands and numbers are different.
Is there any good way?
That's actually a much harder problem than it seems at first, and I say that from experience.
If you want an example of how to do it completely from scratch, here is a question where I posted an example I was working on. It is certainly not complete, but links to a great Java article (actually, probably the best article) on Pratt parses, which in my opinion is the best way to parse expressions. My question was on my attempt to port the Java code found there to C++. You can see a problem I ran into there.
You will also need to know some theory on lexers, and learn how to create tokens, which I don't ask about there.
The point is, you have a lot of research ahead of you, if you want to start from scratch, or even if you want to just know the theory of what's going on, but I certainly encourage you to try it if you don't have a deadline for it.
Use a library such as exprtk.
I'm going to assume that you're a total noob which leads me to advise you to always Google for a library that solves your problem.
I programmed the calculator using function ,loops, switch case.
it can also be programmed with using if else statement but then it will be a simple one. I had made it like a real calculator it can take unlimited argument, while the other takes only 2 numbers as argument.
#include <iostream>
#include <conio.h>
using namespace std;
int add()
{
int total, a, sum = 0;
cout << "how much number you want to calculate :";
cin >> total;
for (int i = 1; i <= total; i++)
{
cout << "enter number " << i << "for +" << endl;
cin >> a;
sum = sum + a;
}
cout << "total addition is:" << sum;
return 0;
}
int subtract()
{
int sub = 0, a, b[20], total;
cout << "how much number you want to calculate :";
cin >> total;
cout << "enter number 1 for - : \n";
cin >> a;
a = -a;
for (int i = 1; i < total; i++)
{
cout << "enter number " << i << "for - :" << endl;
cin >> b[i];
sub = sub - a - b[i];
a = 0;
}
cout << "HENCE THE SUBTRACT IS :" << sub;
}
int divide()
{
float h;
float a;
float b;
cout << "enter number 1 : ";
cin >> a;
cout << "enter number 2 : ";
cin >> b;
h = a / b;
cout << "division is :" << h;
}
int multiply()
{
int a[20];
int total, multi = 1;
cout << "how much number you want to multiply\n";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "enter number to multiply\n";
cin >> a[i];
multi = multi * a[i];
}
cout << "multiplicaion is : " << multi;
}
int main()
{
int num1[20], num2[20];
char sign;
cout << "chouse a sign"
"\npress this for executing the action +"
"\npress this for executing the action -"
"\npress this for executing the action X"
"\npress this for executing the action /\n";
cin >> sign;
switch (sign)
{
case '+':
add();
break;
case '-':
subtract();
break;
case '*':
multiply();
break;
case '/':
divide();
break;
default:
cout << "chouse something";
break;
}
return 0;
}
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)
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to know which program will be more efficient (memory usage) and why? The first program has lesser variables but more computations. Can you really say? All the program does is find the largest of 3 numbers.
#include <iostream>
using namespace std;
int max(int num1, int num2, int num3) {
if((num1 > num2) && (num1 > num3)) {
return num1;
} else if((num2 > num1) && (num2 > num3)) {
return num2;
} else {
return num3;
}
}
int main() {
int num1, num2, num3;
cout << "Enter first number" << endl;
cin >> num1;
cout << "Enter second number" << endl;
cin >> num2;
cout << "Enter third number" << endl;
cin >> num3;
cout << "Maximum value: " << max(num1, num2, num3) << endl;
return 0;
}
OR
#include <iostream>
using namespace std;
int maximum(int num1, int num2, int num3) {
int largest;
if (num1 > num2) {
largest = num1;
} else {
largest = num2;
} if (num3 > largest) {
largest = num3;
} return largest;
}
int main() {
int number1, number2, number3, max;
cout << "Enter the first number: ";
cin >> number1;
cout << "Enter the second number: ";
cin >> number2;
cout << "Enter the third number: ";
cin >> number3;
max = maximum(number1, number2, number3);
cout << "The maximum value is " << max << endl;
return 0;
}
Also, I want to know if it is bad to give the same variable names in the main() and the max() functions? (In program 1)
Inspect the assembly of an optimizing compiler to reach a conclusion
See e.g. this on godbolt.com ¹
The other on godbolt too: ¹
Looks like maximum is more efficient using these optimization flags on GCC
¹ appears the godbolt permalinks might not be working. It's easy to paste the snippets yourself. I use rand() and return to avoid the compiler optimizing it all out
There are different flavors of efficiency. One program can make more efficient use of memory, while another executes faster. So the first step is to be more precise on the type of efficiency you are after.
That said, a few bytes here and there are just not even worth considering on virtually all computer platforms. So simplifying the code to run faster, even if a little more memory is used, is generally a good approach.
There is no problem with using the same variable names in different functions, unless they cause confusions.
It is best to go down the avenue of writing readable code in the first instance.
If performance is an issue the do some analysis. Always remember the 80/20 rule http://en.wikipedia.org/wiki/Pareto_principle
So to answer your question I do not know as it depends on the OS/compiler options.
I would personally write it like this:
int max(int a, int b)
{
return (a > b ? a : b);
}
int main()
{
int number1, number2, number3;
cout << "Enter the first number: ";
cin >> number1;
cout << "Enter the second number: ";
cin >> number2;
cout << "Enter the third number: ";
cin >> number3;
cout << "The maximum value is " << max(number1, max(number2, number3)) << endl;
return 0;
}
The 2nd algorithm, except for the "double", is bound to be faster because is uses less conditional branches - always 2, while the 1st algorithm needs at least 2 conditional branches, and sometimes more.
You might consider to omit an assignment:
int max(int num1, int num2, int num3) {
if(num1<num2) num1=num2;
if(num1<num3) num1=num3;
return num1;
}