Alright. I finally finished problem number four (That's the stupid 1+1/2+1/4.....1/2^n one)...And now I've moved on to number five. It requires that we take some "Pseudocode" and make it into a real algorythm.
Here's the question:
"Implement the following pseudocode in C++. Apply the algorithm to n = 18. What is the value of s when the algorithm stops?
Step 1 Set d = 1 and s = 0
Step 2 while d <= n
Step 2.1 if n/d is an integer
Replace s with s + d
endif
Step 2.2 Replace d with d + 1
endwhile"
Alright...This is what I have so far:
Code:
#include <iostream>
int main()
{
float d = 1;
int s = 0;
int n;
std::cout << "Enter value for n: \n";
std::cin >> n;
while( d <= n)
{
if ( n/d >= 0)
s = (s+d);
break;
d = (d + 1.0);
}
std::cout << "The value of S is " << s << "\n";
std::cout << "D is " << d << "\n";
return (0);
}
The incorrect part is the 'if" statement:
This "if" statement is there to determine whether or not the number n is a whole number, correct? (Because n/d will always eqaul n, because d=1). So my guess is that I need to make up some way to look at "remainders"...like I need to use modulus "%" in this problem. I'm not exactly sure how to do that.
To make sure that nobody thinks I'm asking you guys to do it for me, here's a past example where I've dealt with modulus. We had to make a program that took a number grade as input, and outputted a letter grade with a + or - next to it (A+, b,C-, etc.).
Here's the code, which worked for me:
Code:
int grade;
int remainder;
char plus[1];
std::cout << "Enter numeric grade:\n";
std::cin >> grade;
remainder = grade%10;
if ((remainder == 0) || (remainder >=8))
strcpy( plus , "+");
else
if (remainder >= 4)
strcpy( plus , "");
else
if (remainder >=1)
strcpy( plus , "-");
if (grade <= 60)
std::cout << "The grade is an F\n";
else
if (grade <=70)
std::cout << "The grade is a D" << plus <<"\n";
else
if (grade <=80)
std::cout << "The grade is a C" << plus <<"\n";
else
if (grade <=90)
std::cout << "The grade is a B" << plus <<"\n";
else
if (grade <= 100)
std::cout << "The grade is an A" << plus
<<"\n";
else
std::cout << "Invalid grade\n";
return (0);
}
In this case, it was simple. All you had to do was divide the grade by 10 using mr. Modulus, and then you could set further parameters about the results...like if the remainder was 0, 8, or 9, you got a "plus", I think.
Anyways, how would I apply something like this to my little pseudocode problem? You can't just go 'n/d %10', right?
....
modulus is a dividing mechanism, right?
Ug. Sorry. Please point me correctly, oh wise ones.