Need Help implementing this algorithm

How do you read variables into the command lines?
Prompt:
Make a program that implements this algorithm in a function. The main program should accept the value of n on the command line without prompting. The standard output (cout) should be exactly one line consisting of a statement of n and the result terminated by a newline. In addition, the standard error output (cerr) should be exactly one line consisting of n followed by a space followed by the number of basic operations terminated by a newline. So, a run of the program with an input of 5 would look exactly like this:
$ ./filename 5
The highest power of 2 in 5 is 4. this is cout
5 27 this is cerr
but note that 5 and 27 are not necessarily correct.

Here is an algorithm for finding the largest power of 2 smaller than or equal to a non-negative integer n.

i = n;
j = i & (i - 1);
while( j != 0 )
{
i = j;
j = i & (i - 1);
}
At the end of the loop, i is the largest power of 2 smaller than or equal to the input value n. In this algorithm, & is the bitwise and operator (not the boolean && operator).
Here is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <iostream>

using namespace std;

int main(int argc)
{
   uint i, j, n;

   i = n;
   j = i & (i - 1);
   while (j != 0)
   {
      i = j;
      j = i & (i -1);
   }
   return 0;
}
Last edited on
Your professor is asking you to use command-line arguments. That's what the argc and argv arguments to main are for:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main( int argc, char** argv )
{
  std::cout << "The executable name is: " << argv[0] << "\n";
  for (int i = 1; i < argc; i++)
    std::cout << "Argument " << i << " is: " << argv[i] << "\n";
}
C:\> a 1 2 3 A B C Hello world!
The executable name is: a
Argument 1 is: 1
Argument 2 is: 2
Argument 3 is: 3
Argument 4 is: A
Argument 5 is: B
Argument 6 is: C
Argument 7 is: Hello
Argument 8 is: world!

Your goal is to take one command line argument (which is always a const char*), turn it into an integer (I suggest using std::stoi()) to convert it to an integer (which you might as well name n).

Then find the largest power of 2 less than or equal to n.

Use std::cout to print that value, formatted the same way as the text example given to you by your professor.

Then use std::cerr to print the number of “basic operations” you had to perform to find that value. You should have received prior instruction as to what that means (multiplication,division, etc; comparisons, etc; function calls?).

Hope this helps.
Topic archived. No new replies allowed.