For loop help

// Includes
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <conio.h>
using namespace std;

// GCD Function
int gcd(int m, int n)
{
int r; // Declares remainder

for (n != 0; n >> 0;) // Not Equal
{
r = m % n; // MOD Operator
m = n; // Assignment
n = r;
}
return m;
}
// Main Function
int main(int argc, _TCHAR* argv[])
{
int x, y, howMany;

cout << "\nPROGRAM GCD C++";
cout << "\nEnter how many GCD computations? ";
cin >> howMany;

for (int i = 0; i < howMany; ++i)
{
cout << "\nEnter 1st integer: ";
cin >> x;
cout << "Enter 2nd integer: ";
cin >> y;
cout << "\nGCD (" << x << " , " << y << ") = " << gcd (x , y) << endl;
}
return 0;
}


In the gcd function, i needed to change the while loop to a for loop, this was the while loop.

while (n != 0) // not equal
{
r = m % n; // modulus operator
m = n; // assignment
n = r;
}

i changed it to a for loop in the above coding, but when compiling getting and error saying warning: != operator has no effect; expected operator with side effect.

how can i fix this to make a correct for loop.

also if you could tell me how to paste the actual coding page in visual studio 2012 to make it much nicer and neater that would be great.
code tags (without the spaces in the brackets): [ code ] put code here [ /code ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <conio.h>
using namespace std;

// GCD Function
int gcd(int m, int n)
{
int r; // Declares remainder

for (n != 0; n >> 0;) // Not Equal
{
r = m % n; // MOD Operator
m = n; // Assignment
n = r;
}
return m;
}
// Main Function
int main(int argc, _TCHAR* argv[])
{
int x, y, howMany;

cout << "\nPROGRAM GCD C++";
cout << "\nEnter how many GCD computations? ";
cin >> howMany;

for (int i = 0; i < howMany; ++i)
{
cout << "\nEnter 1st integer: ";
cin >> x;
cout << "Enter 2nd integer: ";
cin >> y;
cout << "\nGCD (" << x << " , " << y << ") = " << gcd (x , y) << endl;
}
return 0;
}


Line 13 is not a proper for loop...
I think u are better off with a while() loop there but do it like this:
1
2
3
4
5
6
7
8
9
while(1)
{
m = m % n;
if(m == 0)
   return n;
n = n % m;
if(n == 0)
   return m;
}

if u need to keep track of the remainder that's another task ;)
Last edited on
Alright thank you for the help, i shall use a while loop.
Topic archived. No new replies allowed.