You are here:

C++/Pseudo code

Advertisement


Question
QUESTION: Hi there am new to programming and this has proved to be difficult to me.Please help me
B.  A user has given you the following pseudo code for a task he has to perform

a.   j  80
b.   do while j ≠ 0
c.      j  j -5
d.      if j is divisible by 3 then
goto line 2
e.      display j
f.      if there is no remainder when j divided by 35 then
goto line 8
g.   loop
h.   display “Done”

a.   Convert the pseudo code to structured C++ code.

b.   What is the output of the program?


ANSWER: Your input got a bit messed up, but I'm pretty sure I get what you're asking.  Given the way it's structured, I suspect this may be a homework question, or otherwise a question from a book, so I prefer not to give a direct answer, but I will assist you in arriving at the answer yourself.  I apologize in advance if I have misinterpreted, and this is actually not a homework question.  Either way, once you have read my answer, give it a shot yourself and send your result back to me as a followup and I'll let you know if you've got it.

OK, lets take this line by line.  Some lines are considerably easier than others, of course.

a. j = 80

For this line, you simply need to declare your variable and set its initial value.  Easy enough.

b. do while j != 0

This line is initiating a loop.  The specific wording here is do/while, though I suspect that's merely a logical way to represent the loop in writing than an actual hint that a do/while loop is needed.  A standard while loop will suffice.  The condition for the while loop is that j cannot equal 0.  If you are unfamiliar with while loops, they are structured like so:

   while (condition)
   {
       // body of loop
   }

The condition is some piece of code that equates to a value, and so long as the value is non-zero, or true, the loop will continue.  Typically, a boolean condition is used which returns either true (non-zero) or false (zero).

c. j = j - 5

Here we simply need to decrement the value of j by 5.  There are many ways this can be accomplished, but my favorite way to decrement a variable by an arbitrary amount is to use the binary operator -=.  The -= operator instructs the compiler to take the variable listed to the left of the operator and subtract the amount to the right of the operator, and store the result back in the variable on the left of the operator:

   myInteger -= 23;

The above piece of code would subtract 23 from the variable myInteger and store the result back in myInteger.  This is perfectly equivalent to writing:

   myInteger = myInteger - 23;

d. if j is divisible by 3, then goto line 2

This is one of the more complex lines of the pseudo code.  Here we need to determine if a number is divisible by 3, and if it is, then we need to go back to line 2, which is "do while j != 0."  What this means is that if the number is perfectly divisible by 3, with no remainder, then we want to ignore the rest of the loop and simply restart the loop.

First we have to know how to determine if a number is perfectly divisible by 3.  The easiest way to do this is with the modulus operator provided in C++.

The modulus operator (%) is very similar to the division operator (/), except that instead of returning the number of times a number is divisible by some other number, it returns the remainder left over.  So, for example, when you divide 7 by 5, the result is one, because 5 will only go into 7 one time, with a remainder of 2.  That means that 7 modulo 5 is 2, because after 7 has been divided by 5 as many times as it can, there is 2 left over.

So, then, using the modulus operator, you can determine if any number is divisible by any other number by checking that the remainder (modulus) is 0.

Once you determine if j is divisible by 3, then you have to react accordingly, either restarting the loop or continuing to execute the rest of the loop.  There are a few ways to do this.

First, there is the continue keyword.  When you are in a loop, there are some special keywords that will alter the execution of the loop.  The break keyword is one, which will prematurely end the execution of a loop.  The continue keyword is another, which will prematurely end a single iterator of the loop and restart the loop from the beginning.  Consider the following code:

   int myInt = 9;
   while (myInt > 0)
   {
       if (myInt > 0)
         continue;
       myInt = 0;
   }

This loop will never actually end, even though the loop explicitly sets myInt to 0.  The reason it will never end is because before myInt is set to 0, a continue statement causes the loop to restart.

Another way to keep further code in a loop from executing is to reverse the logic if your condition.  Instead of thinking, "if j is divisible by three, I need to restart," think, "if j is not divisible by three, then I need to do these other things."  It's a subtle difference, but one that makes the code completely different.  Personally, I tend to prefer this approach, but either way is acceptable.  Below is the previous infinite loop rewritten to use the reverse logic:

   int myInt = 9;
   while (myInt > 0)
   {
       if (myInt <= 0)
       {
         myInt = 0;
       }
   }

There are also actual goto commands in C++, but they are *very* strongly discouraged.  A goto command can occasionally make code simpler, but more often than not, a different approach is preferred.  I know many, many programmers who staunchly oppose the use of gotos and will deride anyone who uses them at all.  Unless you are absolutely certain of your use of a goto and will willingly defend its use against voracious attack, do not use a goto.

e. display j

There are many ways of displaying output to screen.  Pick one and go with it.  Generally, printf or cout are the way to go.

f. if there is no remainder when j divided by 35, then goto line 8

This line, while worded differently, is remarkably similar to line d.  The same style of modulus operation will tell you if the number is divisible by 35.  The big difference here is that instead of continuing the loop, we must stop the loop.  Remember that in addition to the continue keyword, there is the break keyword.  That is the keyword required in this instance.

g. loop

Well, thanks to the way C++ works, so long as line c through f have been included in the body of the while loop, the loop will happen automatically.  This line exists in the pseudo code purely to delineate the actual loop contents from the rest of the code.

h. display "Done"

As I said with line e, there are numerous ways to display things on screen.  Pick one and go with it. :)

So, I've tried to give thorough explanations of what each line is asking for and how it might be accomplished.  I leave the rest to you.  Write up the C++ code and run it, see what you get back.  Please feel free to send me your resulting code and output as a followup and I will let you know if it is correct and help you resolve any issues.

If anything I said was unclear or you otherwise have any further questions, don't hesitate to ask.

---------- FOLLOW-UP ----------

QUESTION: I av tried to come up with the following.hope its the correct output.
//Pseudo code
#include <iostream>

using namespace std;
int myInt = 80;
int main()


{

 //j = 80
  j= myInteger -=5;
  while (myInt > 0);

  {
      if (myInt <= 0); //if j is divisible by 3, then goto line 2
      {
         myInt = 0;
      }
  
  cout<<"j";  //display j   //if there is no remainder when j divided by 35, then goto line 8
     
  cout<<"Done"endl;
  }
}
  return 0;


Please also help me on this.thanx

A programmer is trying to write a program that adds corresponding elements of two arrays of the same size, and store the result into a new array. He has written the following program.  Complete the code.

#include <iosteam.h>

int main()
{
  int arrayA[ ] = {12, 36, 18, 21};
  int arrayB[ ] = {16, 24, 27, 30};

  // declare the third arry
  int arrayC[5];

  // add the elements of arrayA and ArrayB and store in arrayC
     … incomplete
  // output the elements of the array using a pointer
  int* p = &arrayC;
     … incomplete
  return 0;
}










ANSWER: OK, you took my given code a bit too literally.  I was showing you examples of specific bits of code that were relevant to your question without directly giving code that would answer your question.  That's ok, though.  You gave it a shot, and that's all I asked.  First I'll go through your code and explain what it's doing, then I'll give you a workable solution to the original pseudo code.

 //Pseudo code
 #include <iostream>

 using namespace std;
 int myInt = 80;
 int main()
 {

   //j = 80
   j= myInteger -=5;
   while (myInt > 0);
   {
     if (myInt <= 0); //if j is divisible by 3, then goto line 2
     {
       myInt = 0;
     }

     cout<<"j";  //display j   //if there is no remainder when j divided by 35, then goto line 8
 
     cout<<"Done"endl;
   }
 }
 return 0;

There are several compile errors with this code.  First, note that your return 0 exists outside the body of the main function.  Note also that when you declare the global integer, you declare it as myInt, then when you try to assign the number to j, you write it as myInteger.  There is no variable called myInteger.  Additionally, you never actually declare the variable j, you just try to use it.  You must declare a variable before using it.  Finally, you must add an extra << operator before you put the endl in the cout statement.

Now lets look at logic errors in the code.  Please note that I am assuming that, at this point, all compile errors have been fixed.  Ignoring what the code is supposed to accomplish, let's look at what it's doing.  First, you create an integer, j, and set its value to the value of myInt - 5, 75.  You also change the variable myInt at this point, which is incorrect.  Next, you begin a loop based on myInt.  The code really ought to loop based on j, and use j within the loop, not myInt.  Additionally, you have a semicolon at the end of the line with the while, meaning there is no loop body.  In fact, this while loop has just been made infinite, because the variable myInt (or j if you fix the code) will never change.  Next, your if statement.  As previously stated, it needs to be based on the variable j.  Also, just like the while loop, you have a semicolon at the end of the if line, so the statement has no body.  Next, the line where you attempt to output j, you have the j in quotation marks.  This means the line will literally just output the letter j, not the value of j.

Let's assume that all logic errors in the current code are fixed, then the program would simply loop infinitely and print out the following, over and over:

 jDone

OK, now, let's go ahead and look at a listing that is a fully functional translation of the pseudo code into C++.

#include <iostream>
using namespace std;

   int main()
   {
       //a. j = 80
       int j = 80;

       //b. do while j != 0
       while (j != 0)
       {
         //c. j = j - 5
         j -= 5;

         //d. if j is divisible by 3 then
         if (j % 3 == 0)
         continue; //goto line 2

         //e. display j
         cout << j << endl;

         //f. if there is no remainder when j divided by 35 then
         if (j % 35 == 0)
         break; //goto line 8
       } //g. loop

       //h. display “Done”
       cout << "Done" << endl;
   }

I'm not going to go into too much detail about this code, because it's basically all covered in my original response.  The primary things to note are the continue call and the break call.  Each of these controls the program flow during the loop.  The former will prevent the rest of the loop from executing and start the next iteration, while the latter will exit the loop immediately.

I hate to ask this, but I do want to keep these items a bit separate (and I want to get this answer back to you now, without further delay), but would you mind posting the extra question to me either as a followup or as a new question so that I can address it separately?  Thank you.

As always, if you have further questions about what I've said or just something else you wish to know, do not hesitate to ask.

---------- FOLLOW-UP ----------

QUESTION:
A. Given the following input file called personnel.txt consisting of four columns, employee name, PIN, rate per hour and number of hours worked

    Kamau   A1002342Q   77.32   37
    Njoroge   A2131155Q   88.32   40
   Cheprotich   B3232415W   96.54   40
   Taabu   A4344563W   90.80   35

Write a C++ program that will do the following:
a)   Read data from the input file above located in folder c:companypayroll.
b)   Calculate the net pay due for each employee
c)   print the output so that it is organized as follows

       PIN      Name          Netpay   ----------------------------------------------------------
  A1002342Q   Kamau      2860.84
  A2131155Q   Njoroge      3532.80
  B3232415W   Cheprotich   3861.60
  A4344563W   Taabu      3178.00  

Answer
We'll start here:

-----

A programmer is trying to write a program that adds corresponding elements of two arrays of the same size, and store the result into a new array. He has written the following program.  Complete the code.

#include <iosteam.h>

int main()
{
int arrayA[ ] = {12, 36, 18, 21};
int arrayB[ ] = {16, 24, 27, 30};

// declare the third arry
int arrayC[5];

// add the elements of arrayA and ArrayB and store in arrayC
… incomplete
// output the elements of the array using a pointer
int* p = &arrayC;
… incomplete
return 0;
}

-----

The question here is really one of loops and pointer arithmetic, though mostly loops.  It's easy enough to accomplish: loop enough times for each index in the two arrays, add them together and store them in a third array.  Then, loop again (for the same number of times) and output the current value pointed to by p, then increment p.  It'll look something like:

   for (int i = 0; i < numElements; ++i)
   {
       arrayC[i] = arrayA[i] + arrayB[i];
   }

   int* p = &arrayC;

   for (int i = 0; i < numElements; ++i)
   {
       cout << *p++ << endl;
   }

Notice how I use the ++ operator on the p.  It's the post-fix version, so the increment will execute after that line of code has run, so it'll first use p in its current state for the line of code, and after all's done, increment p.

Moving on to the next question:

-----

A. Given the following input file called personnel.txt consisting of four columns, employee name, PIN, rate per hour and number of hours worked

   Kamau A1002342Q 77.32 37
   Njoroge A2131155Q 88.32 40
  Cheprotich B3232415W 96.54 40
  Taabu A4344563W 90.80 35

Write a C++ program that will do the following:
a) Read data from the input file above located in folder c:companypayroll.
b) Calculate the net pay due for each employee
c) print the output so that it is organized as follows

      PIN Name          Netpay ----------------------------------------------------------
A1002342Q Kamau 2860.84
A2131155Q Njoroge 3532.80
B3232415W Cheprotich 3861.60
A4344563W Taabu 3178.00

-----

This is a slightly more complex problem.  It shouldn't take more than about an hour to work up the code for it, though.  You'll need to do a bit of file I/O, some line parsing (ideally to store into a class or struct), some simple math, and some simple output.  The file I/O and text parsing will be the trickiest parts of this one.  As before, I'm not going to outright give you the code to this one.  I'll give you some pointers on how the accomplish the different parts, but I want you to give it your best shot first.  Remember that the code I'm giving, while applicable, is not directly useful for this specific program.  It's to show you how the functions work, not give you the exact code needed to solve this problem.

Let's start with file I/O.  You specifically need to open a text file and read a line.  This is very easy to set up.  First, how to open a file for reading:

   FILE* pFile = fopen("filename.txt", "rt");

The fopen call takes two strings.  The first is simply the file name (including path).  The second string is a set of flags.  The flags are read in as a character string and then parsed.  By default, fopen opens a file in text mode.  However, you can override that and open a file in binary mode.  This is done by passing the "b" flag.  Some people even prefer to explicitly declare that a file is being opened in text mode by providing a "t" flag (as has been done in my example).

The other important part of the open flags is the file operation types allowed.  You can open a file for read, write, appending, read and write (2 types), or reading and appending.  These flags are:

  "r" - read; if file is not found, call fails
  "w" - write; if file already exists, it's overwritten with a new file (previous contents destroyed)
  "a" - append; if file exists, opens and will write at end of file, otherwise, creates a new file
  "r+" - read and write; if file is not found, call fails
  "w+" - read and write; if file already exists, it's overwritten with a new file (previous contents destroyed)
  "a+" - read and append; if file exists, opens and will read from beginning of file and write to end of file, otherwise, creates a new file

So, by combining the "b" and "t" flags with the various mode flags, you can open a binary or text file for reading or writing in many different ways.

Now that you have a file open, there are many different operations to read data from the file.  In this particular case, we want to read one line at a time.  This is done with the fgets function.  The fgets function takes three parameters: the string storage location, the maximum size to read, and the FILE*.  This will look something like this:

   char storage[100];
   fgets(storage, 100, pFile);

This will read up to 100 characters, or a single line, whichever is shorter.  You can then parse the data appropriately and repeat the process.  I'll get to the data parsing in a minute.  First let's finish up file I/O.

The final part of file I/O you'll need for this problem is the fclose function.  This function closes out an open file.  If you do not have a corresponding fclose call for each successful fopen file, you will leak data.  The fclose file is the simplest of all file I/O functions.  It simply takes in the open FILE*:

   fclose(pFile);

The other somewhat tricky part of this program is text parsing.  You need to be able to take a line of text and extract each piece of it, reinterpret it, and store it somewhere.  For this, you'll want to learn how to use strtok.

The strtok function is used in two parts.  First you have to initialize it, then you have to repeatedly execute it to walk through the string.  The function takes two parameters, both of which are strings (similar to the fopen function).  The first string is the string that needs to be tokenized (or broken into pieces).  The next string is the list of delimiters, or separating characters, which determines where a token ends.

To initialize the strtok function, you simply pass it the string you wish to tokenize and the delimiters you want to use.  Something like this:

   char tokenString[] = "This is the string I wish to tokenize.";
   char delimiters[] = " .";
   char* pCurTok = strtok(tokenString, delimiters);

Once strtok has been initialized, you need to set up a loop and continuously execute strtok until all tokens have been gathered.  Something like this:

   while (pCurTok)
   {
       cout << pCurTok << endl;
       pCurTok = strtok(NULL, delimiters);
   }

Notice that when you're looping, you provide NULL as the first parameter.  This is because strtok copies the string internally and keeps the buffer around.  If you provide a valid string as the first parameter again, it will reset the internal buffer and restart tokenizing from the beginning.  If you passed tokenString as the first parameter over and over, you'd only ever get the first token in the string.

OK, I think that should be enough to get you started.  If you have any questions about anything I've written, feel free to ask.  Once you have attempted the second program, please send the code to me as a followup and I will look it over and offer any necessary assistance with it.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C++ code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2016 About.com. All rights reserved.