while/if

Hi,I'm a beginner of c++, here are two questions that I need helps with. I dont know why there's no output comin out for this two programs.
Thanks for your time. =]

//1. I need to print all three digit number n for which the square of n ends with the digits 21. eg, 111 is printed because 111^2 = 12321.

#include<iostream>
using namespace std;
int main(){
for(int n=100; n<1000; n++){
if((n*n)%100==2 && (n*n)%10==1)
cout<<n<<" ";
}
return 0;
}

//2. Calculate the average of first 8 numbers divisible by 3 or 5, but not 6 and 10.

#include<iostream>
using namespace std;
int main() {
int counter=1;
int n=1;
int sum=0;
double average;
if ((n%3 ==0 || n%5 ==0) && (!(n%6 ==0 && n%10 ==0))){
cout<<n<<" ";
while (counter <= 8)
counter++;
}
average = sum/8
sum+=n;

return 0;
}
For First one rather than using
if((n*n)%100==2 && (n*n)%10==1) use
if((n*n)%100==21)
Here is answer for your second question...
please check it out..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
        int counter=1;
	int sum=0;
	double average;
	for(int n = 1; counter <= 8 ; n++)
	{
		if ((n%3 ==0 || n%5 ==0) && (n%6 !=0 && n%10 !=0))
		{
			cout<<n<<" ";
			sum+=n;
			counter++;
		}
	}
	average = sum/8;
	cout << endl <<"Average" << average;
thanks a lot, they both work, i see how is question 2 goin now, that was very clear and helpful.
but for question#1

For First one rather than using
if((n*n)%100==2 && (n*n)%10==1) use
if((n*n)%100==21)

I see it is simplier to set it to 21 rather than 2 and then 1, but im curious, aren't they mean the same, i just put it in a more complex way, is there reason why it is not working?

I see it is simplier to set it to 21 rather than 2 and then 1, but im curious, aren't they mean the same, i just put it in a more complex way, is there reason why it is not working?


Only one of these can be true for a given value of n:
 
((n*n)%100==2)
 
((n*n)%100==21)

because 2 != 21.

You could have used if((n*n)%100==21 && (n*n)%10==1) but the second test is redundant.

Or, if you really want to test the digits separately, try this:
if (((n*n)/10)%10==2 && (n*n)%10==1)
Last edited on
isee, thanks alot!
Topic archived. No new replies allowed.