Why I am getting this output from this loop? - c++

#include <iostream>
using namespace std;
I am very new to cpp and programming and I am trying to find the factors of a number, max, why is my code output coming out the way it is?
int max;
cout << "Enter a number you'd like to see the divisors of: " << endl;
cin >> max;
//I am trying to find all divisors for the number max
//I know this isn't the most efficienct way but I thought that it would work.
//Instead of 50, 25, 20, 10, 5 ,1 for output it looks like 50, 25, 25, 25 25, 5
for (int t=1; t <= max; t++) {
if (max % t == 0) {
int m = max/t;
}
}
cout << m << endl;

Your output is misplaced. Move the cout << m << endl; statement into your if statement block:
if (max % t == 0) { // start of a block
int m = max / t;
std::cout << m << '\n';
} // end of a block
Make sure you properly mark the block of statements using braces {}. Now for a given input of 50 the output is:
50 25 10 5 2 1
Live example on Coliru

using namespace std;
As BO41 said, you should never use the namespace, here are some reasons: Why is "using namespace std" considered bad practice?
Instead of using the namespace, you should write only what you are using, for example:
using std::cout;
using std::endl;
Now back to the question:
for(int t=1; t <= max; t++){
if(max % t == 0)
int m = max/t;
} cout << m << endl;
Note that you are defining m inside the if and using it outside of it. also, if it wasn't for that, you would print only the last divisor you find. You should do something more like:
for(int t = 0; t <= max; t++){
if(max % t == 0){
int m = max/t
cout << m << endl;
}
}
here you will print every divisor of max.
Personally, i would always open a block for if statements, even if there is only one line in the block, for me it's much more organized and may prevent errors.

Is this your entire program? The variable
int m
is out of scope at the line
cout << m << endl;
which leads me to believe you have another variable named "m" declared earlier in the program that is being shadowed by the newly declared int also named "m" inside the if-block. If this is the case, then the previously declared variable "m" outside the if-block would get printed to cout.

Related

I need help solve my problem of my activity

So I need my help to correct my code, which is given to my programming class assignment. My activity is to print numbers divisible by 5 for the integers from 1 to 99. So I tried to code like this:
#include <iostream>
using namespace std;
int main () {
int num, min, max;
cout << "Enter Number: ";
cin >> num;
min = 1;
max = 99;
if (num > min || num < max) {
if (num % 5 == 0) {
cout << "Divisible.";}
else {
cout << "Not Divisible";}
}
else {
if (num % 5 == 0) {
cout << "Error Input.";}
else {
cout << "Error input.";}
}
return 0;
}
So when I compile and run, I test to enter a divisible number by 5 or not. When I put 0, it says "Error input," that's correct. However, when I put 100, it says "divisible" instead of "error input." What is the correct input of my code?
The input is an integer from 1 to 99, which means that it should be >= 1 AND <= 99.
So, simply change
if (num > min || num < max)
to
if (num >= min && num <= max)
You made a mistake in the first if statement. When you are giving the OR operator, it'll return true even if only one of the conditions are satisfied.
You should use the AND operator for your code to work as expected.
Moreover, you don't have to use the min and max variables also, it is making the program unnecessarily big (only 2 lines though, but still).

User inputs N, find all pairs of a and b co-primes where a<N & b<N

#include <iostream>
using namespace std;
void gcd(){
int a,b,hcf;
for (int i = 1; i <= b; ++i) {
if (a % i == 0 && b % i ==0) {
hcf = i;
}
}
}
void pirm(){
int a,b,n,hcf;
for (int a=1;a<n;a++){
for (int b=1;b<n;b++){
gcd();
if (hcf==1) {
cout << a << " and " << b << endl;
}
}
}
}
int main(){
int n,a,b,i,hcf;
cout << "Enter a natural n, less than 100" << endl;
cin >> n;
if (n>=1 && n<100){
pirm();
}
else
cout << "You didn't enter a natural number" <<endl;
}
When I run it and enter a number, it doesn't do anything. The task is as follows:
User enters a natural N, that is less than 100. Find and output all pairs of co-primes that are < 100.
As you can tell by the code, I'm a complete newb at C++. Just wondering why the program "stops" or where I messed up the code in general. Any help is greatly appreciated.
There are a number of issues here.
First, the direct answer to your question: your program never prints because it never executes a print statement. If you enter a natural number, but hcf is never equal to 1, you will never print anything.
Now the question becomes why is hcf never 1? And that's where we start to run into more issues with your code. The main misunderstanding seems to be about scope. If you declare variables inside a function, they are within the function's "scope" -- the function can use them, and any scope inside the function can use them (e.g. loops and conditionals), but no outer scope can use them. You declare a, b, and hcfseveral times, but you only ever use them in gcd(). Not only is this unnecessary, but critically, these are different variables. You change the hcf in the scope of gcd(), but the hcf in pirm() is unchanged!
There are many ways to do what you're trying to do. The one that's closest to what you already have is to have gcd() take parameters by reference. If you change your declaration of gcd() to void gcd(int a, int b, int &hcf), and do not redeclare those variables in the first line of the function, then you are able to modify hcf in a way that will stick even when the function goes out of scope. You will then need to change your call on line 15 to gcd(a,b,hcf);.
Your algorithm could also be improved, though I believe it will still work. If you're interested in a more canonical way to find the gcd, try looking into Euclid's algorithm.
You should learn how to pass arguments to a function. Corrected your code for you, seems to be working:
#include <iostream>
void gcd(int &hcf, int a, int b)
{
for (int i = 1; i <= b; ++i)
{
if (a % i == 0 && b % i == 0)
{
hcf = i;
}
}
}
void pirm(int n)
{
int hcf;
for (int a = 1; a<n; a++)
{
for (int b = 1; b<n; b++)
{
gcd(hcf, a, b);
if (hcf == 1)
{
std::cout << a << " and " << b << std::endl;
}
}
}
}
int main()
{
int n;
std::cout << "Enter a natural n, less than 100" << std::endl;
std::cin >> n;
if (n >= 1 && n<100)
{
pirm(n);
}
else
std::cout << "You didn't enter a natural number" << std::endl;
system("pause");
return 0;
}

C++ do while loop not working

I'm trying to make this code work:
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while(i > 10 && i < 1)
cout << "the square of the number you have entered is " << i*i;
}
Basically, the idea is that a user enters a number between 1 and 10. While the number is not between 1 and 10, it keeps asking the user to enter a number between the values. Then, when the number is between the values, it is squared and returned to the user.
I can't see why this isn't working
Any help is appreciated
You have:
while (i > 10 && i < 1)
You want:
while (i > 10 || i < 1)
while (i > 10 && i < 1)
Your condition is logically faulty; if reinterpreted, it says:
while i is greater than 10 AND i is less than 1
Judging from your code, the || operator should be used:
} while (i > 10 || i < 1);
As others mentioned, your condition is faulty.
a number can't obviously be under 1 AND above 10 at the same time, so the while loop exits immediately after the do statement.
#include <iostream>
using namespace std;
int main()
{
int i;
do
{
cout << ("please enter a number between 1 and 10");
cin >> i;
} while (i < 1 || i > 10)
cout << "the square of the number you have entered is " << i*i;
}
You should use an Or ||, that condition with && will never be true.
The loop condition is wrong and will never loop, as i cannot be less than 1 && greater than 10 at the same time. You should use the logical OR (||) operator instead. In addition, there must be a semicolon placed after the do-while statement. And you probably want and end of line placed after the prompt. Also, you don't want to start the bad habit of polluting the global namespace, even with the awesomeness of std. So:
#include <iostream>
int main()
{
int i;
do {
std::cout << "please enter a number between 1 and 10\n";
std::cin >> i;
} while (i > 10 || i < 1);
std::cout << "the square of the number you have entered is " << i*i << std::endl;
}

Simple C++ input files and if statements

I wrote the code and it works except the total is wrong. It is supposed to multiply the distanceRate by the rate and add each cost to make the total, but it's not doing that. Any help would be appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
//Declare Variables
ifstream inFile;
double packageWeight;
double distance;
double totalCharge = 0;
double rate;
double distanceRate;
int customerNumber;
double shippingCharge;
int packageCount = 0;
inFile.open("shipping.txt");
if(inFile)
{
cout << "Customer Package Shipping" << endl;
cout << "Number Weight Distance" << endl;
while(!inFile.eof())
{
inFile >> customerNumber;
inFile >> packageWeight;
inFile >> distance;
if(0 < packageWeight <= 2)
rate = 1.10;
else if(2 < packageWeight <=6)
rate = 2.20;
else if(6 < packageWeight <= 10)
rate = 3.70;
else if(10 < packageWeight <=20)
rate = 4.80;
else
cout << "Invalid package weight" << endl;
if( 0 < distance <= 500)
distanceRate = 1;
else if( 500 < distance <= 1000)
distanceRate = 2;
else if(1000 < distance <= 1500)
distanceRate = 3;
else if(1500 < distance <= 2000)
distanceRate = 4;
else
cout << "Invalid distance" << endl;
packageCount += customerNumber;
shippingCharge = rate * distanceRate;
totalCharge += shippingCharge;
cout << fixed << setprecision(2) << showpoint;
cout << setw(2) << customerNumber
<< right << setw(14) << packageWeight
<< setw(13) << distance
<< endl;
} //End of while loop
cout << "\nPackage shipped : " << packageCount << endl;
cout << "Total Charge : $" << totalCharge << endl;
inFile.close();
}
else
{
cout << "Could not open file" << endl;
}
system("pause");
return 0;
}
Some issues that I see in the snippet you gave me are as follows:
As pointed out by billz in a comment, your if statements are invalid. The statement if( 0 < distance <= 500) is not doing what you expect, it evaluates from left to right, so you have 0 < distance (lets say that evaluates to true) so then you have true <= 1000 which isn't going to give the results that you think it will. This actually needs to be broken apart into two separate comparisons like distance > 0 && distance < 500.
As I noted in my comment, you're adding the customer number to the package count, this will most likely always give a wrong value for package count. If your customer numbers are 1, 2, 3, 4 then you claim the package count is 10 when it's actually only 4 (forgive me if I misunderstood the purpose of this field).
You have no default value for distanceRate but you still use it in an operation (possibly uninitialized) which will give unexpected results (as you are seeing). In your else, you should actually give it a dummy value that way you guarantee that it will always be set. You also do reset it, so if it gets set to 4, and then next distance fails the tests and enters the else, you have another calculation on the variable as 4 instead of it's default value. You should initialize any variable that you plan to use unless you have explicit reason not to give it a value at initialization, and anytime you use a variable in a loop you should reset it's value at the start of the loop.
Additional Note (EDIT)
I wouldn't recommend using system("pause"); as it does a lot more behind the scenes than you would want in a simple pause, a better approach I've seen used is:
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
cout << "Press any key to continue!";
_getch();
cout << "Finished";
return 0;
}
EDIT 2
If statments can contain a single line or a code block to execute.
Single line:
if (someValueIsTrue)
executeThisFunction();
Code block:
if (someValueIsTrue) {
executeThisFunction();
alsoThisFunction();
}
Anytime you need to execute more than one statement in an if/else/while/for/do...while/etc... you'll need a code block. I imagine (based on your explanation) that you did:
if (blah)
// ....
else
distanceRate = 0;
cout << "Invalid Distance";
And the compiler only sees that you have the distanceRate = 0 nested in the loop, the cout statement is actually not part of the else but part of the previous block of code. You need to use a code block here.
!inFile.eof() // incorrect
inFile.good() // correct
read on eof() it doesn't do what you might think it does.
if( 0 < distance <= 500) // all the if statements are incorrect
if(distance>0 && distance<=500) // correct
The way you wrote the if condition, it does not do what you think it does.

My 'cout' isn't giving correct value - why?

Simple "sum of digits" code. It compiles but when executed, the last cout gives a "0" for the num int rather than the actual user-input number.
Feel free to copy and paste this into your own compiler, if you're so inclined, to see what I mean.
How can I get this to output the correct "num" value?
~~~
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
cout << "Please type any non-negative integer: ";
cin >> num;
while ( num > 0 ) {
sum += num % 10;
num /= 10;
}
cout << "The sum of the digits of " << num << " is " << sum << "\n";
system("PAUSE");
return 0;
}
You've been modifying num all along until it becomes 0 (that's what your while ( num > 0 ) statement ensures!), so OF COURSE it's 0 at the end! If you want to emit what it was before, add e.g. int orig=num; before the loop, and emit orig at the end.
The problem is that num /= 10 changes num. If you want to get this to work, you should create a temp variable that you use to do all the calculations.
For the next time, you can try to use a debugger. You'll find those "bugs" very easy!