I'm new to programming so please write your answer as basic as possible. I made a simple calulator in C++. It's supposed to add 2 numbers but for some reason the output is always 16, no matter the numbers. Can someone explain this to me? This is the code:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum = a + b;
cout << "Enter a number: ";
cin >> a;
cout << "Enter a second number: ";
cin >> b;
cout << sum;
return 0;
}
But, when i do this (creating the int sum first and then assigning it later), it works:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum;
cout << "Enter a number: ";
cin >> a;
cout << "Enter a second number: ";
cin >> b;
sum = a + b;
cout << sum;
return 0;
}
int sum = a + b;
Is not an algebraic rule, it is a statement evaluated at that point in the sequence of statements.
Just do it after your inputs.
In the first example, you're initializing the sum variable before the initialization of a and b so before initialization, the a and b will contain some garbage value and that's why you're getting output 16 the garbage value can be anything. Just initialize your sum variable after a and b variables have some user inputted values.
And if you're doing some addition then it's a good practice to initialize your result variable(sum) with zero sum=0 so it also doesn't contain any garbage values
When you use
int sum = a + b;
sum initilized to whatever a + b evaluates to. The value of sum does not change when you set the values of a and b after that statement. In your case, neither a nor b has been initialized before that statement. Hence, it causes undefined behavior.
The second version of your program works correctly since you are assigning a + b to sum after a and b have been assigned values from user input.
Related
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.
I try to obtain the minimum of two integers, real numbers, strings, and integer arrays by implementing functions that obtain similar treatment results as function overloading.
So I write code like this
#include <iostream>
#include <cstring>
using namespace std;
int GetMin(int a, int b);
double GetMin(double a, double b);
char* GetMin(char* a, char* b);
int GetMin(int* arr, int size);
int main()
{
int num1, num2;
double num3, num4;
char s1[30], s2[30];
int arr[10];
cout << "Enter two integers : ";
cin >> num1 >> num2;
cout << "The minimum value is " << GetMin(num1, num2) <<"\n";
cout << "Enter two real numbers : ";
cin >> num3 >> num4;
cout << "The minimum value is " << GetMin(num3, num4) <<"\n";
cout << "Enter two strings : ";
cin >> s1 >> s2;
cout << "The minimum value is " << GetMin(s1,s2) <<"\n";
cout << "Elements of an Array : ";
cin >> arr[10];
cout << "The minimum value is " << GetMin(arr[10], 10);
}
int GetMin(int a, int b)
{
if (a > b) return b;
else return a;
}
double GetMin(double a, double b)
{
if (a > b) return b;
else return a;
}
char* GetMin(char* a, char* b)
{
if (strcmp(a, b) < 0) return a;
}
int GetMin(int* arr, int size)
{
int min = arr[0];
for (int i = 1; i<size; i++)
if (arr[i] < min)
min = arr[i];
return min;
}
Here's the desired result.
Enter two integers : 10 20
The minimum value is 10
Enter two real numbers : 56.84 120.26
The minimum value is 56.84
Enter two strings : orange apple
The minimum value is apple
Elements of an Array : 41 67 34 25 0 54 98 21 58 62
The minimum value is 0
I got this error message.
Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.
It is wrong to use cin to assign values to the entire array. The more common method is to use the for or while structure. I recommend you to read this issue to understand input and output.
Also, have you observed warnings in your program?
Warning C6201 Index '10' is out of valid index range '0' to '9' for
possibly stack allocated buffer 'arr'.
The index of the array arr[10] should be arr[0]~arr[9]. About C6385 you should read this document.
char* GetMin(char* a, char* b)
{
if (strcmp(a, b) < 0) return a;
}
It is best not to use the parameters of the function as the return value. The common method is to define a variable to store the parameters to be returned.
You have undefined behaviour, caused by this attempt to read into an index beyond the array:
cin >> arr[10];
I think you are trying to read the whole array in, but that is not possible like that. And if it were (e.g. by overloading >>) it would be using arr instead of arr[10].
You can solve this by overloading >> (though I suspect that to be unnecessarily complex...). Or by reading in with a loop.
You can't input to an array like
cin >> arr[10];
Instead that inputs a single value into the eleventh element of your ten-element array (leading to undefined behavior).
You need to use a loop to input each element one by one:
for (unsigned i = 0; i < std::size(arr); ++i)
{
std::cout << "Enter input for element " << i + 1 << ": ";
std::cin >> arr[i];
}
On an unrelated note, I recommend you learn more about the standard containers like std::array and std::string. They will make your life as a C++ programmer much simpler.
Please consider the following code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int a, b;
cout << "Enter two integer: ";
cin >> a >> b;
if (a > b) {
int temp = a;
a = b;
b = temp;
}
cout << a << "<=" << b << endl;
}
The above code yields the minimum of the two inserted numbers. Can anyone explain how the if block works?
It's the idiomatic way of swapping two numbers.
There are more efficient ways: to exploit those use std::swap instead.
(The statement int temp=a; sets the variable temp to the value of a. The statement a=b; sets a to the value of b. Finally, b=temp; sets b to temp which was the original value of a. The overall effect therefore is to exchange the values of a and b.)
This program does the addition of two integers, the program works perfectly (the exercise asks me to use constructor and past integers on it ).
But on the constructor, if I initialize num1 = nbre1 instead of nbre1 = num1the program doesn't work.
Any explanation about the order ?
#include <iostream>
int main(){
class op{
public :
int nbre1, nbre2;
op(int num1, int num2){
nbre1=num1;
nbre2=num2;
std::cout<<"numbers initialized";
}
int add(){return nbre1+nbre2 ;}
};
int n1;
int n2;
std::cout<<"Enter the first integer >> ";
std::cin>>n1;
std::cout<<"\n";
std::cout<<"Enter the second integer >> ";
std::cin>>n2;
op addition(n1,n2);
std::cout<<"The sum of the two numbers is >> " << addition.add();
return 0;
}
The C++ assignment operator = sets the left hand value equal to the right hand value. The statement num1 = nbre1 sets num1 to be the uninitialized value in nbre1. If nbre1 was previously initialized, the statement sets num1 to that value but since num1 isn't being used anywhere else in that function, it essentially does nothing.
The loop in the function require() takes 3 conditions, a > b or "a" or "b" aren't digits. Even when I don't satisfy the conditions and put 2 integers in, it just loops once again.
Also when I put in a character then it just endlessly loops "Enter minimum number Enter maximum number" ignoring the cins. Anyone know why? I'm a beginner so this is probably really obvious
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int random(int minN, int maxN) //generates random number within specified range
{
srand (time(NULL));
int x = (maxN - minN);
int y = minN + (rand() % (x+1));
return y;
}
int require() //makes sure a < b and both are digits
{
int a,b;
do {
cout << "Enter minimum number" << endl;
cin >> a;
cout << "Enter maximum number. Note: Has to be greater or equal to minimum." << endl;
cin >> b;
} while (a > b || !isdigit(a) || !isdigit(b));
return random(a,b);
}
int main()
{
cout << require() << endl;
}
You should not use isdigit as this relates to a particular character is a digiti. Instead the loop should look like this:
int require() //makes sure a < b and both are digits
{
validNumbers = true;
do
{
cout << "Enter minimum number" << endl;
cin.clear();
cin >> a;
} while (cin.fail());
do
{
cout << "Enter maximum number. Note: Has to be greater or equal to minimum."
<< endl;
cin.clear();
cin >> b;
} while (cin.fail() || a > b);
return random(a,b);
}
PS: You only need to call srand (time(NULL)); once at the start of the program.
You are reading the numbers as, well, numbers not as characters as the isdigit function expects. If you are using a C++11 compliant standard library, the values of a and b will actually be zero if the input is not valid integer numbers, which means that e.g. !isdigit(a) will be true. If you are using a non-C++11 library, then the value of a and b will be random, and will most likely cause !isdigit(a) to be true as well as the amount of valid digit ASCII values in a full 32-bit integer range is quite small.
If you read a reference about the input operator, like this one you will see that if extraction fails, then the streams failbit will be set. This can either be tested "inline" like this:
if (!(std::cin >> a))
{
std::cout << "Not a valid number, try again: ";
continue;
}
Or it can be tested using the streams fail function.