Simple beginner C++, increment and decrement questions [closed] - c++

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 8 years ago.
Improve this question
I'm using C++, and I have increments and decrements down solidly, but I have one equation where I have to decrement theChar equation, or the one with int var by -2, and I do not know the code for it.

Please formulate your question better. What do you mean with
I have one equation where I have to decrement "theChar" equation, or
the one with "int var" by -2
Do you mean:
char x = 'a';
x = x + 3; //now x is 'd'
int var = 10;
var -= 2; //equal to var = var -2;

The equations are not equations in a math sense of equation.
The = sign tells the computer to store whats on the right side into the variable that is on the left side.
int a;
a = 5;
this stored the 5 into a once.
int a, b;
a = 5;
b = a;
a = 6;
b is still 5 because when it was stored it copied from a. When a changed b was not recalculated but stayed as it was.
int a;
a = 5;
a = a - 2;
a is now beeing decremented by 2 since a was set to 5 when the right side ( a - 2 ) is calculated it is calculated to be 3. When that is done it gets written to the left side which happens to be a so at this point a is overwritten with 3;
char c = 'B';
c = c - 1;
c has a value of 'A' at the end of this code. There is some behind the scenes magic going on.
Characters are also numbers. So what really happens when i store 'B' into the variable the computer actually stores 66. You can read up on that here. When i decrement by one the value is decremented from 66 to 65. The character with the number 65 happens to be 'A'.
I read in the comments that you have trouble putting it all into a program.
I went ahead and wrote a code snippet for you.
#include <iostream>
using namespace std;
int main()
{
int a, b;
char c;
//cout is like a friend that you give something to put on the console
// << means give this to cout
cout << "Hello World!" << endl; //endl is a new line character
cout << endl << "Setting a, b" << endl;
a = 5;
b = a;
cout << "Value of a is " << a << ". " << "Value of b is " << b << "." << endl;
cout << endl << "Changing a" << endl;
a = 3;
cout << "Value of a is " << a << ". " << "Value of b is " << b << "." << endl;
cout << endl << "Adding to a" << endl;
a = a + 3;
cout << "Value of a is " << a << ". " << "Value of b is " << b << "." << endl;
cout << endl << "Playing around with characters" << endl;
c = 'B';
cout << "Character c is " << c << ". " << "Number stored for c is actually " << (int)c << "." << endl;
c = c + 1;
cout << "Character c is " << c << ". " << "Number stored for c is actually " << (int)c << "." << endl;
c = 70;
cout << "Character c is " << c << ". " << "Number stored for c is actually " << (int)c << "." << endl;
}

Related

Pointer not showing updated value when incrementing a variable in std::cout [duplicate]

This question already has answers here:
Order of evaluation of arguments using std::cout
(5 answers)
Strange output, not as expected
(2 answers)
Undefined behavior and sequence points
(5 answers)
Closed 5 years ago.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a = 5;
int& b = a;
int* c = &a;
cout << "CASE 1" << endl;
cout << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
b = 10;
cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl << endl;
cout << "CASE 2";
a = 5;
cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
b = 10;
cout << endl << "a is " << a << endl << "b is " << ++b << endl << "c is " << *c << endl << endl;
cout << "CASE 3";
a = 5;
cout << endl << "a is " << a << endl << "b is " << b << endl << "c is " << *c << endl;
b = 10;
cout << endl << "a is " << a << endl << "b is " << b++ << endl << "c is " << *c << endl;
}
The output:
CASE 1:
a is 5. b is 5. c is 5.
a is 10. b is 10. c is 10.
CASE 2:
a is 5. b is 5. c is 5.
a is 11. b is 11. c is 10.
CASE 3:
a is 5. b is 5. c is 5.
a is 11. b is 10. c is 10.
I understand CASE 1. But I am having difficulty understanding CASE 2 and CASE 3. Can someone explain why doesn't c get updated with new value in both cases?
The evaluation order of operands is unspecified, and you're modifying an object and reading it without those operations being sequenced.
Thus, your program is as undefined as cout << a << a++;, and anything can happen.
I think your problem is due to what is called sequence points. You can have a long read about that in this answer but in a few words it basically states the order or evaluation of the elements of an expression.
Update in your case this order is undefined, although some compilers seem to make it right-to-left.

C++ - Multiplying / adding, two integers, then determining if they are even or odd

I'm having trouble with a simple program which will multiply 2 integers and print the output determining if it is even or odd. It also will add the 2 integers input in the beginning and do the same on the following line. The multiplying works fine and displays if the product is even or odd properly. However, the addition is not doing so and I am not understanding why. Here is my code:
#include <iostream>
using namespace std;
int main (){
int a, b;
cout << "Please enter an integer: ";
cin >> a;
cout << "Please enter another integer: ";
cin >> b;
if (a*b %2== 0){
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is even." << endl;
}
else {
cout << "The product of " << a << " and " << b << " is " << (a*b)
<< " and is odd." << endl;
};
if (a+b %2== 0){
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is even." << endl;
}
else {
cout << "The sum of " << a << " and " << b << " is " << (a+b)
<< " and is odd." << endl;
}
return (0);
}
Any help and an explanation would be greatly appreciated. Thanks!
Operator Precedence
Basically, % is dealt with before +, so your test:
if (a+b % 2 == 0)
works out like
if (a + (b%2) == 0)
which doesn't make a whole lot of sense, and is rarely going to be true, unless both b is even and a is 0.
All the operations that are to do with multiplication (*, /, %) have the same precedence, and are handled from left-to-right, so
if (a*b % 2 == 0)
works out ok, as:
if ((a*b) % 2 == 0)
which happens to be what you really meant.
However, these multiplication operations are handled before the operations related to addition (+, -). So % is grouped before +, causing your specific problem.
You may have learnt about order of operations in school, for instance I was taught BODMAS. Same rules apply in C++.
Personally, I find it's best to use parentheses liberally in any sort of compound expression, even when it's not strictly necessary. It can make the code a lot easier to read, rather than trying to remember all the rules in your head. So I would prefer:
if ((a*b) % 2 == 0) // ...
if ((a+b) % 2 == 0) // ...
even though the extra parentheses in the first aren't really required.
Operator precedence says that % comes before + so
a+b %2== 0
Is actually
a + (b % 2) == 0
You need to wrap the addition with ()
(a + b) % 2 == 0
Possibly Order of Operations.
To ensure that your code is behaving the way you intend, you may wish to rewrite it like this:
if (((a*b) %2)== 0){
cout << "The product of " << a << " and " << b << " is " << (a*b) << " and is even." << endl;
}
else {
cout << "The product of " << a << " and " << b << " is " << (a*b) << " and is odd." << endl;
};
if (((a+b) %2)== 0){
cout << "The sum of " << a << " and " << b << " is " << (a+b) << " and is even." << endl;
}
else {
cout << "The sum of " << a << " and " << b << " is " << (a+b) << " and is odd." << endl;
}
You can then incrementally remove parenthesis until you're confident that the code is readable but still correct.

C++ assignment help on creating codes for reusability?

I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.

Value always return 0 while calculating [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 8 years ago.
Improve this question
I was doing an assignment for my subject here and in the assignment, every student is required to create a simple C++ program. The problem here is, when I do not assign a default to a variable, a compile error will occur. However, when I assign a default value (in this case, value = 0), the value will always be 0.
My question is, is there any way to solve this problem while not encountering the compile error?
If there was a similar question asked, could you please also, include the link to the solved question as well? Thank you very much!
[Edit #1: To those who wonder why the code is "messy", I only used simple commands and did not use object oriented components, if/else statements etc. The project created was meant to be composed of "simple codes".]
[Edit #2: This is the output display that I snapped:
http://i.imgur.com/4csk1Rz.png
The Total Discounted fee part should be displaying numbers instead of default value 0]
(Microsoft Visual Studio Pro 2013; C++)
Expected output display:
http://i.imgur.com/jOJvymV.png
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
/* Declare variables */
int qtyVehicleCar, qtyVehicleTaxi, qtyVehicleTruck; // User input
double feeOriginalCar, feeTotalOriginalCar, rateDiscountCar, feeTotalDiscountedCar, feeTotalAfterDiscountedCar; // variables for vehicle Car
double feeOriginalTaxi, feeTotalOriginalTaxi, rateDiscountTaxi, feeTotalDiscountedTaxi, feeTotalAfterDiscountedTaxi; // variables for vehicle Taxi
double feeOriginalTruck, feeTotalOriginalTruck, rateDiscountTruck, feeTotalDiscountedTruck, feeTotalAfterDiscountedTruck; // variables for vehicle Truck
double feeRepTotalOriginalFee, feeRepTotalDiscountedFee, feeRepTotalAfterDiscounted; // Generate final output
cout << "=====================================\n";
cout << "=====================================\n";
cout << "====== Malaysia Highway Company =====\n";
cout << "=====================================\n";
cout << "=====================================\n";
cout << endl;
cout << "Enter quantity of the vehicles on 1st January 2014: " << endl;
cout << "Car\t\t:\t";
cin >> qtyVehicleCar;
cout << "Taxi\t\t:\t";
cin >> qtyVehicleTaxi;
cout << "Truck\t\t:\t";
cin >> qtyVehicleTruck;
/* Lay out the Report table */
cout << endl << endl << endl;
cout << "Report\n";
cout << "--------\n";
cout << endl;
/* ============================== */
/* Declaration prior to process */
/* ============================== */
/* The problematic part
feeTotalDiscountedCar = 0;
feeTotalDiscountedTaxi = 0;
feeTotalDiscountedTaxi = 0;
*/
// Prices
feeOriginalCar = 2.00;
feeOriginalTaxi = 1.00;
feeOriginalTruck = 3.50;
feeTotalOriginalCar = feeOriginalCar * qtyVehicleCar;
feeTotalOriginalTaxi = feeOriginalTaxi * qtyVehicleTaxi;
feeTotalOriginalTruck = feeOriginalTruck * qtyVehicleTruck;
// In percentage
rateDiscountCar = 2;
rateDiscountTaxi = 10;
rateDiscountTruck = 15;
feeTotalAfterDiscountedCar = (rateDiscountCar/100) * feeTotalOriginalCar;
feeTotalAfterDiscountedTaxi = (rateDiscountTaxi/100) * feeTotalOriginalTaxi;
feeTotalAfterDiscountedTruck = (rateDiscountTruck/100) * feeTotalOriginalTruck;
// Final total - to be displayed
feeTotalAfterDiscountedCar = feeTotalOriginalCar - feeTotalAfterDiscountedCar;
feeTotalAfterDiscountedTaxi = feeTotalOriginalTaxi - feeTotalAfterDiscountedTaxi;
feeTotalOriginalTruck = feeTotalOriginalTruck - feeTotalAfterDiscountedTruck;
feeRepTotalOriginalFee = feeTotalOriginalCar + feeTotalOriginalTaxi + feeTotalOriginalTruck;
feeRepTotalDiscountedFee = feeTotalDiscountedCar + feeTotalAfterDiscountedTaxi + feeTotalAfterDiscountedTruck;
feeRepTotalAfterDiscounted = feeRepTotalOriginalFee - feeRepTotalDiscountedFee;
/* ================= */
/* Declaration END */
/* ================= */
/* Gives the following variables a default value, they will be modified later by the program */
feeTotalAfterDiscountedTruck = 0;
feeTotalDiscountedTruck = 0;
/* Processes */
cout << "Item\t\t\t\t" << "Car\t" << "Taxi\t" << "Truck\t" << endl;
cout << "------------------------------------------------------\n";
cout << "Original fee\t\t\t" << "RM " << feeOriginalCar << "\t" << "RM " << feeOriginalTaxi << "\t" << "RM " << feeOriginalTruck << endl;
cout << "Quantity\t\t\t" << qtyVehicleCar << "\t" << qtyVehicleTaxi << "\t" << qtyVehicleTruck << endl;
cout << "Total original fee\t\t" << "RM " << feeOriginalCar << "\t" << "RM " << feeOriginalTaxi << "\t" << "RM " << feeOriginalTruck << endl;
cout << "Discount rate\t\t\t" << rateDiscountCar << "%\t" << rateDiscountTaxi << "%\t" << rateDiscountTruck << "%\t" << endl;
cout << "Total discounted fee\t\t" << "RM " << feeTotalDiscountedCar << "\t" << "RM " << feeTotalDiscountedTaxi << "\t" << "RM " << feeTotalDiscountedTruck << endl;
cout << "Total after discounted fee\t" << "RM " << feeTotalAfterDiscountedCar << "\t" << "RM " << feeTotalAfterDiscountedTaxi << "\t" << "RM " << feeTotalAfterDiscountedTruck << endl;
cout << endl;
/* Displays output */
cout << "Total original fee\t\t:\t" << "RM " << feeRepTotalOriginalFee << endl;
cout << "Total discounted fee\t\t:\t" << "RM " << feeRepTotalDiscountedFee << endl;
cout << "Total after discounted fee\t:\t" << "RM " << feeRepTotalAfterDiscounted << endl;
cout << endl << endl;
/* Displays end line */
cout << "------------------- End of Program -------------------" << endl;
system("PAUSE");
return 0;
}
An uninitialized variables warning can mean either (1) you forgot to initialize something or (2) you thought you initialized it but didn't. Looks to me that in this case it's the second problem. Your variable names are mixed up.
For example,
feeTotalAfterDiscountedCar = (rateDiscountCar/100) * feeTotalOriginalCar;
feeTotalAfterDiscountedTaxi = (rateDiscountTaxi/100) * feeTotalOriginalTaxi;
feeTotalAfterDiscountedTruck = (rateDiscountTruck/100) * feeTotalOriginalTruck;
These are supposed to be the amounts of the discounts, no? So why are you storing them into feeTotalAfterDiscountedSomething rather than feeTotalDiscountedSomething?
Similarly,
feeTotalAfterDiscountedCar = feeTotalOriginalCar - feeTotalAfterDiscountedCar;
feeTotalAfterDiscountedTaxi = feeTotalOriginalTaxi - feeTotalAfterDiscountedTaxi;
feeTotalOriginalTruck = feeTotalOriginalTruck - feeTotalAfterDiscountedTruck;
Why is the third one storing the result into feeTotalOriginalTruck instead of feeTotalAfterDiscountedTruck? (Note also that if you fix the first problem above, the rhs of the subtraction will also need to change).
Also,
feeRepTotalDiscountedFee = feeTotalDiscountedCar + feeTotalAfterDiscountedTaxi + feeTotalAfterDiscountedTruck;
Similar problem. These should, I believe, all be feeTotalDiscountedSomething rather than feeTotalAfterDiscountedSomething.
The compiler rightfully complains that feeTotalDiscountedCar and feeTotalDiscountedTaxi are uninitialized. You need to initialize them somewhere. Maybe you want the user to enter them somewhere like this:
cout << "Discount Fee Total Taxi:";
cin >> feeTotalDiscountedTaxi;
cout << "Discount Fee Total Car:";
cin >> feeTotalDiscountedCar;
why are you setting them to zero just before printing out?
feeTotalAfterDiscountedTruck = 0;
feeTotalDiscountedTruck = 0;
It will show the error because you are trying to use the variable with out initializing it.

Program output (Basic operators for c++). Order of operations?

// H2.cpp : Tihs program runs different mathmatical operations on numbers given by the user
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a;
cout << "Enter a number for a: "; //Prompts the user for a and b inputs
cin >> a;
int b;
cout << "Enter a number for b: ";
cin >> b;
cout << "A is " << a << "\tB is " << b << endl;
cout <<"Sum of a and b is equal to " << a << " + " << b << " and the result is " << (a + b) << endl; //Performs addition operator and gives output
cout <<"Product of a and b is equal to " << a << " * " << b << " and the result is " << (a * b) << endl;
cout <<"a > b is " << a << " > " << b << " and the result is " << (a > b) << endl;
cout <<"a < b is " << a << " > " << b << " and the result is " << (a < b) << endl;
cout <<"a == b is " << a << " == " << b << " and the result is " << (a == b) << endl; //Performs boolean operator and outputs result
cout <<"a >= b is " << a << " >= " << b << " and the result is " << (a >= b) << endl;
cout <<"a <= b is " << a << " <= " << b << " and the result is " << (a <= b) << endl;
cout <<"a != b is " << a << " != " << b << " and the result is " << (a != b) << endl;
cout <<"a -= b is " << a << " -= " << b << " and the result is a = " << (a -= b) << endl; //Performs - operator on a - b and makes a equal to the new result
cout <<"a /= b is " << a << " /= " << b << " and the result is a = " << (a /= b) << endl;
cout <<"a %= b is " << a << " %= " << b << " and the result is a = " << (a %= b) << endl; //Performs % operator on a % b and makes a equal to the new result. Ripple effect created from previous 2 lines as the value of a changes each time.
return 0;
The output I'm concerned with is here:
a -= b is -4198672 -= 4198672 and the result is a = -4198672
a /= b is -1 /= 4198672 and the result is a = -1
a %= b is -1 %= 4198672 and the result is a = -1
It seems like the value for a being displayed is the value of a after the line of code is executed. I'm sure that has something to do with the order of operations, but I'm not sure how to get around that. Any help is greatly appreciated.
The order in which arguments to operators or functions are evaluated is undefined in C++. If the evaluation of the different arguments have side effects, these can happen whenever the compiler sees fit and if there multiple modifications to the same object the result is undefined behavior. If you want to force a specific evaluation order, you'd need to break your expression down into multiple separate expression as these are evaluated in order or you could inject operators which create a sequence point. However, the operators creating a sequence point don't play nicely with chaining output operators. The list of operators forcing the first argument to be evaluate before the other arguments are:
the , operator
the logical && and || operators
the conditional operator ?:
Of course, if you overload any of these operators, they stop introducing a sequence point as they become normal function calls.
All the operators you have listed are comparison operators which return value true or false.
Except: -=, /= and %= operators
a-=b is actually a=a-b.
Just check if you are sure that you wanted this in first place?
BTW: if(a=b) is also returns true since it is always success but I do not think we do this intentionally.