Use of "/"

Hi everyone.

I am practicing for my first c++ exam and I am having a small problem.

void question2 ()

int x = 6, y = 1;

cout << "2) "<<endl;
cout<< "\tx\ty"<<endl<<"\t-\t-"<<endl;
while (x != 7) {
x += y/3;
y++;
cout<< "\t" << x << "\t" << y << endl;

Output
2)
x y
- -
6 2
6 3
7 4
The sum of 7 and 4 is 11

--------------

My question is this. What does y/3 do exactly? I always thought / was for division...

Thanks everyone.

Yes, the forward slash does represent division. It divides the value of y by three. If you're looking for a remainder, I would suggest using the modulus operator(%).


Last edited on
It is division.

-BHill
Then how does dividing by 3 lead to that output?
Last edited on
1
2
3
4
5
x y

6 1 	;initiated

6 2   	;x += y/3    =    x = 6 + (1/3)    =      6.3333  since it is an integer, it is rounded to 6, Y++ incremented y to 2




-BHill
try changing x to a float. See what your output is.

-BHill
It's integer division, so 1/3 = 0. Though actually it's 0 remainder 1. If you want the remainder, use 1%3 -- the modulo op -- as Code Assassin suggested)

0/3 = 0 R 0
1/3 = 0 R 1
2/3 = 0 R 2
3/3 = 1 R 0
4/4 = 1 R 1
...

So

6,1 : 1/3 = 0 -> 6+0, 1+1 = 6,2
6,2 : 2/3 = 0 -> 6+0, 2+1 = 6,3
6,3 : 3/3 = 1 -> 6+1, 3+1 = 7,4
...

Last edited on
Thank you andywestken, and sorry to the OP for getting it wrong.

-BHill
Topic archived. No new replies allowed.