I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried.
This is the sample code our prof showed us:
#include<iostream> //header file
using namespace std;
int num1, num2, sum = 0; // global variable
int addTwoNumbers(int a, int b)
{
sum = a + b;
return sum;
}
int main()
{
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum = addTwoNumbers(num1, num2);
cout << "\nThe sum is " << sum;
}
and as for the code I tried, I simply removed the "sum =" part. So,
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
and it still did the same thing. At least, from what I saw in the output. Is there any difference between the two behind the scenes or is there really nothing?
The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables.
The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely the code is better suited to teach you about functions. Let's see:
#include <iostream>
int addTwoNumbers(int a, int b)
{
int sum = a + b;
return sum;
// or simply:
// return a + b;
}
int main()
{
int num1, num2;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
int sum = addTwoNumbers(num1, num2);
std::cout << "\nThe sum is " << sum;
}
Now there are no hidden dependencies between main and addTwoNumbers (in the form of the global variables). This illustrates the procedure of passing data to function and getting data back from the function (parameters and return). Analyze this code and understand how it works. Play with it.
Now this won't work:
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
Because the only way data escapes the function is via its return. Since you discard the return value (you don't assign the result of calling the function) you don't have the result of the sum.
Now you could say you could do this instead:
int sum = num1 + num2;
cout << "\nThe sum is " << sum;
and ask "what's the point of functions?"
True for this particular small function there is no practical point of having it. You'll always write the num1 + num2 instead. However its simplicity makes it perfect as a teaching tool. You will soon see functions that get more complex and you will learn (either by being told or learning yourself the hard way) that writing code in very small chinks (functions) is better for both writing (breaking down the big problem in smaller problems) as well as for reading.
First of all, the reason why the sum is returning those values is that you are assigning the sum to itself. Basically, the addTwoNumber() returns the sum, and then you are assigning that value back into the sum. Hence, you don't need to assign the sum again in other words (sum = addTwoNumbers is unnecessary).
Yes, your code is working and it is actually better than the teachers in this case. However, your teacher may want to show you that you can use global variables like this. Typically you would store that value in another variable for later use if needed.
Related
In order to help us understand type casting in C++, we are required to perform addition of two int's as shown below. If we provide two int's as 4 and 5 respectively, the output should be 4 + 5 = 9.
I tried to follow this type casting tutorial without any success. Could someone please provide me a hint or something?
Quoting the assignment verbatim.
Your friend wrote a program called an adder. The adder is supposed to take two numbers inputted by a user and then find the sum of those numbers, but it’s behaving oddly.
Your first task is to figure out what is wrong with the adder. Your second task is to fix it.
Hint(s) to identify the problem
Try entering 1 and 1. You expect the output to be 2 but you get 11 instead. Similarly, if you enter 3 and 4, you expect the output to be 7 but you get 34. Remember, string concatenation also uses the + operator.
Hint(s) to identify the solution
The + operator functions differently based on the type of data that comes before and after it. What data types will cause the + operator to calculate a mathematical sum? What data type is present in the program now? How do you convert from one data type to another? Check out the Type Casting page for some idea
#include <iostream>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
string sum = num1 + num2;
cout << ( num1 + " + " + num2 + " = " + sum ) << endl;
return 0;
}
The problem with the code is that it is performing string concatenation when it needs to perform arithmetic addition instead. So you need to get the user's input into numeric variables, not strings. The assignment even alludes to this.
However:
Check out the Type Casting page for some idea
That is bad advice for this task, as you can't solve the problem with type casting.
You need to either:
Change the code to use int variables instead of string variables. This is the preferred solution, eg:
#include <iostream>
using namespace std;
int main() {
int num1;
int num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = num1 + num2;
cout << num1 << " + " << num2 << " = " << sum << endl;
return 0;
}
Otherwise, if you want to continue using string variables, you need to convert (not type cast!) their values into int values at runtime, and then convert back afterwards, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
string num1;
string num2;
cout << "Type the first whole number and then press Enter or Return: ";
cin >> num1;
cout << "Type the second whole number and then press Enter or Return: ";
cin >> num2;
int sum = stoi(num1) + stoi(num2);
cout << ( num1 + " + " + num2 + " = " + to_string(sum) ) << endl;
return 0;
}
if you typecast a character or string it get's converted into its equivalent ASCII value , either you need to use stoi or subtract from '0' for every digit position(a bit repeatitive work) go with stoi
I'm working on a school assignment, but I'm having trouble with a problem.
The problem is as follows:
"Write a function called divideIt that takes two integers, divides them, and returns the result as a float. Have this function skip division when it encounters an unacceptable value, and also retain the decimals. Do you know what to quit on?"
With the code I currently have, it divides and retains the decimal like the problem states, but I don't understand how to skip division. If I skip division because of an unacceptable value, what do I place in return? Should I just use null? Also, I'm not sure about the "Do you know what to quit on?" line.
My Code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
//Prototype
float divideIt(int num1, int num2);
int main()
{
int num1, num2;
float finalResult;
finalResult = divideIt(num1, num2);
cout << "Result: " << finalResult << endl;
}
//Header
float divideIt(int num1, int num2)
{
cout << "Simple Division\n" << "Input first integer: ";
cin >> num1;
cout << "Input second integer: ";
cin >> num2;
if(num2 == 0) //I wanted to make ASCII values unacceptable, but because they automatically translated into zeros, so I used that to my advantage on num2.
{
cout << "The second value was undefined or unacceptable." << endl;
}
return static_cast<float>(num1) / num2;
}
If I skip division because of an unacceptable value, what do I place in return?
You could return std::nanf ('not a number'):
if (num2 == 0)
return std::nanf ("");
There is also a corresponding std::isnan function.
Also, I'm not sure about the "Do you know what to quit on?" line.
Presumably, they mean 'what do you test for to decide that a value is unacceptable`. And I think we just did that.
Here is code:
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int score_one;
int score_two;
int score_third;
int final_score = score_one * score_two * score_third;
int main()
{
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
cout << "Your average score is: " << final_score << endl;
return 0;
}
Originally I am trying to get the average, by dividing the three scores, but that doesn't work, nor my arithmetic. It does not even multiple the variables. I use cin to get the numbers. Not sure what I am missing.
At the time that you assign to final_score, the values of the other scores are 0 (as you haven't assigned to them yet and they're global). You then read into the scores, but never update final_score!
You need to add this after you read in the third score:
final_score = score_one * score_two * score_third;
This will update final_score.
I would also suggest staying away from global variables. I'd also suggest initializing your variables when you declare them to avoid garbage values.
Also, you're not actually calculating the average! To do that, you'll need to add your values and divide by 3, since you have 3 values total. But you've declared final_score as an integer, so you won't be able to store the average with full precision. I'd suggest declaring as a double.
Taking into account all these changes, your code will look like:
int main()
{
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
final_score = (score_one + score_two + score_third) / static_cast<double>(3);
cout << "Your average score is: " << final_score << endl;
return 0;
}
This line should be moved after you cin to the variables on the right hand side of the equation
int final_score = score_one * score_two * score_third;
cout << "Your average score is: " << final_score << endl;
The variable isn't somehow recomputed when those variables are later set.
This part
int final_score = score_one * score_two * score_third;
should be inside main() after the last cin.
You have already received some answers, but I would like to offer another point of view.
It seems to me that you are used to a program like Excel, where you can set a cell to a formula (like the product of 3 other cells), and then, whenever you change any of those cells, the product is immediately updated, automatically. C++ (and, in general, programming languages) does not work like that. When you write a line like
int final_score = score_one * score_two * score_third;
you are not setting a rule, which will cause the value to be recalculated. The approach is different!
A program is executed from the beginning to the end (in practice, from the top to the bottom), and every time you assign a value to a variable (like final_score), what you are doing is reading the current value of the input variables (here, your three scores), calculating the result (which in this case is undefined, because you haven't initialised any of the scores), and assigning it to the variable, just this time. That's it. If you later change the scores, the change will not be reflected automatically on your final_score. If you want the value to be recalculated, you have to do it manually. That's why you have to move that line after the lines that read the input from the user, as the others have said.
You really should not use global variables, see here on why you should avoid them.
Next, instead of doing using std::cin etc. Just get used to typing it.
Lastly, use appropriate flags in your compiler to help you catch mistakes. The compiler is meant to be your friend. A good compiler would tell you,
int score_one;
int score_two;
int score_third;
int final_score = score_one + score_two + score+third / 3;
Is not initialized. To really achieve what you are thinking, you could use a function that will return a double. And that would look something like
double doAverage(int score1, int score2, int score3)
{
return (score1 + score2 + score3) / 3.0;
}
But that will probably come later in your coding practices.
#include<iostream>
int main()
{
// Delare your variables here and initialize them to zero.
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
std::cout << "What was your first score?" << std::endl;
std::cin >> score_one;
std::cout << "What was your second score?" << std::endl;
std::cin >> score_two;
std::cout << "What was your third score?" << std::endl;
std::cin >> score_third;
// Take all scores and divide it. This is the important part since
// order matters in your code.
final_score = (score_one + score_two + score_third) / 3.0;
std::cout << "Your average score is: " << final_score << std::endl;
return 0;
}
You're on the right track, you just have to look at your code and read it outloud to yourself. One of the best things you can do in programming is starting from the top and saying, "Okay, where does this break?" And follow it line by line making sense of it.
I am trying to write a program to find the sum of multiple amounts and the average of the amounts given. It doesn't seem to be working but I don't know if the issue is within my compiler of if it is my code. This is what i have so far.
#include <iostream>
using namespace std;
int main()
{
int n, i;
sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
you didn't declare "num" array anywhere, also your data declarations are missing types for sum and average. They should be floats. BTW float literals need f on the end:
float num = 0.0f; // hold the current number
float sum = 0.0f; // store the sum so far
float average = 0.0f; // store the average at the end
When reading store cin straight into num, with no [i] subscript:
cin >> num;
sum += num;
This will fix the main errors. Again, read the error messages carefully, they will always tell you the line number and a message about the type of error, you just need to learn to decipher what the messages mean.
forget about the array for now, as that would need dynamic memory allocation, since the size is inputted by the user, and you should get basic program flow and variables worked out before delving into that.
"unknown symbol" or similar means you used a name, but you never declared what type of thing that was, so you forgot to declare a variable or didn't declare a type for it (just throwing a name out doesn't tell the compiler whether it's meant to be the name of e.g. a variable, a function, a class or whatever. The compiler isn't a mind reader).
I have made a simple program in C++ and this is the code:
#include <iostream>
using namespace std;
int main()
{
int number;
int square;
number = 5;
square = number * number;
cout << "The square is ";
cout << square;
return 0;
}
what it does is basically taking the integer "5" and get the square value on the screen and so on...
my question is:
how can I make the program take any value from the user instead of storing a value in the memory?
than Q.
Your code makes use of cout to print. C++ makes cin available for input from the console:
int x;
cin >> x;
"An example is worth a thousand words..."
Well cout takes some var. from memory and prints it out on the screen, right?
Well, cin does the exact opposite, it takes in some value from the keyboard and puts it in your memory..
You have to take in the value with the help of cin command, like this:
int a; //lets say you have a variable
cout << "Enter a value here: "; //prompts the user to enter some number
cin >> a; //this line will allow the user to enter some value with the keyboard into this var.
int square = a * a;
cout << "The square is: " << square;
Hope it helps...
Just replace:
number = 5;
with:
cout << "What's the number? ";
cin >> number;
You already know how to use cout to generate output, this simply uses cin to retrieve input.
Keep in mind that, while this may be okay for small test programs or learning, data input in real programs tends to be a little more robust (such as if you enter the string xyzzy when it's trying to input an int variable).