Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

At the beginning of the program, add

#include <string.h>

Now in main() add two more variables:

int price;
char car_model[100];

Then, inside the switch(), instead of printing the information, you set these two values, then print them after the end of the switch():

        switch(d)
        {
            case 1:
            strncpy(car_model, "ZEN", 100);
            price = 4000;
            break;

            case 2:
            strncpy(car_model, "OMNI", 100);
            price = 5000;           
            break;

            case 3:
            strncpy(car_model, "Volkswagen Polo", 100);
            price = 15000;

            break;
        }

        printf("\n You have selected %s | Cost %drs per day \n", car_model, price);
        break;

Do the same for the other two inner switch() statements and you should be good to go. You then can use these variables at the end of the program as well.

Mind you, there are all sorts of ways to simplify this program further; I expect you'll see some of them if you look.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Has your coursework covered data structures yet? You can bundle the car model and price up into a struct type and save yourself some hassle:

struct Car
{
    char make[16];
    char model[16];
    char year[4];
    int price;
};

This let's you have a record of the all the car makes and models which in each category:

const struct Car SUV[] = { 
                              {"Tata", "Sumo", "2010", 9000},
                              {"Chevrolet", "Tavera", "2009", 12000},
                              {"Trax", "Toofan", "2011", 10000}
                          };
const int SUV_COUNT = 3;

You can use these records to display the model and price info for the category:

        case 2:
        printf("\n You have chosen Long Trip Vehicles \n");
        printf("\n Vehicles Available are \n");
        for (i = 0; i < SUV_COUNT; i++)
        {
            printf("%d: %s %s, ", i + 1, SUV[i].make, SUV[i].model);
        }
        printf("\n\n ----------------------------- \n");
        printf("Enter the number of the car model you want: ");
        scanf("%d", &r);
        r--;
        printf("\n You have selected %s %s %s | Cost %d rs per day \n", 
               SUV[r].year, SUV[r].make, SUV[r].model, SUV[r].price);

        break;

You would do the same for each of the other two categories.

You can similarly bundle the customer info into a single struct, like so, with a pointer to the car information:

struct Customer 
{
    char name[32];
    int age;
    char address[3][32];      /* three lines of 32 chars each */
    struct Car* vehicle;
} customer;

You could then read in the customer information at the beginning of the program, and print it out again at the end along with …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think that if you actually open up the file grade.txt, you'll see that there is no actual line with the text EOF on it; rather, in the example given, the EOF stands in the for the actual end-of-file marker, which isn't a printable character.

In any case, Python provides an easy way to iterate through a text file without using readline() or any explicit test for completion, by using just a for: loop:

inFile = open('grade.txt', 'r')
for line in inFile:
    lst = line.split(',')
    print(lst)
inFile.close()

Another way to do this, which may prove even more useful, is to use the with statement. Let's try that, with a little more formatting to the output as well:

with open('grade.txt', 'r') as inFile:
    for line in inFile:
        lst = line.split(',')
        for element in lst:
            print("{0:<15}".format(element.strip()),  end=' ')
        print()

The major advantage of the with is that you don't need to explicitly close the file.

I could also add that files of this type (called a comma-separated value file or CSV file), are especially common, so much so that Python has a special library just for handling the data from them.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The main problem I see is that you are indexing the arrays incorrectly, which is probably the cause of the segfault. In C++, arrays are zero-indexed, that is to say, an array arr[5] would have elements arr[0], arr[1], arr[2], arr[3], and arr[4]. When you try to access arr[5], you overrun the array and get an access violation.

What this means is that you need to fix all of the array indices in the program. Fortunately for you, I've done just that:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(NULL));

    //Constants
    const double SALESTAX = 0.08;
    const double DISCOUNTRATE = 0.05;
    const double DISCOUNT = 95;

    //Counts
    int customer, book;

    //Customer arrays
    string customer_Non[5][2]; // 1 = name, 2 = address
    int customer_Num[5][2]; // 1 = age, 2 = receipt#
    int quantity = 3; //3 books per customer

    //Book arrays
    string book_Non[5][3][3]; // 1 = book number, 2 = Title, 3 = Author
    int bookAisle[5][3]; // 1 aisle per book
    double bookPrice[5][3][2]; // 1 = book price, 2 = discount

    //Calculations
    double calculation[5][5];
    /* 1 = subtotal, 2= total discount, 3 = subtotal and discount
     * 4 = sales tax, 5 = Total to be paid */

    //Validations
    int customerValid [5][2]; //1 = name validation, 2 = address validation
    int bookValid[5][3][3]; //1 = booknum validation, 2 = title validation,
                            //3 = author validation
    ofstream fOut;
    fOut.open("Project4_A00635756_Output.txt");

    for(customer = 0; customer < 5; customer++)
    {
        customer_Num[customer][1] = rand() % 999 …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

BTW, just as Woooee pointed out about updateboard() (which can just be update(), given that the board part is implied), you can simplify printboard() fairly easily:

def display(self):
    for i in range(0, 3):
        for j in range(0, 3):
            print(self.board[i][j])
        print() 
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think that you're having some conceptual issues with inheritance, resulting in what is sometimes called 'spaghetti inheritance' (that is, inheriting from an otherwise unrelated class just to get a desired behavior). There's a simple test to see if the inheritance is valid: is a Board a specific example of a Human in your model? If it isn't then Board shouldn't be inheriting from Human.

Perhaps a change of names will clarify things a bit. Replace Human with the more general name Player, and subclass Player with HumanPlayer and AiPlayer. Separate the playing behaviors of Board out into AiPlayer, and have Board be a representation of just the board itself. This should disentangle your current inheritance structure a bit.

On a secondary note, you might want to separate the part of makeboard() which initializes the board into a separate clear() function. If you then have it called by the c'tor rather than makeboard(), follwed by a call to updateboard(), it will allow you to eliminate makeboard() entirely.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the future, when getting this kind of error, please post the traceback and error message as well as he code where it is occurring. I was able to work out the problem this time, but the traceback makes it much easier to figure out the problem once you learn how to read it.

Also, always mention the version of Python you are using; Python 3.x, which is what you seem to be working in, is very different from the older Python 2.x regarding several things, including basic console I/O.

The specific error you are getting is on line 22:

    numPumpkins = input("Enter the number of pumpkins: ")

You are reading in the user input as a string, but - unlike in the code below it on line 29 - you don't convert it to an integer. You need to write it as:

    numPumpkins = int(input("Enter the number of pumpkins: "))

Note that even this isn't foolproof; if the user makes a typing mistake or deliberately enters a value other than an integer, an exception will get raised. To do this properly, you really should wrap the line in a while: loop, and then in a try:...except: block.

    numPumpkins = 0
    while numPumpkins == 0:
        # get the input value separately so you can include it in any error msgs you print out
        numString = input("Enter the number of pumpkins: ") 
        try:
            numPumpkins = int(numString)
        except ValueError:
            print("{0} is not an integer. …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, the error message is exactly correct - you invoked a class method (info(), which as written does not take a self argument) with the name of an instance, which in Python is the same as passing it an argument (namely,help_ itself). Just to make it clearer what is happening, you need to know that these two forms are equivalent:

help_.info()

and

Help.info(help_)

You should either invoke it with the name of the class, and no arguments, instead

Help.info()

or else add a self argument to the method parameters.

As an aside, I would like to point out that there is a standard module metadata variable named __author__ which you usually would use for this purpose:

__author__ = 'Jerome Smith'

This automagically gets included in the docstring for the module, if you use the standard help() built-in function. For more flavor, see PEP-258 for details on docstrings and the help() function, and this thread on StackOverflow about the Pydoc metadata variables.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In retrospect, I would have used sample() had I thought of it. I was thinking mainly in terms of reorganizing the entire 'deck' of questions, but your solution makes more sense.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Yes, but sample() returns a list of samples out of the tuple; it doesn't modify the tuple itself, the way shuffle() does. When I ran shuffle on a tuple, I got the following traceback:

>>> random.shuffle((1, 2, 3, 4))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 288, in shuffle
    x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment

I have to admit that sample() is in some ways a better solution, as you can use it to limit the size of the questions list, obviating the need for the enumerate(). I wish I'd thought of using it myself.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

When you say that import random failed, just what do you mean? If you got an error message, post it with the full traceback. Otherwise, did it simply not do what you expected it to?

I would recommend using the random.shuffle() function on the series of questions; however, to do that, you'll need to make a small change, which is to make the outer tuple holding the question-answer pairs into a list.

questions = [("Denis Glover wrote the poem The Magpies ", 'yes'),
    ("God Save the King was New Zealand’s national anthem up to and including during WWII ", 'yes'),
    # several lines omitted for clarity...
    ("The Treaty of Waitangi was signed in 1901 ", 'no'),
    ("Aotearoa commonly means Land of the Long White Cloud ", 'yes')]

random.shuffle(questions)    # automagically rearrange the questions in a random order

Note that all I did was change one pair of parentheses to a pair of square brackets, and add the call to random.shuffle(). The reason for changing questions from a tuple to a list is simply that tuples are immutable: once they are created, they cannot be altered. You can reassign a different value to the variable, but you can't change the tuple itself. Lists, on the other hand, are mutable, so the shuffle() function can work on them.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Adding a score is fairly easy; all you need to do is have a variable score which is set to zero to start, then for every right answer, add one to it.

# make input equal to Python3 style input even in Python2
try:
    input = raw_input
except:
    pass


print("Welcome to my yes or no quiz!")
questions = (("Denis Glover wrote the poem The Magpies ", 'yes'),
             ("God Save the King was New Zealand’s national anthem up to and including during WWII  ", 'yes'),
             ("Kiri Te Kanawa is a Wellington-born opera singer  ", 'no'),
             ("Phar Lap was a New Zealand born horse who won the Melbourne Cup  ", 'yes'),
             ("Queen Victoria was the reigning monarch of England at the time of the Treaty  ", 'yes'),
             ("Split Enz are a well-known rock group from Australia who became very famous in New Zealand during the 80s  ", 'no'),
             ("Te Rauparaha is credited with intellectual property rights of Kamate!  ", 'yes'),
             ("The All Blacks are New Zealands top rugby team ", 'yes'),
             ("The Treaty of Waitangi was signed at Parliament  ", 'no'),
             ("The Treaty of Waitangi was signed in 1901 ", 'no'),
             ("Aotearoa commonly means Land of the Long White Cloud   ", 'yes'))

score = 0
maxQuestions = 0
while maxQuestions <= 0 or maxQuestions > len(questions):
    try:
        maxQuestions = int(input("Enter the number of questions to ask (more than 0 and less than to {0}): ".format(len(questions))))
    except ValueError:
        print("Please enter an integer value.")
        maxQuestions = 0

for count, (q, right) in enumerate(questions): …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would try asking the user for the number of questions to ask before the for: loop, and use enumerate() to get a count of how many questions have been asked. Then, add an if: clause that checks whether you have reached the number of questions, and break if you have.

The enumerate() is a bit tricky, so I'll give that part to you:

for count, (q, right) in enumerate(questions):

The reason for this is because enumerate() returns a tuple containing the enumerated value, and the next value in the argument. Since the next value in questions is itself a tuple, you need the parens around the two variables to force it to unpack the inner tuple.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Yes, please post your existing code for us, otherwise we won't know how to adivse you.

revelator commented: thanks, please do this help for me :) +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Certainly you can nest lists inside another list, and you wouldn't necessarily need another method to do it. If you already have the list to insert, the it is as easy as

>>> alist = [1,2,3]
>>> blist = [4,5,6]
>>> clist = []
>>> clist.append(alist)
>>> clist.append(blist)
>>> clist
[[1, 2, 3], [4, 5, 6]]
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few questions:
Are BufferPixels, Bpp, height, and width instance variables? They aren't declared or passed anywhere in the method as shown.

Why couldn't unsigned char* Pixels = &BufferPixels[0]; be written as unsigned char* Pixels = BufferPixels;?

What does Bpp represent? Pixel depth (bits per pixel)? If so, shouldn't the pixels be a 32-bit unsigned, rather than an 8-bit unsigned (even if only 24 bits are actually used at times)? Or is this the reason why you have unrolled the loop by three (or four, in cases where Bpp is greater than 24)?

Why is Result a void pointer?

Do the pixels have to be aligned on word or doubleword boundaries in order to be rendered correctly? Is byte order significant?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, are you using a system Date (java.util.Date) or a database Date (java.sql.Date)? I am assuming the former, but if you are working with a SQL database, you may be talking about the latter.

Either way, you will want to use one of the Calendar classes, probably GregorianCalendar. The Calendar classes all support a method called .add() which will do the job you want.

However, when adding or subtracting time from a Calendar object, you need to tell it what incement of time to add - an hour, a day, a year, a month, whichever. so what you would have is something along these lines:

Calendar cal = new GregorianCalendar();   // default is current time and default zone
cal.add(Calendar.DATE, 5);

Note that I haven't addressed the question of time zone, which you may neecd to do.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, it's not so much that (especially since 60 lines isn't all that much) as it is the tendency of newcomers to simply post their code without actually asking a question about it.

In this case, we'd also need to see where you are setting c_num, as well.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I believe that what you are looking for is the import statement. If you have a Python file, say test.py, and wish to run the program in that source file while in the interpreter prompt, you can enter

import test

and, provided that the file test.py is in the same directory that you launched the Python interpreter from, you should be able to run the program, as well as access it's variables, call it's functions, etc. once it is imported.

Mind you, this is not the usual manner in which Python programs are run. It is more typical to have the .py files associated with pythonw.exe, which allows you to run the program just by double-clicking on the file. See the link Gribouillis posted for more details.

If, rather, you are looking to edit and test the program in question, you would be better off running IDLE (and simple integrated development environment that should have come with your Python distribution), which has a window for the interpreter prompt but also allows you to open separate editing windows for working on your source files. If you launch IDLE, the go to File-> Open File... and select your test.py file, it will open a window showing the source code; you can then run the program by going to Run-> Run Module in that window. IDLE takes a bit of getting used to, so you might consider a more powerful IDE such as Dr Python (very simple to learn …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is that you aren't resetting either count or totalGrade before beginning the second loop. also, in both loops, you can (and probably should) move the calculation of average out of the loop body.

I think you'll also have a problem with the second loop's end condition, as you aren't changing plusStudents anywhere in the loop.

Mind you, there are ways to avoid having to have two otherwise identical loops one right after another. Has your course covered functions yet? For that matter, are you certain that these should be separate loops, as you have it here? I suspect that what you want is to nest the loops, with the outer loop being the test for whether to add more students, and the inner loop being the one to read in the test grades.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first step in solving this problem, I think, is learninig to indent your code in a consistent and legible manner; since this is Java, I recommend following the official Java Style Guide, at least as far as the basics are concerned.

import java.util.Scanner;
import java.io.*;

public class prog166d2 {
    public static void main (String[] args) {
        int hours = 10;
        int wage = 4;
        int emp = 3;
        int maxemp = 6;   //maximum number of employees
        int count = 0;
        int counter = hours * wage;

        while(count <= (maxemp - emp)) {
            while(emp <= maxemp) {

                System.out.println("\nWages for " + emp + " employees\n");

                while(hours <= counter) {
                    int calc = hours * wage * emp;
                    System.out.println("For " + hours + " hours worked, the wages are " + calc + " dollars");
                    hours += 10;
                }

                while(hours == counter) {
                    hours = 10;
                }
                emp++;
            }
            count++;
        }
    }
}

Once you've done that, you'll see that your outermost loop is not actually necessary - you only need the first inner loop and the loop inside of that one. The test for hour being equal to counter is also unneeded - if it reaches that point, it is always going to be equal to counter, while on the second pass it will always be unequal. I would add that counter itself is unneeded, as it will always equal 40, though it will be different if you ever change wage; there's no actual relationaship between …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What is the expected result?

I suspect that you have misunderstood the last part of the summation formula. I suspect it is supposed to go more like:

         n
       ----
       \         n 
   1 + /     (-1)  n! / (x - n)
       ----
       i = 2

or,

1+2!/((x-2))-3!/((x-3))+4!/((x-4)) - ... n!/((x-n))

which means that for the example given, it would be

1+2!/((x-2))-3!/((x-3))+4!/((x-4))-5!/((x-5))

Note that if n is less than 4, the formula goes shorter than the example given. So, for example, for n = 3, the formula would simply be

1+2!/((x-2))-3!/((x-3))

The practical upshot of this is that you need to compute the sum using a loop.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Before we go anywhere with this, I want you to be clear about two things. First, that this is actually two different programs which you'll need to write, and second, that you will need to be the one to write them. We can give advice and help, but we cannot and will not write the program for you.

Having said that, let's start with what you do know how to do. Can you write a simple class layout, and declare the various local and instance variables you will need for the first program?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In the declaration of struct author, you define down as type link, which is a typedef for struct author*. What you actually want is for it to be a ptr (that is, struct book*). Thus, you'll want to move the typedef of type ptr up to before the definition of struct author, and change link down; to ptr down;.

typedef struct author *link;
typedef struct book *ptr;

struct author
{
       char name[20];
       link next;
       ptr down;
};
typedef link LIST;
typedef link pos_author;


struct book
{
       char title[20];
       int year;
       int page;
       ptr down;
};
typedef ptr pos_book;

Oh, and you misspelled 'title', BTW. HTH.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The ampersand actually marks the character which is to be used as the hotkey; if you look at the menu as it actually is rendered, you'll see that those letters all are underscored. In the case of 'Exit', the 'x' is the hotkey character (that is to say, if you hit ALT-X, it would cause the program to exit), so the ampersand is directly before it. It only seems out of place because all of the other items have hotkeys with the first letter of the word, but this does not need to be the case, as you can see.

As for why 'x' is used for exit rather than 'E', it is because, according to the Windows style standard, Alt-E is used as the hotkey for the Edit menu, even if it isn't present in the application.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rather than sharing the code this way, which has some serious disadvantages (no versioning, having to manually cut and paste the code into place, risking overwriting the good code with the older code, etc.), I would suggest finding a source repository such as SourceForge or GitHub and share your code through that. The advantages are multiple, as you'd be able to easily track what changes were made when, and by whom; have multipled separate lines of development for testing purposes; be able to merge changes from several different people; and so forth. Believe me, once you've worked with a decent distributed version control system, you won't want to do any project without it.

Of course, this assumes an open-source project; but then again, you'd hardly be posting your code here if it weren't, would you? Even if it is meant to be closed-source, most source control sites allow you to set up a private, members' only repo, though it usually costs money.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

EDIT: I originally thought that this was a different problem, but then I noticed that you were, in fact, reading in a number and not a character. My error.

Looking over the code again, it's simply that you aren't putting break; statements at the end of each case of the switch().

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you should always use int as the type for main(), not void. While some compilers allow for other return types, the only really correct (in the sense of portable and matching the standard) declaration is int main() (or, when using command-line arguments, int main(int argc, char* argv[])).

Second, you don't #include the necessary headers, at least not in the sample of code you have given us. This is important because you also re-declare a function free() which is significantly different from the Standard C free() declared in <stdlib.h>. If you had included the headers, your com[piler should have given a multiple declaration error.

Third, the argument passed to malloc() is simply erroneous; you are allocating what you assume to be the size of a pointer (though it would actually depend on the system and compiler), but are returning it to the elements of an array of pointers to struct mem_chunk, which is significantly larger than 4 bytes long. Assuming you intended to populate the array with struct mem_chunk structures, the correct call should be:

 temp[i]=malloc(sizeof(struct mem_chunk));

Even if your intent was to populate the array with pointers to pointers (which is not what it is declared as), you would need to call it as

  temp[i]=malloc(sizeof(ptr));

because the size of a pointer will vary depending on system and the compiler.

In any case, you aren't actually creating a linked list at any point in the program; instead, you are creating an array of …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The shell command you are looking for is g++ filename -o executablename, or at least that will get you started (the '-o' stands for 'output', and let's you choose the name of the final executable). Look up the documentation on GCC and make for more involved compilation.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, fixated on the first part as I was, I missed the whole question. Ah, yes, here's the problem: you are putting the numbers in quotes, which means that you are comparing the input values (0, 1, 2, 3) against their character representations ('0', '1', '2', '3'). While those representations are indeed treated as valid int values, they are not the same values as the integers. For example, the character '0' is actually encoded as the numeric value 48. Thus, you want to drop the quotes around the numbers, like so:

int printOutcome(int choice, int compChoice)
{
    if (choice == 0 && compChoice == 0)
        cout << "Tie \n";
    if (choice == 0 && compChoice == 1)
        cout << "Computer wins\n";
    if (choice == 0 && compChoice == 2)
        cout << "Human wins\n";
    if (choice == 1 && compChoice == 0)
        cout << "Human wins\n";
    if (choice == 1 && compChoice == 1)
        cout << "Tie\n";
    if (choice == 1 && compChoice == 2)
        cout << "Computer wins\n";
    if (choice == 2 && compChoice == 0)
        cout << "Computer wins\n";
    if (choice == 2 && compChoice == 1)
        cout << "Human wins\n";
    if (choice == 2 && compChoice == 2)
        cout << "Tie\n";
    cout << endl;
}

This has the values compared to the equivalent integer values, not the character encodings.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You could eliminate a certain amount of redundancy by using toupper() (defined in the <cctype> header) to force the user input to upper case:

int userChoice()
{
    char choice;
    int choice2;
    do
    {
        cout << "Please enter your choice[r,p,s,q]: ";
        cin >> choice;
        choice = toupper(choice);
        cout << "Human: " << choice;
    }while ((choice != 'R')&&(choice != 'P')&&(choice != 'S'));

    if(choice == 'R')
        choice2 = 0;
    if(choice == 'P')
        choice2 = 1;
    if (choice == 'S')
        choice2 = 2;
    if (choice == 'Q')
        choice2 = 3;

    return choice2;
}

It's a small change, but one which makes the function quite a bit easier to read.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The first thing we need to know is what operating system you are running under. For now, I'll assume some version of Windows, probably XP but that's just a guess (edit: your profile says Windows 7. Knowing that makes the rest of this easier.)

The next thing we need to know is, do you have a compiler already, and if so, which one? If you don't have one already, there are a number of free compilers available, with Visual C++ Express and the MinGW port of GCC being the most notable. Pelles C is an excellent choice if you intend to use C rather than C++, and like VC++, it comes with it's own integrated development environment (IDE).

Finally, we'll need to know what editor or IDE you are using. Each development environment has its own peculiarities, and we'd ned to know what you are using to give helpful advice. Again, if you don't have a programmer's editor or an IDE, there are some good ones available for free; Visual C++ Express comes with one, while Code::Blocks is a good one which will work with multiple compilers. I recommend installing Pelles C is IMHO a little easier for newbies to use than VC++ Express.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The immediate problem actually lies in avgs(); what is happening is that, since you aren't generating any negative numbers, negNums is zero, which means that when you go to get the average of the negative numbers, you cause a divide-by-zero error.

Since this is a possibility even when correctly generating the random numbers (it might by sheer chance only have positive or negative values), you will want to test for this eventuality:

    if (posNums > 0)
        avgP = posSum / posNums;
    if (negNums > 0)
        avgN = negSum / negNums;

Of course, the root problem lies with how you are generating the numbers. To get a range [-1000, 1000], you want a range (that is, a modulo) of 2000 and an offset of -1000.

//generates random numbers and fills the array with those random numbers
void randomList(int list[], const int n)
{
    signed seed;
    cout << "Enter a random seed ";
    cin>>seed;
    srand(seed);
    for (int i = 0; i < n; i++)
    {
        list[i] = (rand() % 2000) - 1000;
    }
    return;
}

While this isn't a very good way to generate random numbers, it will at least give you the desired range.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That this is undefined behavior isn't a matter of any debate or opinion; it is defined as such by the language standard, as WaltP stated more than 4 years ago.

Could someone please close this thread?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've run across this before, and the short answer is: you can't.

DLLs were designed originally with the Pascal language in mind, and as a result, older 16-bit DLLs often used the Pascal parameter passing conventions. By the time Win32 came on the scene, Pascal was largely forgotten, but, Visual Basic was on the rise inside of Microsoft, so a new calling convention, __stdcall, was developed for language-indpendent parameter passing. This became the standard for pretty much all modern DLLs.

One thing that was not supported was classes. Object models of different languages were too different, and for system programming Microsoft assumed you'd be using C in any case. Full support for object-oriented programming didn't come around until .NET, and then only for .NET style objects and classes.

The practical upshot of this is that while you can have a class inside of a DLL, you have to 'unwrap' the class by providing external functions which act as an intermediary to the class's methods.

Lucaci Andrew commented: Indeed. +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ugh, you are correct, I got it backwards. Sorry if I misled you PoloBlue, especially given my ranting about careless instructions.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

jaw drops

You'll need help if this is the way you're being taught how to do things. You don't even know how much you need it.

If you don't mind me asking, has your coursework covered basic data structures - using either struct or class - yet, and if so, did the instructor show you how they would be applied to this project? If so, then you've misunderstood the project; if not, then the instructor has misunderstood it, which is even worse. Given what I've seen so far of the way your course is being taught, I can hazard a guess, but I'd prefer to give the professor the benefit of a doubt.

OK, personal revulsion at the particular way this is being implemented aside, let's fix the division and multiplication methods. Right now, your formulae are entirely wrong for these two functions, and I'm not sure just how you (or, I'm guessing, your professor) managed to come up with the approach given. The correct formula for division is

//  e/f = (a/b) / (e/f) = (b * c) / (a * d) 

void Divide (const int a, const int b, const int c, const int d, int& e, int& f)
{
    e = b * c;   
    f = a * d;
}

and

// e/f = (a/b) * (c/d) = (a * c) / (b * d)
void Multiply (const int a, const int b, const int c, const int d, int& e, int& f)
{ …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

AH, it took me a bit to work out what you were saying, but I think I understand the issue now. What you need to do is assign the values in csci1370[][] to the different variables, in effect 'unrolling' the array. You want to get rid of the inner loop entirely, and have something like this inside what is now the outer loop:

    total = 0;
    double attendance, quiz, homework, tests;
    double hw1, hw2, hw3, hw4, hw5, hw6, T1, T2, T3;

    attendance = csci1370[row][0];
    hw1 = csci1370[row][1];
    hw2 = csci1370[row][2];
    hw3 = csci1370[row][3];
    hw4 = csci1370[row][4];
    hw5 = csci1370[row][5];
    hw6 = csci1370[row][6];
    T1 = csci1370[row][7];
    T2 = csci1370[row][8];
    T3 = csci1370[row][9];
    quiz = csci1370[row][10];

This will assign the correct values to each of the variables.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just an unrelated question: am I correct in thinking that with this assignment, and most of the others you've been working on, the intructor has provided the main() function and a skeleton for the header file? I ask this to get a sense of how free you are to take different approaches than the one you've been using; for example, rather than have several indipendent arrays which would nee dto be coordinated between, I would use a struct type, but I am pretty sure you haven't covered structs yet so that would be of little help to you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In grading(), you declare hw1, hw2, and so on, but never assign any values to them before you use them. This means that they will be filled with whatever garbage happened to be in memory before the function was called.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Asking questions isn't a problem. Answering them is what we're here for, after all.

The answer to both of those questions is the same: In C++, all executable statements have to be inside of a function. Declarations and directives do not fall into this category, but function calls do. In general, anything that causes an action to occur, or creates a result, has to be inside a function to be valid.

As for the issue of the std namespace, it's a bit more complicated than that. Namespaces can cover multiple compilation units and multiple headers, so it isn't really correct to say that std is 'inside' of <iostream>. This becomes evident when you learn about other classes and objects in std which are declared inside other headers. For example, the string class is also in std, but it's declaration is in the <string> header file.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think you've misread the assignment somewhat. The initial loop for entering in the array values is good, but you are misinterpreting what is meant by 'in the array'. What you need to do is declare another int value - let's call it testNumber - and read in a value for it. Then you need to have a second loop, this one comparing testNumber to each element of the array numbers[] - not the index value, as you seem to have been thinking. Then, if one of them matches, you need to break the loop and print out that testNumber is in the array; otherwise, if you go through the whole array without a match, print out that testNumber is not in the array.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I did some looking around, and found that the loan payment formula you were given is wrong. The correct formula, as give here, is:

MonthPmt = loanAmount * (MonIntRate + (MonIntRate / (pow(1 + MonIntRate, No_of_Months) - 1)));

This still doesn't quite work right, however; I'll keep looking into it.

EDIT: I figured it out, all right. The problem was in your call to MonthlyPmtCalculator(); you had put the arguments out of order, with the Annual Percentage Rate last rather than first. The correct working code is as follows:

main.cpp

#include <string>
#include "hw3.h"

using namespace std;

int main()
{
    string Fname, Lname;
    double loanAmount;
    double annualIntRate, MonIntRate=0;
    int No_of_Months;
    welcome();
    getCustomerInfo(Fname, Lname);
    getLoanInfo(loanAmount, annualIntRate, No_of_Months);
    AmortizedTable(loanAmount, annualIntRate, No_of_Months);
    return 0;
}

hw3.h

#include <string>
#ifndef         HW_3_HEAD_H
#define         HW_3_HEAD_H

void welcome();
std::string getCustomerInfo(std::string& Fname, std::string& Lname);
void getLoanInfo(double& loanAmount, double& annualIntRate, int& No_of_Months);
double MonthlyInterestRateCalculator(const double annualIntRate);
double MonthlyPmtCalculator(double annualIntRate, const double loanAmount, const double MonIntRate, const int No_of_Months);
void AmortizedTable(const double loanAmount, const double annualIntRate, const int No_of_Months);

#endif

hw3.cpp

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
#include "hw3.h"


void welcome()
{
    std::cout << "Welcome to Rio Grande Bank "<< std::endl;
    std::cout << "We are please in assisting you in your banking needs" << std::endl;
}

std::string getCustomerInfo(std::string& Fname, std::string& Lname)
{
    std::string fullname;
    std::cout << "Enter your first name and last name:";
    std::cin>> Fname>>Lname;
    fullname = Fname + Lname;
    return fullname;
}

void getLoanInfo(double& loanAmount, double& annualIntRate, int& …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Compare:

MonthPayment = LoanAmount * MonIntRate * (1 + MonIntRate)^NumMonths/(1 + MonIntRate)NumMonths-1

with

MonthPmt = loanAmount * MonIntRate/(1 - pow(1 + MonIntRate, -No_of_Months));

You should see that they don't match. The correct code should be

MonthPmt = loanAmount * MonIntRate * (pow(1 + MonIntRate, No_of_Months) / ((1 + MonIntRate) * No_of_Months)) - 1;    

Or at the very least, that is how I read it; I may be off still.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In this case, the error is most likely in one of the header files you are including, with the most probably cause being that you omitted a semi-colon at the end of a class definition.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The simple answer for why b is not defined in this loop:

while b <= 10:
    print (b)
b += 1

is that b is not, in fact, defined, at least not when you are trying to compare it to 10. Thus, you do indeed want to initialize it to zero before the beginning of the loop.

But wait, you say, why then is it causing an infinite loop, when you clearly have an increment in the loop? Well, the answer there is, you don't have an increment in the loop; you have an increment after the loop, where it does you no good at all. This is simply a matter of incorrect indentation, and easily is solved thusly:

b = 0
while b <= 10:
    print (b)
    b += 1

To finish up, let me answer a question which you haven't asked: why doesn't the while: loop's conditional value default to zero, when the equivalent for: loop's is:

for b in range(0, 11):
    print (b)

The answer is that the value of this b is getting set by the range() generator on the first pass of the loop, and is reset on each subsequent pass.

Lucaci Andrew commented: Nicely done +4
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

And what seems to be the trouble with it? I can see that it is incomplete, but you will need to spell out just what you need help with.

Seriously, PoloBlue, you have been posting here long enough that you should know better than this by now. We are not mind readers; while we'll help you to the best of our abilities, we can't simply guess at the problems and hope to be right.

I can point out a few things, but that's about it. First off, you haven't actually implmented the main loop yet. The program runs through the sequence once, and stops, with no final message.

Second, the GetCustomerInfo() function returns a string, but you don't actually assign that string to a variable anywhere in main(); the customer information is simply getting lost. The same is true for MonthlyInterestRateCalculator() and MonthlyPmtCalculator().

Now, I don't know if you've covered structures in your class yet, but you might find it useful to declare the following struct types:

struct Customer
{
    string firstName, lastName;

};

struct LoanInformation 
{
    double loanAmount;
    double annualIntRate;
    int No_of_Months;
};

This helps organize the data and makes it easier to pass the data around between the functions.

As for the header issue, I've already said my piece about that, and see little point in re-hashing the issue with you; but as I said before, if you need help in setting up a project file to work with multiple compilation units, let me …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There really aren't any specific rules about making wrapper casses I'm afraid; it depends too much on the functions and structures which are being encapsulated. Some wrapper classes are nothing more than a static class with a group of methods that call the original functions directly being nothing more than a way of organizing the existing functions into a single package. Others focus on building a class around a data structure, with the aim of simplifying the function calls by making them methods of the data structure, rather than having to apply the functions to the data. Still others may actually combine behaviors in ways that actually change the way the library works, though at that point you generally wouldn't call it just a wrapper.

The closest thing to a general method or approach which I've found was this article, and I'm not sure it really applies generally. TheAdapter Pattern is often seen as a type of wrapper, but it isn't necessarily done as a wrapper class per se, IIUC.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Before we get to the specific issue, I'd like to mention a few things. First, it is incorrect to use void as the return type of the main() function; according to the C++ language standard, you should always use int main(). Some compilers do allow void main(), but strictly speaking it is incorrect.

Second, you are using the older form of the header files. In modern C++ (since the 1998 standard), the correct standard library headers no longer use the '.h' extension; thus, it should be <iostream> rather than <iostream.h>. On a related note, the C++98 standard also requires that all standard library classes, tyoes, and objects be placed in the std namespace. Thus, you would need to scope the references to std::cout and std::cin.

(BTW, what version of the compiler are you using? If it is the Turbo C++ compiler, you should be aware that that is over twenty years old, and you ought to replace it with something newer. There are several good free compilers available that support the latest version of the standard, so there's no reason to use the older compiler if you have any choice in the matter.)

Finally, you should be aware that the <conio.h> library is proprietary to the Borland compilers, and is specific to DOS programs (which is not the same as Windows console, though the console is backwards-compatible with DOS to a degree). It is both non-portable and outdated, and you are best off avoiding it.

Now we get to the …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In this context, the ampersand is the reference type indicator; it means that instead of passing the value of the arguments, it should pass a reference to them. A reference is similar to a pointer, in that it let's you act on the original variable rather than a copy.

In practical terms, this means that when you change the values of b and e in the function bande(), it also changes the values of the b and e in the main() function.