Order of initializing an equality C++ - c++

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.

Related

I found this bug in my code that i created to get the highest value from 2 integers and the variable is assigning itself a value

I'm starting out to learn C++ and I'm a bit clueless as to what might be happening here. when I run the program and enter 2 equal inputs the int variable-result, automatically assigns itself the value, when it should not because none of the if statements are fulfilled.
#include <iostream>
#include <cmath>
using namespace std;
// this is the function to find the highest value among 2.
int MaxNum(int Num1, int Num2) {
int result;
string asdf;
if (Num1 > Num2) {
result = Num1;
} else if (Num1 == Num2) {
asdf = "equal inputs";
} else if (Num2 > Num1) {
result = Num2;
}
// here if the 2 given values are equal the variable result, should not be
// assigned any value but when it is tested, it automatically assigns
//itself the input value.
cout << result;
cout << asdf;
}
int main() {
int Uno;
int Dos;
cout << "enter 2 nos and ill tell the highest.";
cin >> Uno;
cin >> Dos;
MaxNum(Uno, Dos);
return 0;
}
When you define a variable, it will always have some value. This value, if you do not assign one, can be anything - just whatever value happens to be in the memory where it is defined. So you might see the number you inputted here, but that can be just a coincidence, or caused by some more complicated reasons on how programs use and recycle memory (because of how the stack is built up, but that is out of scope here). Either way, you cannot count on this.
nb- it is good practice to always initialize your variables (for example int result = 0). If you don't do that, bugs can get hard to reproduce when you start building more complicated programs.

Simple C++ calculator always outputs 16

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.

Why for loop behave differently in following different situations

I am new in programming I am studying about for loop I tried it in various ways and output every time was different.
Code when I wrote only "a" to initialize for loop:
input was "Enter binary number:11011"
Output was "Decimal Number=27"
#include <iostream>
using namespace std;
int main(){
int a,b,c=1,d=0;
cout<<"Enter binary number:";
cin>>a;
for (a;a!=0;a=a/10) {
b=a%10;
d=d+b*c;
c=c*2;
}
cout<<"Decimal Number="<<d<<endl;
}
Code when I wrote "int a" to initialize for loop:
input was "Enter binary number:11011"
Output was "Decimal Number=0"
#include <iostream>
using namespace std;
int main(){
int a,b,c=1,d=0;
cout<<"Enter binary number:";
cin>>a;
for (int a;a!=0;a=a/10) {
b=a%10;
d=d+b*c;
c=c*2;
}
cout<<"Decimal Number="<<d<<endl;
}
Code when I wrote nothing to initialize for loop:
input was "Enter binary number:11011"
Output was "Decimal Number=27"
#include <iostream>
using namespace std;
int main(){
int a,b,c=1,d=0;
cout<<"Enter binary number:";
cin>>a;
for (;a!=0;a=a/10) {
b=a%10;
d=d+b*c;
c=c*2;
}
cout<<"Decimal Number="<<d<<endl;
}
Your first and last code snippets do not differ from each other, apart from a being evaluated and its value discarded in the initialization section of the first for loop
Your second loop re-declares a without initializing it. Variable a inside the for loop is not the same as the variable a outside the loop, so reading its uninitialized value is undefined behavior.
Since you do not really need a separate loop variable, using a while loop is a more common choice:
while (a) {
b = a%10;
d += b*c;
c *= 2;
a /= 10;
}
Note the use of compound assignment expressions +=, *=, and /=. A compound assignment of the form x += y is equivalent to x = x + y

Am new to c++ programming and i have been working on the following task: [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 5 years ago.
Improve this question
Write the definition of a function that takes as input the three numbers. The function returns true
if the first number to the power of the second number equals the third number; otherwise, it
returns false. (Assume that the three numbers are of type double.)
The program runs and executes but after everything is done its only returning 0 and not true or false. Where could i be wrong please. thank you in advance. this is my code so far:
#include <iostream>
#include <math.h>
using namespace std;
class powers
{
private:
double num1;
double num2;
double num3;
public:
bool takeInput(double, double, double);
};
int main()
{
powers power;
double a;
double b;
double c;
cout << "please input first number: ";
cin >> a;
cout << "please input second number: ";
cin >> b;
cout << "please input third number: ";
cin >> c;
power.takeInput(a, b, c);
}
bool powers::takeInput (double num1, double num2, double num3)
{
double a;
double b;
double c;
num1 = a;
num2 = b;
num3 = c;
if (pow(a, b) == (c))
return true;
else
return false;
}
Your program will not magically print anything by itself. To print "true" or "false" to the standard output, you would have to call your function power.takeInput like this at the end of main.
cout << power.takeInput(a, b, c) ? "true\n" : "false\n";
As additional notes:
The code of powers::takeInput seems to be unnecessary complicated. What is the purpose of your variables a, b and c if you end up assigning to them the values of num1, num2 and num3? Why not use these values directly?
if (a) then return true else return false is equivalent to return (a).
– Indeed, the return code of the main function is always an integer, which is used exclusively to indicate the successful execution of a program. 0 means successful execution.
You never initialize variables a, b, c inside of takeInput. I guess num1 = a; should be a = num1; and so on. Also notice how power class fields num1, num2, num3 are not initialized as well and have the same names as takeInput parameters which may lead to more confusion. You should either name member fields with m_ prefix or access them using explicitly, like this->num1. Also if you have variables with names like x1, x2 ... xn it would be better to use array instead.

One of my variables in my simple calculator says that it is not being initialized. Why?

I am a noob to C++, and as a part of homework I had to create a simple calculator with four functions within C++. I have done this and it works, however, I am now trying to loop it so that a user can have infinite attempts at using it, however, I am having struggles. Basically, when I run my program and tell the program which operation I'd like to use, it tells me that my variable "sum" is not being initialized. Im not quite sure what this is, or how to fix it. Any ideas? Here is my code -
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
while (true)
{
int num1, num2, r;
double sum;
cout << "Enter a number\n";
cin >> num1;
cout << "Enter another number\n";
cin >> num2;
cout << "Please enter an operator (+ , * , /, - or End)\n";
cin >> r;
if (r == 'End') break;
if (r == '+') sum = num1 + num2;
if (r == '-') sum = num1 - num2;
if (r == '*') sum = num1 * num2;
if (r == '/') sum = num1 / num2;
cout << r;
cout << "The answer is \n" << sum << endl;
system("pause");
return 0;
}
}
If the user enters 'a' as operator for example (something else than the valid choices), sum is never assigned a value, but sum is printed.
As others have said, the variable sum remains uninitialized if the user enters an invalid choice for r. Just set double sum=0; and you're good to go.
In addition, 'End' is not a char, so you can't compare it to r. You'll have to use some other option for ending.
The compiler says that you are trying to use an unintialized variable, sum.
If you think you initialize it, think again: You only assign a value if r is +, -, * or /. But what if r is a? 'End' is not a character, and thus invalid
Then sum is never initialized/has a value, and so the compiler complains.