I'm having trouble with the equations needed. we have learned the loops so far and i think this problem wants me to use the loops, and it looks like i need if-else as well. Here is the problem.
Write a program that asks the user to supply three positive integers k, m and n, with k being greater than 1. the program should compute the sum of all the integers between m and n that are divisible by k.
I don't know how to tell C that that i only want an integer evenly divisible by another. and then, i'm not quite sure how to get the addition of those integers done.
C programming help for beginning C class?
int sum = 0;
for (int i=m; i%26lt;=n; i++)
if ((i % k) == 0) sum += i;
Use the "modulus" operator ("%"). It's the remainder of the first number, when divided by the second. When this is zero, the first number evenly divides by the second one.
So, for example,
5 % 3 = 2,
6 % 3 = 0,
7 % 3 = 1
And if you don't want to include m or n in the list, change the loop from:
for (int i=m; i%26lt;=n; i++)
... to:
for (int i=m+1; i%26lt;n; i++)
And make sure m is the smaller of the two numbers. You can swap them if not.
=====================
As an alternative, you don't have to check every single number. You could write:
for (int i=(n-(n%k)); i%26lt;=m; i+=k)
if (i %26gt;=n) sum += i;
... which starts i off as the biggest multiple of k less than or equal to n, and increments i by k in each loop iteration.
You can get rid of the if statement if you initialize i a little better:
for (int i=((n-1+k)-((n-1)%k)); i%26lt;=m; i+=k) sum += i;
Reply:You must ensure that the loop terminates (so that it doesn't last forever). This is how:
#include %26lt;iostream.h%26gt;
void main()
{
int m,n,k , i ,sum = 0;
cout %26lt;%26lt; "Enter k: ";
cin %26gt;%26gt; k;
if( k %26lt;= 1)
cout %26lt;%26lt; "k must be greater than 1";
else
{
cout %26lt;%26lt; "Enter m: ";
cin %26gt;%26gt; m;
cout %26lt;%26lt; "Enter n: ";
cin %26gt;%26gt; n;
if(m %26gt; n)
{
m = m + n;
n = m - n;
m = m - n;
}
for(i=m ; i%26lt; n; i++)
{
if(i % k == 0)
sum +=i;
}
cout %26lt;%26lt; "Sum is " %26lt;%26lt; sum;
}
}
You have to check if m%26gt;n otherwise the loop
if(i = m; i%26lt; n; i++)
will never terminate.
We do this by swapping m and n if m%26gt;n
This is the classic way of swapping 2 numbers with only 2 variables:
m = m + n;
n = m - n;
m = m - n;
This is a complete program - compile and run this to see for yourself.
Reply:if (i % k)
{ i is evenly divided by k }
else
{ there is a remainder after the divide }
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment