Does it matter where I initialize my integer? - c++

I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.
However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?
Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.
#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;
int main() {
int value = 0; // where I input
cin >> value;
// if you put int result above cin program changes.
int result = value % 2;
if (result == 0) {
cout << "Even number." << endl;
}
else {
cout << "Odd number." << endl;
}
return 0;
}

Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.
When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.
That's why you need to use cin>>value; before setting result = value%2;.

C++ read the code top to bottom , line by line. So you will have to int your variable first.I made a much more simpler version of the program if you want to read it:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "a=";
cin >> a ;
if(a%2==0)
{cout<<"a is even";}
else
{cout<<"a is uneven";}
}

When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;

Related

for-loop variable takes a random value at the beginning

So, I am trying to do this code, which lets the user know whether a given nr. is a perfect one or not. But I am facing some difficulties in a part of my code. I also tried to solve it with a debugger, and I always see the initial value of variable "i", which I use in my for-loop, take a huge random value for no reason at all. While for the nr. 6, you get the correct answer, for nr. 28 you don't.
And maybe this is the reason why my code doesn't work as it should
#include <iostream>
using namespace std;
int main()
{
int a,a_half,sum_divisor=0;
float multi=0.0;
cout <<"Give number: ";
cin >>a;
a_half = a/2;
for(int i = 1;i<=a_half;i++)
{
multi=a/i;
if(int(multi)==multi)
{
sum_divisor+=i;
}
}
if(sum_divisor==a)
{
cout << a<<" is a perfect one!"<<endl;
}else
{
cout <<a<<" is not a perfect number";
}
return 0;
}

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.

Super basic code: Why is my loop not breaking?

for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
cout << size;
if(inputnum[i] == '.')
{
break;
}
}
The break breaks the input stream but the size keeps outputting.
The output of size is 012345678910111213...474849.
I tried putting size++ inside the loop but it made no difference. And size afterwards will be equal to 50, which means it went through the full loop.
I forgot to explain that I added the cout << size within the loop to debug/check why it outputted to 50 after the loop even if I only inputted 3 numbers.
I suspect that inputnum is an array of int (or some other numeric type). When you try to input '.', nothing actually goes into inputnum[i] - the cin >> inputnum[i] expression actually fails and puts cin into a failed state.
So, inputnum[i] is not changed when inputting a '.' character, and the break never gets executed.
Here's an slightly modified version of your code in a small, complete program that demonstrates using !cin.good() to break out of the input loop:
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
int inputnum[50];
int size = 0;
for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
if (!cin.good()) {
break;
}
}
cout << "size is " << size << endl;
cout << "And the results are:" << endl;
for (int i = 0; i < size; ++i) {
cout << "inputnum[" << i << "] == " << inputnum[i] << endl;
}
return 0;
}
This program will collect input into the inputnum[] array until it hits EOF or an invalid input.
What is inputnum ? Make sure t's a char[]!! with clang++ this compiles and works perfectly:
#include <iostream>
int main() {
int size = 0;
char inputnum[60];
for(int i=0;i<50;i++,size++) {
std::cin >> inputnum[i];
std::cout << size;
if(inputnum[i] == '.') {
break;
}
}
return 0;
}
(in my case with the following output:)
a
0a
1s
2d
3f
4g
5.
6Argento:Desktop marinos$
Your code seams OK as long as you're testing char against char in your loop and not something else.. Could it be that inputnum is some integral value ? if so, then your test clause will always evaluate to false unless inputnum matches the numerical value '.' is implicitly casted to..
EDIT
Apparently you are indeed trying to put char in a int[]. Try the following:
#include <iostream>
int main() {
using namespace std;
int size = 0;
int inputnum[50];
char inputchar[50];
for(int i=0;i<50;i++,size++) {
cin >> inputchar[i];
inputnum[i] = static_cast<int>(inputchar[i]); // or inputnum[i] = (int)inputchar[i];
cout << size << endl; // add a new line in the end
if(inputchar[i] == '.') break;
}
return 0;
}
Then again this is probably a lab assignment, in a real program I'd never code like this. Tat would depend on the requirements but I'd rather prefer using STL containers and algorithms or stringstreams. And if forced to work at a lower-level C-style, I'd try to figure out to what number '.' translates to (simply by int a = '.'; cout << a;`) and put that number directly in the test clause. Such code however might be simple but is also BAD in my opinion, it's unsafe, implementation specific and not really C++.

User input in simple C++ counter program

I'm trying to make a simple counter program in C++ that will increment a variable with user input (specified by pressing a certain key). Here is what I came up with:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int variable;
char userInput;
variable = 0;
cout << "To increment variable one, press a \n";
do
{
variable = variable++;
cout << "variable++ \n" ;
} while (userInput = "a");
}
I have perused several related threads on this site and believe this should work. However, I get several errors, including that the operation on variable is not defined and that there has been an "invalid conversion" from "const char" to "char."
Add cin in your loop:
cin>>userInput;
and change
variable = variable++;
to
variable++; // or variable = variable + 1;
next you while condition should be like this:
while (userInput=='a');
So your overall program will look like this:
#include <iostream>
using namespace std;
int main()
{
int variable;
char userInput;
variable = 0;
cout << "To increment variable one, press a \n";
do
{
cin>>userInput;
variable++;
cout << "variable++ \n" ;
} while (userInput=='a');
return 0;
}
In while loop you need a std::cin, like
cin >> userInput;
Moreover, the following line
variable = variable++;
will produce Undefined Behaviour. Read more about Sequence point for better understading.
Try:
variable = variable + 1;
Finally in the while loop breaking condition, instead of assignment operation
while (userInput = "a");
Use comparison like:
while (userInput == "a");
You need to use
std::cin >> userInput; // each time you go through the `do` loop.
Also, you just need to use
variable++; // on the line.
Also! Use cout << variable << "\n";
Lastly, use
} while(strncmp((const char*)userInput,(const char*)"a",1));

C++ "While" Loop

I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2