954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

using the MOD operator

heyy all..I am really confused on the MOD (%) operator and how it is processed..

int n;
	cout << "Enter n: ";
	cin >> n;
	for (int i=1; i<=n; i=i+1)
		if ( (i % 2) == 0) //even
			cout << "-";
		else  //odd
			cout << "^";


What exactly is going on with the %..I want to understand the way that the computer processes that..I have no idea how to use it.

thankssss

meli123
Light Poster
42 posts since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

The modulo operator is the remainder operator. it says what is left after I divide x by y. So if you do 10 % 2 you get zero because 10 / 2 = 5 with nothing remaining. If you do 10 % 4 you get 2 because 10 / 4 = 2 so 4 goes into 10 two times and there will be 2 remaining. The way to calculate % is

let x = number to get the mod from
let y = number to mod against

mod = x - ((x / y) * y)

2 = 10 - ((10 / 4) * 4)

2 = 10 - (2 * 4)

2 = 10 - 8

2 = 2
this calculation only works when doing integer division
NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: