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

I'm afraid we'll need more information about the problem you are having in order to give you any advice. Is this your own code, or was it provided by your instructor? Have you tried compiling and running it, and what was the result?

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

Ah, thank you for the correction.

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

Actually, Deceptikon, this is one place where C and C++ part ways; the C++ standard does require and int return value, and always has, whereas the older C standard recommends but does not enforce it.

IIUC, the C11 has changed this to require an int return as well, even on systems where it isn't needed (presumably, the compiler simply discards it, in those cases). Can anyone confirm or deny this?

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

The main things that jump out at me are:

  • line 4: there is an extra '(' at the end of the line. This was probably a typing error.
  • line 7: you dropped the colon at the end of the line
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The istream and ostream classes work with chars, rather than wchar_ts, and won't interpret wide chars correctly. However, changing them to work with wchar_t would break a large amount of existing code, so they have to be retained for backwards compatibility. Naturally, the standards commitee wanted to provide a portable solution to this, and to this end, the standard now defines wistream and wostream classes, and mirror objects for the standard input and output: wcin and wcout. To work with wide chars, you will want to use those instead of cin and cout.

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

Another approach that occurred to me would be to use tuples for the runs:

[(1,4), (2, 2), 3, 4, 5, (3, 3), 11, 12]

def decompress(comptext):
    plaintext = list()
    for c in comptext:
        if isinstance(c, int):
            plaintext.append(c)
        elif isinstance(c, tuple):
            for n in range(c[1]):
                plaintext.append(c[0])
        else:
            pass # TODO: handle the invalid/error case
    return plaintext
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Assuming your goal is Run-Length Encoding, you need to have some way of marking the places where you've applied the encoding, preferably with some character that would never appear in the data stream, or else one that is rarely used. Assuming that your data is always going to be integers, you could choose an arbitrary non-numeric character, such as '\' (backslash, an escape char used in several such encodings). Thus, you would actually encode it something like this:

[1,1,1,1,2,2,3,4,5,3,3,3,11,12]
['\', 1, 4, 2, 2, 3, 5, '\', 3, 3, 11, 12]

Note that with this scheme, you would want to avoid encoding runs of less than three.

Alternately, given the type of data encoded, you could just use the character representations of the numbers themselves, which would save some space and make it feasible to encode all the runs, though this would require additional processing in decoding:

['1',4,'2',2,3,4,5,'3',3,11,12]
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just to make what pyTony and Vegaseat said perfectly clear: we won't do your homework for you. To quote the DaniWeb Community Rules:

Do provide evidence of having done some work yourself if posting questions from school or work assignments

We are here to help you become a competent programmer, not to hand you an underserved passing grade. Show us what you've done so far, and we'll help you fix it. Ask questions, we'll try to answer them. But just posting the your assignment without so much as an introduction? That's not going to earn anything but our contempt.

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

i have the windows.h include, but the 'L' where is declared?
or i must declare it?

The prepend L is a feature of the C language itself, and is implemented inside the compiler; there is no definition for it. If you think it through, this has to be the case, because the compiler has to be able to interpret the string literal's glyphs as text characters.

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

Off the top of my head, the two other approaches which come to mind - using the enumerate() operator, and using a list comprehension - would both involve things which you probably haven't used before, either. There may be others here who can think of still other approaches, I guess.

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

You need to step through the matrix, just as you are now, but at the same time you need to generate a new matrix and assign the multiplied values to its elements.

def scalar_mult(matrix, scalar): 
    matrix_prime = list()
    for i in m: 
        vector = list()
        for j in i: 
            vector.append(j * scalar)
        matrix_prime.append(vector)
    return matrix_prime
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I ran the code, and while it didn't print in the manner you probably would like, it does indeed multiply the matrix by a scalar. What problem are you experiencing with it?

First off, the name matrix() for this isn't really appropriate; it's matrix multiplication, whereas the name matrix() makes it sound like a class c'tor.

On that note, I would say that writing a Matrix class would be a good idea, given that you'll almost certainly want to do more than just multiply by a scalar and print out the results.

I would recommend separating the process of printing the matrix from that of multiplying it; this will, among other things, allow you to keep a copy of the new value, rather than simply display it.

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

Start by declaring a class named Rectangle. Write a constructor (an __init__() method) that accepts arguments self, length and width, and assign the latter two to self.length and self.width inside the constructor.

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

What have you tried so far? Please show us the existing code, if any.

Note that, chances are, you are going to have to rad the whole file into memory (or at least the part from where you are editing it onwards) and write it back to the file. You may want to use an intermediate file, and then delete or rename the original file and change the name of the intermediate file to that of the original. Something like this:

read the lines in from 'original' up to the mark where you are changing it
write that first section out to 'intermediate'
write your changed text to 'intermediate'
read in the part of 'original' following the changed text
write that out to 'intermediate'
rename 'original' as 'original.old' or something similar
rename the 'intermediate' to 'original'

You would, of course, use the appropriate names for the files, rather than 'original' and 'intermediate'. You would want to look up the os.rename() method to get the details of renaming files.

I would add that the issue of file handling is completely independent of the windowing library, and it would probably be wise to keep the code for the text file change separate from the user interface. Write the function for edtining the file as if you didn't know where the text to change came from; pass the data as an argument to it, rather than getting it from the user directly. You'll find it easier both to write …

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

First off, you should be made aware that the forum software does not by default maintain the formatting of code; in order to get the code to stay formatted, you need to enter it using the 'CODE' button at the top of the editing window, else manually indent it by an additional four spaces.

f = open("program0.4.txt", "w")
done = input('Enter done for last name when finished')
Last_Name = input("Enter Last Name: ")
while Last_Name != 'done':

    First_Name = input("Enter First Name: ")
    Hrs_Wrkd =int(input("Enter Hours Worked: "))
    Hrly_Wge = int(input("Enter Hourly Wage: "))
    f.write('Last Name' + ' ' + 'First Name' + ' ' + 'Salary' + "\n")
    Last_Name = input('Enter Last Name: ')

f.close()

f = open("program0.4.txt", "r")
line = f.read()
for line in f:

    info = f.split()

Salary = Hrs_Wrkd * Hrly_Wge
print(line)

    print(Last_Name, " ", First_Name, " ", Salary)

f.close()

Second, while it is certainly helpful for you to post your code, we also need to know what the problem you are having with it is. Could you give us some details about the project, and where it is failing?

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

Setting aside the questionable wisdom of this design approach, the question becomes, what have you done with it so far? As stated in the DaniWeb community rules, we will only help you if you first demonstrate some effort on your own part. Post some code, or a specific question, and we can do something for you, but we cannot and will not solve the assignment outright.

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

Would you mind explaining why you need to avoid template arguments in this? I would think templates would be the preferred approach for this, in C++.

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

The problem you are having is three-fold. First, you are using the same names (student_name, School, and Majors) for both classes, and for the parameters to the to Student_Track.__init__(). Second, you are using the names of the classes in your print statement, rather than names of the instance variables (which always bgine with self., remember). Thirs, you are attempting to print the objects directly, without defining a __str__() method for them.

While I have not tested this, I think tha the following will fix the problem:

class Student_Name:
    def __init__(self, student):
        self.student = student
    def __str__(self):
        return 'Student Name: {name}'.format(name=self.student)

class Majors:
    def __init__(self, major, minor):
        self.major = major
        self.minor = minor
    def __str__(self):
        return 'Majors: {0}, {1}'.format(self.major, self.minor)

class School:
    def __init__(self,school):
        self.school = school
    def __str__(self):
        return 'School Name: {0}'.format(self.school)
class Student_Track:
    def __init__(self, school, student,  majors):
        self.school = school
        self.student = student
        self.majors = majors
    def __str__(self):
        return '{school},\n{student}\n{majors}\n'.format(
                                                         school=self.school,
                                                         student=self.student,
                                                         majors=self.majors)

ob1 = Student_Name('bob')
print(ob1)
ob2 = Majors('l','l')
print(ob2)
ob3 = School('o')
print(ob3)
ob4 = Student_Track(ob3,ob1,ob2)
print(ob4)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've tested your code (with GCC running under Code::Blocks) and found it to work, which indicates to me that the menu.txt file isn't in the same directory executable. Add the following test to you code right after the open() call:

    if(inData.fail())
    {
        cout << "Could not open menu file. Stopping.";
        exit(-1);
    }

(And add #include <cstdlib> to the start of the program.) This should tell you if it is reading the menu file at all.

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

Believe you misunderstood Ddanbe's point, I am afraid. The issue he was pointing out was not the use of the switch() statement; that was fine. The problem is that the variable you are testing, symbol, is never getting set to a usable value. You need to read in symbol after reading in the op1 (not res, as yo currently have it, BTW). So, going back to your original code, it would look like this:

    while(!in.eof())
    {
        op1.ReadMixedExp(in); 
        in >> symbol;

        switch(symbol)
        { //.. etc.
Begginnerdev commented: Yep +9
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you tell us what you are having difficulty with, please?

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

Well, fortunately, all you really need to do is change your System.out.print() calls to .append() calls on your StringBuilder:

            StringBuilder motCache = new StringBuilder(nombreLettres);

            for (i = 0; i < nombreLettres; i++) {
                motCache.append('.');
            }

(I hope that 'mot cache' is the correct phrasing for 'hidden word'...)

You can then print out the StringBuilder object whenever you need it, and manipulate the characters using the .setCharAt() method.

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

OK, that does explain things a little, but it still isn't clear what you really need. It sounds as if you are looking to test whether a given public key's numerical value is prime; but that makes no sense - the whole point of the encryption algorithm is that it uses values too large to be factored in a reasonable time period given current hardware. That's why you select 'pseudo-primes' (numbers very likely to be prime, but which can't be factored quickly) rather than ensuring the primality for the keys.

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

I have to agree with Deceptikon on this: the difference in performance between these two approaches is going to be both minor and unpredictable, as the compiler's optimization could get ruined by the cleverness of the hack.

If your concerned about performance, the best thing to do is to start by profiling the unoptimized performance. This will tell you if and where any optimization is needed. Also, you always want to compare the profile results of the 'optimzied' version with the 'unoptimized' version; you may find that your work has actually made things worse rather than better.

Given your interest in optimization, I would highly recommend reading the Graphics Programming Black Book, as it remains the best text on the subject of software optimization I know of despite it's age.

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

To run a program or script that isn't in a path directory, you need to give at least a relative path to the file:

$ ./filterList

This tells bash where to find the script in question.

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

Could you please clarify what it is you need for us? It sounds as if you are having difficulty with the input itself. Is that correct?

Assuming that this is the case, then there are a few options you can choose. The simplest of these is to use scanf() to read in the number, and checking the return value to make sure that it did in fact read in integer (scanf() returns the number of characters read, which in this case would be the number of actual digits read in).

However, using scanf() directly has its disadvantages; for one, it leaves behind whatever extra characters were in the data stream, such as the newline, which you then have to manually clear. I would recommend instead that you read the data in using fgets(), and then using sscanf() (note the extra 's') to extract the integer from the read line of data.

int possible_prime, retval;
char buffer[MAX_LINE];  // whatever you set MAX_LINE to be

// ... now we skip to where you're reading in the data...

do
{
    printf("Enter a number to test for primality: ");
    fgets(buffer, MAX_LINE, stdin);
    retval = sscanf(buffer, "%d", &possible_prime);  // note the ampersand - we use a pointer to the variable here
} while (retval == 0);
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you explain the question a bit better, please? It isn't clear just what you are looking for, especially what you mean by 'execute first'. That last part sounds like your professor's instructions to you rather than a part of the question.

I assume you are asking, how would you write the code for this, but frankly, the first part sounds trivial; you would simply assign the first variable's value to the temporary variable, then assign the second variable's value to the first variable, then finally assign the temp variable's value (which is holding the first's old value, remember) to the second variable.The only possible complication I can see is if you are writing it as a function, in which case you would have to pass the variables by reference (that is to say, using pointers to the actual variables rather than copies of the values).

As for swapping without a temporary variable, the usual approach in C is to use a trick involving the XOR operator (^), but I'll leave it to you to figure it out. I will warn you that the XOR trick isn't necessarily more space efficient than the temp variable version (because of certain optimizations the compiler can use involving internal registers), and it has a potential to backfire - if the two values are already the same, then XORing them will give a result of zero. It's the sort of kludgy optimization that you are unlikely to bother with on a modern system, because …

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

Actually, tuples are mainly used by the Python language itself, for certain types of operations where lists would too slow, or where the immutability of tuples is helpful. For example, multiple return values are actually passed as a tuple, which can either be assigned as a single value or 'unpacked' across multiple variables.

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

The problem is that you are calling the is_divisible() function, and then, on a separate line, testing whether True is true, which will always be the case. What you want to do is call the function as part of the if: clause itself:

    primes=[]
    for n in range(2, N+1):
        if is_divisible(n, primes):
            primes.append(n)
    print(primes)

This has the effect that the return value of the function is used as the condition of the if: statement.

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

Keep in mind that there is difference between the general algorithms, and the archive file formats which are their concrete realization. For any given algorithm, there are more than one possible representation of the compressed data. It is only when you have a specific format that you can meaningfully talk about detecting the format from the file metadata. For example, two different archive formats may both use LZW compression for part of their formats, yet the actual formats could be quite different.

EDIT: I was wrong about Zip and GZip. Sorry if I misled anyone.

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

It's been a while since I've been there, but I used to be a regular.

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

I think there is some confusion about the nature of operating systems going on here. That is natural, as much of the OS is hidden from view, while most of the things people think of as being part of the OS are actually separate programs (or at most sub-sections of the OS proper). There is a definite disconnect between what OS developers (both professional and hobbyist) think of as 'the operating system' and what most users and client-programmers think of as the OS.

Generally speaking, most people think the operating system is the Graphical User Interface and the Window Manager, the upper-most levels of the system. This isn't really the case, however; in fact, these aren't necessarily part of the operating system at all. For example, most Unices - Linux, FreeBSD, and MacOS X included - do not have a GUI or Window Manager as part of the operating system; in fact, the entire user interface, including the text shell, runs as a set of user-level applications. Even in Windows, most of the windowing system is run in user space.

Conversely, to a serious OS developer, the real meat of the OS is in the kernel, the lowest level part of the system. This is where things like memory management and process scheduling take place, and but it is only a very small part of the whole system.

Just to put the issue of operating systems in different programming languages into perspective, there is a page on the …

ddanbe commented: Well explained. +14
Assembly Guy commented: Nice. I'm never bothered to explain so clearly +4
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The problem is that, just as with division, taking the modulo of a number by zero is undefined; what you are actually getting is a division by zero exception, as internally, both division and modulo (or rather, strictly speaking, remainder) are calculated using the same assembly instruction. Thus, this is one place where you actually want to initialize b to one instead of zero. No, on second thought, start at 2 - there's no point in starting at 1, as every number is divisible by that, and it would give you a false negative for everything.

I might also suggest that you only iterate b from 1 to ciel(sqrt(a)), as you know that no prime divisor of a number is going to be more than that number's square root.

 for(b = 2; b <= (int) ciel(sqrt(a)); b++){

Finally, you might want to actually print the results when you find a prime number other than 2. Just sayin'.

Anyway, here is a simplified version of your code, though it assumes that the C99 <stdbool.h> library is available (it should be, with any compiler newer than, say, 2004). It isn't actually tested, but it should fix most of the problems in the original.

#include <stdio.h>
#include <stdbool.h>

int main() {

    int a, b, c;
    bool composite;

    printf("2, "); 

    for(a = 3; a <= 100; a += 2) {
        composite = false;

        for(b = 2; b <= (int) ciel(sqrt(a)); b++) {
            c = a % b;
            if (c == …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Congratulations on finishing it, though once again, more detail on how you fixed it would have been appreciated.

Also, just as a friendly reminder: when you do finish with the issue at hand, please mark the thread as closed, so that everyone knows you've solved the problem. TIA.

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

I would mention Structure and Interpretation of Computer Programs as a good starting place, but it's a controversial sugestion; on the one hand, it does an admirably job of covering programming in the small, starting from the ground up and moving alll the way through several complex topics. On the other hand, it is based on a very unusual language (which they use a fraction of, at that) and takes an approach that is highly ideosyncratic; many programmers find it too divorced from daily practice to be relevant. On the gripping hand, that sort of more abstract approach is exactly what many programmers are lacking - tunnel vision is rampant among ordinary coders, and the sort of sweeping vision SICP gives is an excellent antidote to that. Your call.

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

Questions about OS development are a bit outside the usual range for this forum; you might want to try the OS Dev forums at OSDev.org, as they are experts in the subject. Note that you need to tread lightly there, as they are rather rough with newcomers and do not suffer fools gladly. Still, the Wiki there has answers to many of the questions you are likely to have.

As for your specific question, the real issue is this: even if you are running this on a Windows development platform, your are presumably running it with an emulator such as Bochs, or through a virtual machine client such as Virtual PC or VMWare. In either case, the emulator/VM will behave as if it were running on bare metal; as far as your code is concerned, there won't be any Windows system to call out to. Thus, any handling of system services will have to come from you and you alone, or from the hardware BIOS (which will only help in a 16-bit system and is of minimal value anyway).

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

Your second (output) loop has an inner loop that looks to have been intended to iterate through the five test values; however, you then unrolled that loop, making the inner loop unnecessary. The solution is either to eliminate that inner loop altogether:

    for (int a = 0; a < grades.length; a++) {
        System.out.print(
          grades[a][0] + "\t" +
          grades[a][1] + "\t" +
          grades[a][2] + "\t" +
          grades[a][3] + "\t" +
          grades[a][4] + "\t" +
          percentage(quiz1, quiz2, midterm_exam, final_exam) + "%\t\t" +
          grade(percentage)
        );
      System.out.println("\n");
    }

or try to fit the unrolled values back into the loop (note the subscript before the .length property):

    System.out.println("Name\tQuiz 1\tQuiz2\tMidterm\tFinal\tPercentage\tGrade");
    for (int a = 0; a < grades.length; a++) {
      for (int b = 0; b < grades[a].length; b++) {
        System.out.print(grades[a][b] + "\t");
      }
      System.out.print(
        percentage(quiz1, quiz2, midterm_exam, final_exam) + "%\t\t" +
        grade(percentage) + "\n"
      );
    } 

Note that this does not address the problems with the first loop.

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

First off, I would strongly, emphatically recommend replacing the call to gets() with fgets(). The gets() function lacks boundary checking, and presents a substantial risk of buffer overflow.

Second, the delimiters for strtok() are incorrect; you presumably meant '\n' (the newline character) rather than '/' and 'n' (two separate characters). This would explain the problem you are experiencing, as right now it is truncating any word with an 'n' in it.

Third, in C, you can't have a statement followed by a declaration inside of a block. thus, you need to move the decalaration of pch to the line above the [f]gets().

Finally, I'll recommend a way of simplifying the program: in the declaration section, add the following declarations:

    int i;

    const struct {
        char* cmd;
        int code;
    } commands[] = {{"exit", EXIT}, {"dir", DIR}, {"copy", COPY}, {"type", TYPE}, 
                     {"del", DEL}, {"ren", RENAME}, {"rename", RENAME}, {"mkdir", MKDIR},
                     {"cd", CD}, {"rmdir", RMDIR}, {NULL, 0}};

You can then use this table as a lookup table for the commands, and loop through it like so:

    // TODO: Assignment 1 - Part 3 - Find and return command in commandTable that matches argv[0]
    for (i = 0; commands[i].cmd != NULL; i++) {            
        if (strcmp(argv[0], commands[i].cmd) == 0) {
            return command[i].code;
        }
    }

    return NONE;
}

(This assumes that the command codes are integers; if they are an enumeration of some kind, you would want to change the declaration of code to match.)

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

Uhm, all that return does is end the function. Since command is optional, not required, simply omitting the command keyword argument would do the trick. OTOH, if you think you absolutely need a function there (e.g., as a placeholder), you can use something like this:

def empty_command:
    pass

Which has the effect of simply ending the function.

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

DarrelMan: Did you mean to post this in the C forum? While it is certainly possible to write a shell in C++, most OS courses use vanilla C for such projects. If you are using C++, then you ought to be able to use the overloaded equality operator to compare the strings instead of strcmp(), which, given that you are looking for strict matches, should work for your purposes.

Mind you, if the goal is to write a shell, then I'm a bit confused over your variable naming. Conventionally, *argv[] is the name of a command line argument to the main() function, but beyond being a convention there's nothing special about the variable name argv. Still, one would normally assume that argv is a command argument to the current program, in which case argv[0] would be the name of the shell program itself, not the name of a program or shell operation. If, OTOH, you are using argv for the name of the array of strings which the shell reads in from stdin, and then parses to get the command line, then it is somewhat misleading to call it argv, as it can be confused with the shell's own argv argument.

To clarify what I mean: if your shell is named, say dmsh (for "DarrelMan's Shell"), then to have it running as a shell, you would run the program from the existing shell as

$ dmsh

Let's further assume you used ']' as the prompt (old-time Apple II …

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

Assuming that you are creating a new file, then the simplest solution is just to name the file testfile.html to begin with:

std::ofstream FileOne("c:\\testfile.html");

The C++ file I/O works the same no matter what the file extension is; a 'text file' is just a stream of bytes which is interpreted as character data, after all.

OTOH, if there is an existing file named testfile.txt already, and you want to rename it to testfile.html, then the easiest solution is to open testfile.txt for reading, and testfile.html for writing, and copy the data from the former to the latter:

std::ifstream infile("c:\\testfile.txt");
std::ofstream outfile("c:\\testfile.html");
std::string temp;

while (infile.good() && outfile.good())
{
    getline(infile, temp);
    outfile << temp;
}

If you absolutely need to rename the file in place, then you need to use the <cstdio> function rename():

int result = rename("C:\\testfile.txt", "C:\\testfile.html");

I hope that one of these is what you are looking for.

daino commented: Great comprehensive answer +3
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The (float) part is a cast; it converts the integer value of (i + 1) (note how I had changed i to an int ealier?) to a float value. The reason I did this was because otherwise it would have been compilede as integer division, which wouldn't give the desired values.

As for the += operator, it is what is called the accumulate-addition operator, and what it does is it adds the value on the right-hand side to the variable on the left-hand side. it is a shorthand for

sum = sum + (i / (float) (i + 1));
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

A few notes:

  • You should always declare the main() function as type int, and return a value at the end of it. While some compilers do allow you to declare void main(), it is non-standard and non-portable. Don't do it.
  • The <conio.h> header and the functions it declares are not part of the standard library, and even for those few compilers which support it, vary greatly in the specific functions it supports. Avoid using it. In any case, a good modern IDE shuch as Code::Blocks shouldn't close the program window off immediately after the program is finished, so the getch() kludge shouldn't be needed.
  • Using a float to hold an integer variable is problematic, as floats do not have an exact represention for certain integer values. The variable i should be type int in this case, and cast to float when the division is made.
  • The whole section using the variable y is unnecessary, and since y is never initialized, it actually causes the computation to fail. You can safely remove the entire thing.

Taking all this into account, the follow should do what you want:

#include<stdio.h>
#include<math.h>

int main()
{

    int n, i;
    float sum = 0;

    printf("Enter nth term ");
    scanf("%d", &n);

    printf("sum = ");
    for(i = 1; i < n * 2; i += 2)
    {
        if (i > 1)
        {
            printf(" + ");
        }

        sum += i / (float) (i + 1);
        printf("%d/%d", i, i + 1);
    }

    printf(" = %f\n", sum); …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The reason it isn't working is because the condition in the if: statement is incorrect. When you write

    if first == "a" or "e" or "i" or "o" or "u": 

... what it is really saying is

        if (first == "a") or ("e") or ("i") or ("o") or ("u"):

That is to say, it only compares the value of first to "a"; the rest of the clauses all evaluate to True, so the the whole condition will always be True.

In order to compare a single value against several values, you need to use a list and a set membership (in or not in) operator:

    if first in ["a", "e", "i", "o", "u"]:

Note that you also aren't handling the case of uppercase values, but that's a complication you can handle on your own, I think.

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

Well, the good news is, a certain number of C++0x/C++11 features did make it into VS2010 and VS2012; the bas news is, constexprs weren't among them. A detailed explanation of which features are and aren't supported can be found here.

This leaves you with the prospect of using a different compiler with Visual Studio, something that is possible with the full version of VS but not the Express versions. The obvious choice for this would be GCC, which has a little better support for C++11 than the Microsoft compilers do, but getting it to work with VS is not easy; if you really wanted to use GCC, it would make more sense to ditch Visual Studio entirely in favor of something like Code::Blocks or Eclipse, either of which integrate much better with GCC. Since your main goal appears to be to use Visual Studio Express 2010, this probably isn't an option.

The Intel C++ compiler may be an option, but it is quite expensive (US$1500), and again, you would need the full version of VS2010 to support it.

A comparison of different compilers support for C++11 can be found here. As you can see, support for the new features is spotty at best, with all of the current compilers.

As for incremental linking, I don't know of any way to disable that in VC++ Express. Is there any particular reason you need to disable it?

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

Unfortunately, Moschops is right. Assembly language by its very nature isn't particularly friendly, and x86 assembly specifically is rather gruesome. The best you can really do is get a good IDE such as RadASM, WinAsm, AsmEdit or EasyCode, which lessens the severity of it somewhat. For the sort of work you seem to be doing, AsmEdit is probably the best choice, as the others are all geared toward writing applications rather than low-level systems code.

Mind you, I am presently writing my own x86-64 assembler, but given that a) it would be using a radically different syntax based on Lisp, and b) I am unlikely to ever finish it, I don't think that it is much of an option for you.

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

OK, perhaps we need to start over from scratch. What you need to understand is that an object is a model of something. It can be something real, like a car or a person, or something conceptual, like a list or a dictionary (I use those examples because, as it happens, lists and dictionaries are objects in Python). The point is that the object captures or encapsulates the properties of the thing it is modeling, its current state, and its potential behavior. The properties and state are described by variables that are part of the object, called instance variables, and the behavior is described by functions which are bound to the object, called instance methods.

A class is a description of an object, a sort of template or mold for making new objects. It defines both the instance variables of the object, and the methods the object can perform. It works by providing a way of creating a new object - the __init__() method, also known as the constructor or c'tor. The c'tor primary job is to set the initial values of the object's instance variables. It can do anything that you can do in any other method, but it should initialize the instance variables in some way.

In Python the first argument of any instance method is the object itself, which by convention is named self. This is true of the __init__() method as well, even though it is actually not an instance method per se (it is a …

Necrozze commented: Thanks man! This was exactly what I was looking for +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Aside from the linkage problem, I noticed that in the InitialiseTree() function, you have several places where you are using 2^x to exponentiate the powers of two. The problem with this is that C doesn't have an exponentiation operator; the caret (^) is used for the exclusive-or operator instead. To exponentiate, you need to #include <math.h> and use the pow() function from the standard library, like so: pow(2, 0).

Also, you can significantly simplify that function by placing the repeated computations into loops, and moving the larger set of calculations to a utility function, like so:

void InitialiseTree(FILE *wordlist, typosWords W, int totalwordsin)
{
    int i=0, j, res;
    char word[20];
    struct timeval start, t[7], tALL;

    gettimeofday(&start, NULL);    /* start timer */
    do{
        res=fscanf(wordlist,"%20s\n", word);
        InsertWord(W, word);
        i++;
        for (j = 0; j < 7; j++)
        {
            if (i == (1024 * (int) (floor(pow(2, j)))))
                gettimeofday(&t[j], NULL);    /* save time */
        }
    }while(res!=EOF);

    totalwordsin=i;
    gettimeofday(&tALL, NULL);          /* save total time */

    for (j = 0; j < 7; j++)
    {
        calcElapsedTime(W, &start, &t[j], j);
    }

    calcElapsedTime(W, &start, &tALL, 7);
}


void calcElapsedTime(typosWords W, struct timeval* start, struct timeval* t, int offset)
{
    double elapsedTime;

    /* calculating time for all words to be inserted */
    elapsedTime = (t->tv_sec - start->tv_sec) * 1000.0;      /* sec to ms */
    elapsedTime += (t->tv_usec - start->tv_usec) / 1000.0;   /* us to ms */
    SetInsertTime(W, elapsedTime, offset);
}

This makes the function much easier to understand, and should make fixing and maintaining the code much …

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

I believe I see where the problem lies. The local variable ylop is defined in main.c, inside the main() function, as a regular char variable. The problem is that the functions are being selected using conditional compilation, which is performed by the pre-processor, not the compiler per se.

The thing is, the preprocessor #if directive knows nothing of C language variables; it can only operate on those constants which are defined using the preprocessor itself. The preprocessor operates entirely at (or, to be strictly accurate, before) compile time, and run time variables cannot affect it. Using conditional compilation to set something at run time simply won't work.

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

Technically, the while() loop is what is known as an 'indefinite iteration', which is to say that it repeats the body of the loop zero or more times, with the number of repetitions being unknown at the time the loop is begun. It repeats based on a condition which holds true, and stops repeating when the condition no longer holds. The form of the while() loop in EBNF looks like this:

while-loop ::= 'while' '(' <condition> ')' <body>

body ::= <statement>
       | '{ <statement>+ '}'

I doubt that this is any less confusing, however. The practical upshot of this is that the while loop has a conditional, similar to an if() statement, except that instead of selecting the body that follows it once it repeats until something changes the condition to false. So, let's say you want to read in something from the console, and keep repeating echoing back a line number and the string until it gets to an end-of-file marker (Ctrl-Z in Windows, Ctrl-D in Unix) is found, then you would write something like this:

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    int count;

    while (!std::cin.eof())
    {
        std::string line;
        std::getline(std::cin, line);
        std::cout << std::setw(4) << count << ": " << line << std::endl;
        count++;
    }

    return 0;
}

Now, you may wonder what the point of this program is, as it doesn't seem to be very useful; but this is actually a rather neat little utility of a type called …