Program Efficiency & Readability [closed] - c++

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;
}

Related

Advice on repairing the errors in this C++ void function for a homework problem [closed]

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 1 year ago.
Improve this question
I am a college student looking for help on picking up the messy bits in this code I've worked on for class. I believe there's an error in this code that CodeBlocks is finicky with.
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void func1();
void func2();
int main()
{
int num1, num2;
double num3;
int choice;
cout << fixed << showpoint << setprecision(2);
do
{
func1();
cin >> choice;
cout << endl;
if (choice == 1)
{
func2(num1, num2, num3);
cout << num1 << ", " << num2 << ", " << num3 << endl;
}
}
while (choice != 99);
return 0;
}
void func1()
{
cout << "To run the program, enter 1." << endl;
cout << "To exit the program, enter 99." << endl;
cout << "Enter 1 or 99: ";
}
void func2(int num1, int num2, double num3)
{
cout << "input 2 bumners a and b";
cin >> num1;
cin >> num2;
if (num1 >= num2){
num3 = pow(num1, num2);
}
else if (num1 < num2){
num3 = pow(num2, num1);
}
else if (num1 != 0 && num2 == 0){
num3 = sqrt(abs(num1));
}
else if (num2 != 0 && num1 == 0){
num3 = sqrt(abs(num2));
}
else if (num1 == 0 && num2 == 0){
num3 = 0;
}
}
Your func2() accepts parameters by value; whatever you do to those parameters is not visible outside of that function (when it returns). You should pass by reference.
void func2(int& num1, int& num2, double& num3)
This code isn't too hard to debug. I just tried compiling it, and I was told the error existed at line 6. Here's what you have to do:
Make sure you put in the correct parameters when you declare void func2() at line 6. It should have these parameters: (int num1, int num2, double num3).
The parameters must be the same when you declare the function and when you define the function, otherwise the defined function is never declared.

Writing program better [closed]

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;
}

Why does this code return a long number at the end? (c++) [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 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;
}

c++ to the top of the program

I have to write a program in C++ and am unsure on how to return to the top after an error. For example, I have the user input 2 integers, if the 2nd integer is smaller than the first i have an error stating pls enter in a number larger than the first, but from here I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
if (num1 > num2)
cout << "You second number must be larger than your first number." << endl;
Problem
I do not know what code to enter to have the question be asked again / send to the beginning / top of the code?
Well almost always when you have that situation, you will use a while loop. This loops over the block if the condition is true.
#include <iostream>
#include <string>
int main()
{
int num1;
int num2;
do {
std::cout << "What is first num? ";
std::cin >> num1;
std::cout << "What is second num? ";
std::cin >> num2;
} while (num1 < num2);
}
Basically, what happens is first you have to declare the integers num1 and num2. Then you have a do while loop! Well this executes the code in the do block before checking for the condition! First we ask for the two user inputs, then we check for the condition. Let's look at the condition carefully:
while(num1<num2)
This means if the first number the user entered is less than the second number, loop through the while block. The while block does the same thing until num1 becomes greater than num2!
Here is a compiled version (GCC).
Additional Exercises
icodecool
Tutorial
CS_PDF
References
cpprefrence
MSDN
Flow Control Tutorial
Glossary:
do-while loop:
Executes a statement repeatedly until the value of the expression becomes false. The test takes place after each iteration.
Syntax
attr(optional) do statement while ( expression ) ;
attr(C++11) - any number of attributes
expression - any expression which is contextually convertible to bool. This expression is evaluated after each iteration, and if it yields false, the loop is exited.
statement - any statement, typically a compound statement, which is the body of the loop
Try:
cout << "Enter number 2: ";
cin >> num2;
while (num1 > num2) {
cout << "You second number must be larger than your first number." << endl;
cout << "Enter number 2: ";
cin >> num2;
}
int num1 = 0, num2 = 0;
do
{
cout << "num1: ";
cin >> num1;
cout << "num2: ";
cin >> num2;
if(num2 < num1)
cout << "error num2 is smaler than num1" << endl;
}while(num2 < num1);

C++ - Loop function or program forever? [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 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here