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

What is the problem you are having? This looks like a legitimate assembly program fragment (assuming you are using EMU8086 or a DOS box of some sort), but not exactly a complete program. The biggest issue I can see is that it doesn't compute what your supposed to; this takes in five variables, not the three specified, and the formula it calculates does not match that in the problem statement.

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

Minor point, but the correct printf() format string specifier for a pointer value is %p, which will show it in the correct format for a pointer on the given platform. While %x will show that value as a hex number, this isn't necessarily the correct way to specify a pointer value.

printf ("The value is %d and the address is %p\n", x, & x);

Also, as me.stober points out, cout and cin are C++ objects, and cannot be used in C. Similarly, the <iostream> header and using namespace directive are also specific to C++.

You have declared a function named foo(), but it isn't in the code given. I know you've been having some trouble working with functions, so let me ask: what is foo() meant to be for? Or was that an example the instructor used that you copied verbatim? The identifier foo isn't usually used in actual coding; rather, it is a meta-syntactic variable, a word which is used to stand in for some other, unspecified word. It is mostly seen when giving general examples of the structure of things like functions, without giving a real function name.

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

Hey I still have trouble understanding it a little and I still have to
put add projectors and student name how do I do that?

What parts are you confused by? Can you try to work it out from what I've given you? I can explain more if you need me to, but I would like to know what you are having trouble with first.

As for the projectors function, it should work almost the same as the function for gtting the number of windows. Look over that function carefully and try to see how you cuold modify a copy of it to work for the projectors question.

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

Could you show us what you have so far, or at least the part where you check for the substring " my "? Generally speaking, you want to simply take the tokens or words following "my", whatever they happen to be.

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

That seems a reasonable assumption, though I'd want to hear back from the OP before assuming that this is what is needed. In the meanwhile, here are some comments I cann make based on the code itself:

  • You included the <iostream> header for the C++ style I/O, but used C style I/O throughout the program. While this isn't a problem in and of itself, you would want to #include <cstdio> instead of <iostream> if that is how you wish to write the program.
  • You use system("cls"); for clearing the console. While this isn't a very good approach (as explained here in detail), that's not what I wanted to mention. The system() function is part of the standard C library, and you should #include <cstdlib> if you are going to use it at all - but really, you don't want to do it this way, trust me. The link given above lists the alternatives for clearing the console under both Windows and Unix.
  • On a similar note, to use strcpy(), you need to #include <cstring>.
  • OTOH, you aren't using anything that requires <windows.h>, and you can safely remove it from the list of includes.
  • You use <conio.h> for the getch() function. the conio libary is not standard, and using it is generally discouraged.
  • The line

    int const = 20;

is incomplete, and should cause a compile-time error. You need to have an identifier in there after const, otherwise it's a syntax error.

  • You don't have a default case …

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

I do not know how to do that. Can you help

Certainly.

You may not realize it yet, but you do know how to write functions, or at least one special function, the main() function. main() is a special case, however, as it does a lot of extra things behind the scenes when the program begins, things which are system and compiler dependent. Also, the main() function has a specific signature, which should always be used with it.

You have also used many functions in the past. In C++, much of what may seem to be part of the language - system(), cout, cin, the string class - are actually part of the standard library rather than the core language. Any time you use one of the functions or operators associated with them, you are calling a function. So the principle is, at least somewhat, familiar to you.

As for writing functions to work with your structure type, the fist thing you need to do (as sfuo pointed out earlier) is move the struct definition out of the main() function. This will make the structure type visible to other functions, allowing them to use it themselves.

Then next step is to break the exsting program down into pieces. For example, we can take the part where you are getting the roo number, and make a simple function out of it:

int get_room_number(classroom& cls)
{
    cout << "What is your Classroom Number? ";
    cin >> cls.room_number;
    cout << …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is fairly straightforward, and is exactly what the error message says: in both of the functions, you declare i and j as type float, which is not an integral type - that is to say, it isn't a type which holds only integer values, such as int, short, unsigned int, long, and the like. You cannot use a floating-point number as an index, for reasons that should be tolerably clear (i.e., you can't have a fractional index to an array). If you simply change the declarations to type int, the problem should resolve itself.

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

At what point to do you set the random seed? I don't see any calls to srand() in the Random class, which means that the sequence of 'random' values will always be the same. You can solve this issue by adding a class integer variable seed and a static initialization function for it:

// Random.h
#include <cstdio>
#include <cstdlib>

class Random {
public:
    static void setSeed(int source) { srand(source); };
    int Between(int min, int max);
    int Solid();
};

And add a call to it in main() before using the Random objects:

    Random::setSeed(time(NULL));

Note that rand() isn't a very good random number generator to begin with, and applying modulo to it creates a bias towards smaller values. Furthermore, since only one seed is set, supposedly separate Random objects all draw from the same pseudo-random sequence. If the randomness of the values is important to you, or if you need to be able to seed the individual Random objects separately, you may want to find some other pseudo-random number generator algorithm to implement yourself, one which could be better tailored to your needs. For that matter, if you have a hardware random number generator, you may want to use that - if not directly, then as a soource of a good random seed.

I would also add that you should use the newer forms of the include headers, such as <cstdlib> and <ctime>, rather than the C-style <stdlib.h> and <time.h>.

As for using the array syntax, you …

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

The reason for the macro expansion of add in this instance is because of how the immediate instructions encode the immediate values. The actual 'add immediate' instruction, addi, is a single 32-bit value which encodes the instruction opcode itself, plus the two register arguments, and a 16-bit immediate value.

| opcode | src register | dest register | immediate value |
    6           5              5              16

This means that the addi instruction can only add a 32-bit value (from the source register) to a 16-bit immediate value. In order to handle a larger 'immediate' value, the value has to be read into the assembler temporary register ($at, register $1) in two stages: first, using 'load upper immediate' (lui) on the upper half of the immediate value, then by using 'or immediate' (ori) on that value against the lower half-word of the immediate value. This has the sum effect of loading a 32-bit value into the $at register, which is then used as the argument in the normal register to register add.

As for why it sign-extends the two values, I can only guess that it is an artifact of how the disassembly is displayed. Because both 0x8000 and 0xD000 have the uppermost bit set, the disassembler is reading them as signed values, which would normally have to sign extended as a 16-bit negative value should not become a positive value when converted to 32 bits. The fact that they are actually the upper halves of a 32-bit value …

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

I am fairly sure that the from Server import * should work, assuming that you are running in your working directory (which ought to be the case, as you probably only get access to your own folder on their server). Not having worked with PythonAnywhere, I cannot say for certain. I would say pyTony's suggestion of using the PythonAnywhere user interface is the best approach overall.

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

First off, it isn't in most cases necessary to enter into the Python console itself to run a file; you can instead just open a system console window and use

python Server.py

and the program should run. For that matter, if you are running Windows, the file assocations should automagically run the Python interpreter for you if you double-click on the Server.py file. Under most Unices, such as Linux or MacOS X, you can add a shebang line at the beginning of the file to invoke the interpreter:

#!/usr/bin/python 

Now, if you'd still prefer to run the program from the Python console, then you will want to use an import statement:

from Server import *

or just

import Server

However, this requires that you invoke the console in the same directory as the Server.py file.

As for the issue of version, yes, the version matters greatly, at least with regards to the 2.x versions versus the 3.x versions. The language has been substantially overhauled in version 3, in ways that broke a lot of programs written for version 2; this is why the two different versions have continued to be maintained. If your program was written for version 2.x, then chances are it won't run under 3.x, but many 3.x programs wil run under 2.6 or 2.7 (but not generally earlier than that). It all depends on the version that Server.py was written for. If you are still writing Server.py, then it …

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

That's correct. Generally speaking, while it would have been a lot easier for the programmer had they allowed register offsets, it would have also made for a more complicated hardware. Given that one of the original goals of MIPS was that it would not be designed for assembly programmers (it was optimized to make compilers easier to write), this wasn't seen as a major limitation.

As a practical upshot of this, instead of trying to change the offset, you generally just want to keep the offset at zero and use one of the scratch registers to hold the index. Why a scratch value? because these are almost certainly not going to values you need to hold on to, whereas the original values of the indices and offsets you may need later, so you don't want to overwrite them.

For the most part, what you wrote should do the trick, though I would warn against storing a loaded value into the same register you are using as the base address. Also, a word in MIPS is 32-bits long, or four bytes, so you need to multiply the index constant by 4, not 2. I would recommend make the following changes:

sub $t0, $s3, $s4
sll $t0, $t0, 2
add $t0, $t0, $s6
lw $t1, 0($t0)
sw $t1, 32($s7)

Note, however, that in most practical programming, you are dealing with values that are function local on the stack, so you would need another level of indirection in order to get the …

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

Two classic articles on this subject which might be of interest to you: So, You Want to Write an Operating System and it's sequel, Climbing the Kernel Mountain.

Among the things you need to decide before you begin are:

  • Do you know enough about both programming and computer hardware to write an OS? How good are you with C? With Assembler? What assembler(s) do you know, and can the one you are using produce a flat binary file (or an ELF file, if you are using GRUB)? What do you know about compilers and how they work? About linkers and loaders? About file systems? About memory management? About process management and interprocess communication?

  • What hardware are you writing it for? I would assume that it is an x86 based PC of some sort, but it is possible you'll want to write for soemthing like a Pegasus (PowerPC-based) or a smartphone (which could be any of a number of things, but are mostly ARM-based) or something like an Arduino card. If it is a PC, is it a current day one, or some older box you happen to have around or picked up somewhere? What are the limitations of the system you are writing for?

  • Assuming a PC, are you going to write a 16-bit real-mode system, or are will you make the jump to 32-bit protected mode (or even 64-bit long mode)? Real mode is a lot simpler starting out, but is painfully limited. …

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

Not really; the two programs work in ways that aren't really compatible with each other, and if you'd written either of them yourself, you'd realize why that is the case. The first doesn't actually calculate anything; it just generates a second program that does the computation, then deletes the second program. I doubt that this approach would be accepted as a way of calculating anything in most courses, as it is more of a work-around to avoid the actual job of parsing the input - you miss the entire point of the lesson this way.

The other one is a Windows GUI program, not a console program, and while it is possible to write to the console (the 'black edit box') from a GUI program, this particular one doesn't. It actually does calculate a simple operation, but it does it in a way that can't be easily applied to the kind of calculator that the course requires.

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

We generally prefer to have everything posted publicly, so that others can benefit from it. If you post your code, we'll try to help you with it.

On the other hand, if you really don't wish to have your code out for anyone to see, you can PM me or some of the others and we'll help as best we can.

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

As an old hand there in days gone by, I would warn you that the regulars at the OSDev Forums don't suffer fools or newbies. It's an excellent resource, but if you do post there, be on your toes, use your clearest proper English, and do everything you can ahead of time to prepare your questions.

In other words: Stay Alert! Trust No One! Keep Your Laser Handy!

(Seriously, it really is a great message board, but after years of people wandering in to ask irrelevant or silly questions, they've become very defensive. Lurk and get a sense of the place before posting, if at all.)

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

Sneaky little Schemer that I am, I'll throw in Scheme from Scratch, a project to write a simple Scheme interpreter in C. While Peter Michaux has posted his own code for it, there are several others who followed along the basic design with their own implementations (in a fit of perversity, I decided to implement my version in MIPS assembly language). It's a few weeks worth of part-time work, but it does make a good project for a long holiday. It gives you a basic idea of how to implement an interpreter, as well as exposing you to a language you probably aren't familiar with.

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

First, permit me to re-post the code with suitable indentation, courtesy of Astyle:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include "windows.h"

using std::cout;
using std::endl;

bool ListDirectoryContents(const char *sDir)
{
    WIN32_FIND_DATA fdFile = {0};
    HANDLE hFind = NULL;
    ULONGLONG fileSize;
    time_t rawtime;
    struct tm * timeinfo2;
    long bsize;
    float kbsize;
    char sPath[2048];
    sprintf(sPath, "%s\\*.*", sDir);
    if ((hFind = FindFirstFile(sPath, &fdFile)) == INVALID_HANDLE_VALUE)
    {
        printf("Path not found: [%s]\n", sDir);
        return false;
    }
    do
    {
        if (strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0)
        {
            sprintf(sPath, "%s\\%s", sDir, fdFile.cFileName);
            if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                ListDirectoryContents(sPath);
            }
            else
            {
                cout << "# FILE NAME: ######################################################" << endl;
                cout << "File: " << sPath << endl;
                cout << "# FILE SIZE INFO: #################################################" << endl;
                bsize = fdFile.nFileSizeLow;
                kbsize = (float) bsize / 1024;
                cout << "SIZE: " << fdFile.cFileName << " " << bsize << " bytes " << kbsize << " kb" << endl;
                cout << "size HIGH: " << (fdFile.nFileSizeHigh * (MAXDWORD + 1)) + fdFile.nFileSizeLow << endl;
                fileSize = fdFile.nFileSizeHigh;
                fileSize <<= sizeof ( fdFile.nFileSizeHigh) * 8;
                fileSize |= fdFile.nFileSizeLow;
                cout << "fileSize: " << (DWORD) fileSize << endl;
                cout << "# FILE ACCESS INFO: ################################################" << endl;
                time((time_t*) & fdFile.ftLastAccessTime);
                cout << " --> last open: " << ctime((const time_t*) &fdFile.ftLastAccessTime) << endl;
            }
        }
    }
    while (FindNextFile(hFind, &fdFile));
    FindClose(hFind);
    return true;
}

int main()
{
    ListDirectoryContents("C:\\Repository_Files\\");
    return 0;
}

Now, when I compile and run this (under Code::Blocks, with MinGW GCC …

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

Finding a favorite language is a bit of a personal experience, so it's hard to give exact advice. While a part of me still wants to plump for Scheme (and specifically Structure and Interpretation of Computer Programs, a classic introductory textbook that is available online), I have to second the suggestion of trying Python. It is a very simple yet powerful language with a straightforward syntax that doesn't get in the newcomers' way.

The only caveat I would make is to be careful about which version of the language you choose. There are significant differences from version 2 to version 3, and the two different branches of the language are (for the time being) maintained independently of one another. While version 3.3 (the latest 3.x release at this time) is the one I would recommend, there are a lot of tools and libraries that only work with version 2.7 or earlier, and if you need to use a specific toolset, you may find yourself in the position of having to use the older revision of the language.

The main Python website has some excellent tutorials to start with, as well as extensive documentation on the language. As for textbooks, I, too, have heard of Learn Python the Hard Way, but I haven't looked into it enough to say if it is a good choice or not. One textbook I can recommend is Think Python, an updated version of the venerable …

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

Setting aside issues about your Belief System (since I am no one to talk, given that my own BS is far stranger), I would mention that at least some 64-bit Intel chips have built-in entropy sources that can be accessed with the RDRAND instruction. On Macs which have this instruction, you should be able to use the /dev/random device to access it, though I am not certain which models, if any, actually implement this.

Wikipedia has a short list of companies which sell HRNGs. It also mentions randomness servers, which can accessed online.

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

OK, there does seem to be a bit of disagreement on this part, it is true. For my part, what I am arguing is that, even if you are using the same syntax and semantics as Python, if you are writing a significantly different language from Python you'd want to have your own expression evaluator rather than co-opt Python's. I think PyTony is thinking in terms of something a lot simpler than what I have in mind, however. Either that, or he's thinking of writing a partially meta-circular evaluator, which I hadn't thought to do myself.

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

If this is the formula for power consumption on a CMOS circuit, then yes, though you are missing part of the equation (the Activity Factor, which represents the fraction of the circuit that is actually bearing a current); as it is, it's only correct if the whole circuit is active, which would not normally be the case. The full formula is

"Dynamic Power" = "Activity Factor" times "Capacitive Load" times "Voltage²" times "Frequency Switched"

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

This issue is simple: you are trying to append() a NULL pointer, which (depending on how your append() function works) will either return an error or silently fail, as a NULL node is the same as not appending a node at all.

In order to actually append a new node, you need to allocate that node first:

p = malloc(sizeof(struct node));

Otherwise, you are saying, 'Add a node that does not exist', which is the same as not adding a node in the first place.

Is the int argument of the append() function supposed to be the number of nodes added, or the location to add the node to? EIther one presents possible problems. If it is a number of nodes to be appended, then how are you appending more than one node at a time without using varargs? If, on the other hand, it is a location index, how do you handle the case where there are fewer nodes in the list than the index value?

Could you post the code for your append() and count() functions, please? That way we could tell you if there are any problems with them.

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

Whenever any function is called, the arguments are evaluated first, and their results are the actual working arguments. In this case, the string concatenation is performed first, then the whole string is passed to the function. So, if i = 50, then the string passed to System.out.println() is "Hi...50Welcome". In other words, it is the same as writing

System.out.println("Hi...50Welcome");

So, to answer your question, System.out.println() is only called once.

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

Is this solely as a learning experience

What do you think.

I don't know quite what to think, actually. I am assuming that it is primarily to learn abot intrpreting languages; but if you have a specific goal in mind, it would help us if you said so, as we could give more specific advice.

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 don't think that this is quite what Snippsat meant (or at least I'll give him/her the benefit of the doubt). What Snippsat is saying is that if you are implementing something other than Python, you don't want to use Python's eval() or similar reflective techniques, as those are based on Python's syntax and semantics, not your languages; instead, you need to parse and interpret the new language as something unrelated to Python.

The language you write the interpreter in should not (in principle) affect how the interpreted language runs. Now, there are real-world considerations such as performance, availability of libraries, interfaces to th system and other languages, etc. that are impacted by the choice of implementation language, but for the most part, you can implement any language in any other (Turing-complete) language. If Python is what you want to use, go ahead and use Python; but don't rely on Python's ability to interpret itself as a way of implementing adifferent language.

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

Mainly, that it leverages the existing EnumMap class rather than having to write a c'tor and accessors for the Rank class. Also, because it decouples the value of the cards from the Rank class, it makes easier to re-use the classes for another type of card game (e.g., poker, bridge). While neither of these is a big deal in this particular case, they are good design practices to get familiar with.

speakon commented: Thanks! +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As it happens, there is a class named EnumMap which is designed for precisely this situation. It provides a mapping keyed to an enumeration. I this case, you would use it something like this in the class BlackJack:

static final EnumMap<Rank, int> rank_value = new EnumMap<Rank, int>(Rank);

static {
    rank_value.put(Rank.Deuce, 2);
    rank_value.put(Rank.Three, 3);
    rank_value.put(Rank.Four, 4);
    rank_value.put(Rank.Five, 5);
    rank_value.put(Rank.Six, 6);
    rank_value.put(Rank.Seven, 7);
    rank_value.put(Rank.Eight, 8);
    rank_value.put(Rank.Nine, 9);
    rank_value.put(Rank.Ten, 10);
    rank_value.put(Rank.Jack, 10);
    rank_value.put(Rank.Queen, 10);
    rank_value.put(Rank.King, 10);
    rank_value.put(Rank.Ace, 11);
};

You could then use this to get the values of the cards:

    /*
    * Print Initial Cards
    */
    System.out.print("The Dealer Has: " + deck.dealer.getDealerList() + " for a total of ");
    int dv = 0;
    for (Card card : deck.dealer.getDealerList()) {
        dv += rank_value.get(card.getRank());
    }
    System.out.println(dv);

    System.out.print("You Have: " + deck.user.getUserList()  + " for a total of ");
    int pv = 0;
    for (Card card : deck.user.getUserList()) {
        pv += rank_value.get(card.getRank());
    }
    System.out.println(pv); 

I hope it is clear how this works.

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

What it comes down to is that sizeof(struct node) gives the size of a struct node element, while sizeof(struct node *) gives the size of a pointer to a struct node element. So, if struct node is

struct node 
{
    int data;
    struct node* next;
}

Then, on a typical 32-bit machine, sizeof(struct node*) would probably be four (4 bytes == 32 bits), while sizeof(struct node) would be equal to sizeof(int) + sizeof(struct node*) (possibly with some additional padding as well, to align the data on a word boundary, though probably not in this instance), which would likely (but not definitely) come to eight bytes. Note that you can't assume the sizes are what you'd expect them to be, because different types of system have different pointer and data sizes; this is why you use the sizeof operator, even for the primitive types.

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

It would help us considerably if you'd give us some idea of your goals, your design ideas, and your purpose in this. Is this solely as a learning experience, you do you have a particular application in mind for this new language?

Have you done any work on designing the language, and if so, could you give us some idea of the grammar and semantics you mean for it? (A simple BNF grammar for some basic statements, and some prose explanations of the intended behavior, should suffice). It would let us know what you have in mind, and may give us some idea of how to help you.

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

The deck instance variable probably should be an ArrayList<Card> rather than ArrayList<String>.

I would make the suits and values of the card enumeration types, rather than strings; that way, you can change the representation (using abbreviations, for example, or images of some kind), without needing to change the Card or Deck classes themselves. This sort of decoupling of the user interface with the logic is often a valuable approach.

enum Suit {Hearts, Clubs, Diamonds, Spades};

enum Face {Ace, Deuce, Trey, Four, Five, 
           Six, Seven, Eight, Nine, Ten,
           Jack, Queen, King};

public class Card {

    private Suit suit;
    private Face value;

    public Card(Face v, Suit s) {
        value = v;
        suit = s;
    }

    public String getValue() {
        return value;
    }

    public String getSuit() {
     return suit;
    }
}

Fortunately, Java enumerations are a lot more flexible than those in C or C++, and you can extract the string form of an enumerated value just by using either name() or ToString(). Thus, while you can decouple the interface if you choose, you can also 'cheat' a bit and use the actual enumerated values.

You probably want to write one or more comparison methods for the Card class.

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

You don't necessarily want to hard-code the size of the Deck, either. The reasons for this are four-fold:

  • As the play goes on, the size of the Deck will decrease, until it reaches the point where you need to reshuffle the discards, at which point it will go back to the original size,
  • You may want to extend your deck with additional Cards (e.g., jokers),
  • You may want a 'shoe' of cards consisting of more than one 52-card deck (as is done in most casinos), and
  • The easiest way to handle the player's hand is to sub-class Deck, in which case the size will always be smaller than 52.

Just some advice based on my own experience implementing a card game.

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

Deceptikon: While that argument in favor of iterative solutions has merit in general (much though it pains the Schemer in me to admit it), in this particular case, the recursion is used less as a way of performing a loop than for the purpose of building up a stack with which the information about the list elements' positions is held at run time. The alternatives, either using an explicit stack or creating a separate reversed list, involve additional explicit data structures which have to be manually manipulated by the coder. Thus, I would argue that the recursive solution is the more elegant approach in this instance.

As for when one would want to generate a list in reverse order from the original, as opposed to traversing the existing list in reverse, it would depend on whether the reversed list needs to be persistent independent of the original. If you need the reverse of a list several times over, it makes sense to use a copy of the original in reverse order rather than performing the traversal repeatedly.

PyTony: While I too tend to have a bit of a Lisper's viewpoint on these matters, it is useful to recall that a Lisp style cons cell differs from most C linked lists in that the data is not bound to the cons cell directly; both the CAR and CDR of the cell can point to either an atom or a list, and more than one cons pointer can point to the same …

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

Pardon the thread necromancy, but I can't help but mention a famous bit of hacker lore regarding a programmer working in pure binary (well, hex actually, but still) in the 1960s - The Story of Mel, A Real Programmer.

(And yes, Mel Kaye was a real person; the story is apparently as true as any such legends go.)

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

The book Linkers and Loaders by John Levine (available online in a beta version) is an excellent resource in this regard. It gives details about several of the most common file formats (though for better or worse, the book does not cover Mach-O, the Mach kernel format used by MacOS). It is a bit dated now, but since there haven't been any major changes (AFAIK) to either PE or ELF (used by Windows and Linux, respectively), there isn't much loss of information due to it's age.

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.