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

Wasn't resursive algorithms non-efficient ?
I mean if you look at recursive fibonacci's runtime you'll see Its not efficient at all O(N^2) !

It depends greatly on the particular algorithm. While recursion is generally less efficient due to overhead issues (which can be obviated in some instances by tail-call optimization, and by memoization for functional programs), most recursive algorithms are not inherently less efficient than iterative equivalents. The fibonacci algorithm is a specific case where, yes, the naive tree-recursive form is grossly inefficient compared to the naive iterative algorithm, but this isn't going to hold for all recursive algorithms.

OTOH, as mike_2000_17 points out, iteration is in general a better 'fit' to the conventional random-access sequential machine model. Even in languages like Scheme, where recursion is the natural means of repetition, it is common to use iterative algorithms (even if they are implemented by means of recursion) for anything requiring efficiency.

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

In most modern languages, there are two fundamental approaches to repeating an action: either iteration, in which an action is placed inside a special-purpose structure which causes the action to be repeated, or recursion, in which a general-purpose function calls itself (or another function which in turn calls the earlier function). Which is to be used depends on the nature of the problem at hand, and to a great degree, the language being used. Some languages, especially Lisp and the various functional languages, strongly favor recursion; but most other languages, including C++, focus almost entirely on iteration.

As a result, novice C++ programmers are often given little if any experience with recursion, which tends to lead to it being overlooked even for problems where it is well suited. Also, recursive design takes a very different view of what it means to repeat something, and the approach can seem alien to programmers more familir with iteration. Finally, because it is based on function calls, recursion generally takes more memory and time than the equivalent iteration, and while there are ways for a compiler to optimize away this overhead for some types of recursion (specifically tail calls, where the recursive call is the last step in the function), few C++ compilers do any tail call optimization. As a result, recursion is poorly understood by many C++ programmers.

This is unfortunate, as in some ways recursion is the simpler of the two approaches to looping. It does not require any additional language constructs …

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

Then you should have asked the question in a new thread, rather than raising a long dead one back up.

As for the answer to your question, the original C++ compiler was written in C, and most C++ compilers today are written in either C or C++. I gather, however, that your real question is, 'how did they write the first compilers without a compiler to use?' The answer is, they used assembly language and an assembler. But how was the first assembler written? Simple: it was written in assembly language, and then hand-assembled into some representation of machine code (in octal or hex or what-have-you).

However, that would have been a long time ago; by the mid-1960s, high-level languages were dominating the field, though machine code and assembly came into use again briefly when the first personal computers came on the scene circa 1974. Today, when a new model of CPU is made, the software for it is first written on some existing system, then cross-compiled to the new system. It is exceedly rare for anyone to do any machiine-code programming today.

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

I am currently working on a new language design in the Lisp family, which I am calling 'Thelema'. It is intended to be a multi-paradigm language which is related loosely to Scheme and, to a lesser extent, Common Lisp, but with modern concepts such as package management, support for object oriented design, and an extensive library system.

The current design sketch can be found on its Github repo, where I am (slowly) working on codifying the design and eventually impementing it.

Note that I am not soliciting collaborators (though I wouldn't turn one down out of hand, either). I am hoping to get some eyes on the language design and opinions about it, in the hope that I can find places where it isn't clear or where I have ideas which are unlikely to work. At this point, it is still quite some way away from implementation, though I would like to begin working on a sub-set compiler in the new year.

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

Could you please explain your goal in this a little? We need more context to be able to give a meaningful answer.

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

What is happening here is that you are defining the function at the point where you want to be calling it, but you never actually call it. You do refer to the function, on line 14 of the code above, but that is not a function call; without parameters, it simply returns a reference to the function itself. In order to call the function, you need to have an argument list, where to values to be passed to the function are in parentheses, like this:

convert_Fahr2Cel(degree)

This is true even of functions that don't take parameters; those would need an empty argument list, like so: foo(). Without the argument list, you are returning the function, not the function's value.

You have a number of other errors in the code as it is, as well. First off, you generally want to separate the function from where it is being called; the usual practice is to put the functions before the running code, and then have the actual code in a test to make sure that the source file is the one that should be running, like so:

if __name == '__main__':
    # your running code here

What this is doing is checking that this file is being used as a program, and not a module (a source file that is called from another program). Don't worry too much about it yet, it will make sense later when you learn about modules, just know that it is a …

ddanbe commented: Nice. +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would start by writing a data file or database that holds the questions. Each question would have an identifier (a primary key), a difficulty level, a subject, a question, a set of four answers, and a marker indicating which answer is the correct one. I would then write a class or set of functions which can read the questions from the database, order them by difficulty, and select one from each difficulty level at random. Then, assuming that you are playing the current version of the game rather than the 'classic' Regis version, you would want a shuffle function to randomize the order and value of the questions below the 9th difficulty level.

Note that all of this is the part that takes place behind the scenes of the game. It is better to write and test these parts separately from the user interface, to keep the design modular.

At this point you should be able to test how these fit together with a simple text version of the game. Once you have it to the point where you are able to play the game as a text game, replace the text interface with the PyGame interface. At that point, I expect you'll be back here looking for more advice :)

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

A few pieces of advice:

  • Never use certain letters for variable names, especially l (lowercase 'L') and O (uppercase 'o'). They are too easily misread as the numbers 1 and 0, especially when scanning the code quickly.
  • Using a for: loop and then breaking down the values of the loop into separate conditions (the so-called 'for-case' or 'for-if' anti-pattern) makes no sense; you are better off either finding a way to consolidate the conditions, or else eliminate the loop.
  • When getting the mininmum or maximum of a list, the easiest (if not necessarily the most efficent) way to find the value in question is to sort a copy of the list. In the case of a multi-dimensional list, merge the lists into a single copy first, then sort.

Taking this last piece of advice into account, the solution should be trivial:

t = [[1.0, 2.0, 3.0, 4.0, 5.0],
     [6.0, 7.0, 8.0, 9.0, 0.0],
     [1.1, 2.2, 3.3, 0.1, 0.3]]

def minmax(table, row):
    table[row].sort()
    return table[row][0], table[row][-1]

min, max = minmax(t, 1)

print(min)
print(max)
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

static POD variables are initialized just like all other global POD variables. I posted assembly code to prove it.

In the case you give, where the static variable is initialized to a fixed value, the compiler is indeed initializing the variable at the start of the process; however, given that this is a reasonable optimization which can be shown to have no effect on program behavior, it is possible that the compiler generated the code in this manner for the sake of efficiency rather than strict compliance. The assembly output for the code given by Mike_2000_17, where the static variable is being initialized to a value passed at run time, would be more relevant for this matter. A modified version of that code would make the behavior clearer:

#include <cstdio>

int get_first_value(int value) {
  static int x = value;
  return x;
};

int main() {
  int n;
  printf("Enter a value to test: ");
  scanf("%d", &n);
  printf("%d\n", get_first_value(n));
  printf("%d\n", get_first_value(69));
};

Here, the initializing value will not be known at compile time at all; it would not be possible to have an initialization at the start of the process. And indeed, the program run comes out as follows:

$ ./testd.exe
Enter a value to test: 23
23
23

While I do not have a copy of VS on the system I am on right now, I do have GCC, and the (unoptimized) assembly output for this program comes out as:

    .file   "testd.cpp"
.lcomm …
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

I would like to propose a link thread for posting listings of sites on CS topics not tied to a specific language. Two that come to mind as being relevant to some of the more common questions would be the OS Dev Wiki, and the similarly themed but less established Compiler Dev Wiki. Rosetta Code would also be relevant, for comparisons between languages and paradigms. A few others to start with might be:

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

This posting may help explain why it is (generally speaking) a mistake to include functions in a header, and what headers are mainly used for in the first place.

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

The best recommendation I have is to download the Lazarus IDE,

http://www.lazarus.freepascal.org/

It includes Free Pascal as part of the installation.

In light of the fact that the instructor provided the compiler and development tools, I can't promise that getting the current version of either Free Pascal or Delphi would help; if the instructor is requiring the the older Turbo Pascal, then you are pretty much stuck, as the graphics systems have been redesigned since then. I would check with the professor about this before commiting to using the newer version.

If you end up having to use the older compiler and graphics, this page may prove helpful.

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

Knowing assembly is also useful in debugging programs; being able to walk through the generated code with a debugger is a underrated but important skill.

Compiler development also (usually) requires assembly language knowledge, for generating the target code.

Aside from this, understanding assembly language gives significant insights to the actual behavior of the computer system, especially how things like function calls actually work in the system.

That having been said, not many programmers today actually ever need to write assembly code. It is a valuable skill, but more for its side results, rather than for actual use as a programming language.

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

Aside from the formatting issues (which I resolved automagically using the GNU Emacs' Pascal Mode auto-indent), I see some definite show-stopping problems with this code. Given your current approach to laying out the board on the screen, you would need something on the order of 350000 'screen shots' to display all the possible outcomes of a game. You are going to have to find some way of generating the screens programmatically. I would start by simplfying the issue, using a simpler display matrix rather than the multi-column approach you are now using, something like this:

   | o | 
---+---+---
 o | x | x
---+---+---
   |   |

This would be much easier to write a generating code for, as you would be able to write an 'x' or an 'o' with a single character. All you'd actually need to store is a cross-bar (---+---+---) a vertical bar (|), and a 3x3 array holding the positions of the already marked values.

program TICTACTOE;
{$APPTYPE CONSOLE}
uses
SysUtils;

const
   crossbar = '---+---+---';
   verticalbar = '|';

type
   Mark = (EMPTY, CROSS, NOUGHT);

var
   Board: array[1..3, 1..3] of Mark;

   procedure initBoard;
   var
      i, j: integer;
   begin
      for i := 1 to 3 do
      begin
         for j := 1 to 3 do
         begin
            board[i,j] := EMPTY;
         end;
      end;
   end;

   procedure drawMarks(lineNumber: Integer);
   var
      i: integer;
   begin
      for i := 1 to 3 do
      begin
         write(' ');
         case (board[lineNumber, i]) of
            EMPTY:  write(' ');
            CROSS:  write('x');
            NOUGHT: write('o');
         end;
         write(' ');
         if i < …
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

First, please do not post new questions in existing threads someone else started, unless they are directly relevant to the discussion in the thread. Starting a new thread is much beter. Second, be careful not to double post when you submit your messages. Third, please try to be as clear in your writing as possible, using proper grammar and punctuation as best to your ability.

To address the question you seem to be asking, I'll start by asking, did you use an import ctypes directive before trying to access that library? You always have to import all libraries you are trying to use before using them. Also, user32 is itself a sub-library; you would want to call a specific function from that library such as MessageBoxW() in order to get anything done with it.

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

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

Well, the instructor's hint at the bottom definitely seems to be the place to start, really. I would pick the Individual class first, as it is the simpler of the two; it's really little more than POD, with no methods other than maybe getters and setters.

The Factory class is a bit more involved, as the Factory objects have to be able to mananage their product lines. How you represent the product lines is something of an open question; the easiest solution is to have a simple Product class, consisting of the properties given in the instructions, and have an array or vector<> of Products to hold the given product lines.

The last class you want to define will be for the DistributionCenter itself. This will mostly consist of two arrays - one for the Factory objects and the other for the Individual customers. You will also want methods to add, modify, and remove the elements of these arrays.

ddanbe commented: Good hints for the OP! +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

There isn't any kind of procedure in Scheme to do that, no; how could there be, when you aren't actually looping in the sense of an iterative construct? Instead, what you would do is have a different pathway in your conditional which makes the appropriate call.

For example, let's say that in our example where you were generating a list, and you wanted to have it skip, say, the values for 5 and 11 in a range of 20. You would do this in one of two ways. The way closer to what you are talking about would have a test for those cases, with calls specific to the case at hand:

(define (interrupted-range m n . skips)
  (let range-loop ((count-up m))
    (cond ((>= count-up n) '())
          ((memv count-up skips)
           (append (list (+ 1 count-up)) (range-loop (+ count-up 2))))
          (else (append (list count-up) (range-loop (+ count-up 1)))))))

(interrupted-range 0 20 5 11)

However, no self-respecting Schemer would do that for this particular case. Instead, you would generate the initial list, and then filter the list to remove the unwanted values:

(define (int-range-2 m n . skips)
  (filter (lambda (x)
            (not (memv x skips)))
          (range 0 20)))

The point is, there may not be an exact equivalent to continue or break, but there are alternatives that are just as effective.

As for the case where you are populating a list or array, Rubberman is correct; the values aren't separate values, but part of the array in question, and in …

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

The good news is, there is a control structure in Scheme that can be used as either a break or a continue; the bad news is, it is really hairy, and not something you would want to use in most cases. The (call-with-current-continuation) function (abbreviated as (call/cc) in most implementations) is more than just a loop short-circuit; it is a generalized form of goto that allows to to halt a computation, move on to a different one, and then pick up again where you left off. This example (taken from a page of Scheme idioms uses a continuation to break out of a nested loop:

   (define (continued x) 
     (call/cc (lambda (return)
                (let loop ((y 0))
                  (if (eq? x y) (return)
                      (begin 
                        (display y)
                        (newline)
                        (display "next? ")
                        (loop (read))))))))

Fortunately, you rarely need it; in most cases, careful design of the returns from a call can avoid the need to break a loop entirely.

Can you give a more specific case of what you want? Scheme (and Racket) uses recursion for nearly all forms of repetition, including those that would be done by iteration in other languages (what is referred to as a 'recursive iteration' in Scheme parlance). Normally in Scheme, you can escape a simple loop by using multiple returns in a (cond) clause, with the return percolating back up the function-call stack.

As for creating new variables, I'm not sure I follow your question. Are you asking how to generate a list or vector, …

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

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

I know you have a working program as of now, but you'll still want to try and understand the difference between a function prototype and a function call, and between the formal parameters and actual arguments.

First for prototypes. These are, basically, declarations describing how the function's signature, which is to say, it's name, return type and parameter types. You need to have the prototypes ahead of any calls to the function, so that the compiler knows that there is in fact a function names so and so that takes such and such arguments.

If you look at a header file such as <iostream> or <cmath>, you will see a large number of function prototypes, for the standard library functions. These functions are, broadly speaking, the same as those you would write yourself, they just are part of the standard library. As I explain here, headers are used mainly as a way of getting large numbers of declarations and prototypes into programs without having to enter them in manually each time.

When you write a function prototype, you need to put the types of the return value and the parameters, and optionally, the names of the parameters as they are in the actual function implementation. The names of the parameters aren't really important to the prototype, but they do make it easier to understand.

When you then write the function's implementation, you need to have it's parameter types and return type match those of the prototype, or else …

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

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

Asking "What's the best programming language?" is much like asking "What's the best airplane?" - it entirely depends upon what you want to do with it.

As Nelson-sensei once wrote, it is in some ways closer to asking, "What's the best religion?" Programmers often commit themselves to their tools, well beyond reason. It is perhaps less true today, but languages are often the subject of both prejudice and egotism. While no one language is best for all purposes, it is not uncommon for a programmer to try to use the language which he or she had 'bonded' to for all purposes, simply because they can't see the limitations of their tools.

ddanbe commented: Well said. +14
rubberman commented: Ditto what ddanbe said. See my post below. +12
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

As an aside, I noticed that you have posted to both here ande DevShed with the same problem. FYI, cross-posting is generally frowned upon, as it leads to duplication of effort. You should only post to one forum at a time, and only re-post elsewhere if you think you have exhausted the possibilities there, and if you do cross-post, always give a link to the other fora so that everyone can see what was done before.

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

Conceptually, a string is an object that holds a piece of written text. The name 'string' is historical, and refers to the concept of 'string rewriting', a mathematical technique for analyzing sentences in an abstract grammar; the intended mental image is of pieces of paper held together by a (physical) string, which was an early way of manipulating character strings before computers.

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

One piece of advice I can give is that, whenever you find yourself using several variables of the form nameN, consider refactoring them as an array or an ArrayList. The hang0, hang1, hang2,... hang10 variables in particular stand out as something where a number of things would be simplified if you used an array for them.

Similarly, given that you are just using them to initialize an array, there is no need to have the individual letter buttons declared separately. If you really need to be able to refer to them by the letters themselves - which I don't believe you ever do - you could easily use a HashMap for that purpose instead:

private HashMap<char, JButton> letterButtons = new HashMap<char, JButton();

// later, initialize the HashMap like so
for (char letter = 'a'; letter <= 'z'; letter++) {
    letterButtons.put(letter, new JButton(letter);
}

Note also that you cannot use a String as the index of a swich() statement; you can, however, use an enum, which I have done in the following version of your code:

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

enum ActionType {Easy, Medium, Hard, NoMercy};

public class Hangman extends JFrame {

    private HashMap<Character, JButton> letterButtons = new HashMap<Character, JButton>();
    private JLabel trysRemaining;
    private int setTrysHere = 6; …
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

There really isn't any one language which all beginners start with, and no language appeals to everyone; the real issue is that a lot of universities start people off with C (or worse, C++), despite it being poorly suited for most beginners.

As for complexity, C is actually a rather simple language, compared to Python. This is not the same as saying it is an easy language by any stretch of the imagination. C is simple in the same way chess is simple: it has relatively few rules and very few exceptions to those. It still takes years to master either of them, and starting of with them before any others is, for most people, an exercise in frustration.

(To follow the analogy, Scheme and the other Lisp languages are like go: there are hardly any rules to the game at all, and learning how to play takes just a few hours, but mastery is a lifetime's work. Conversely, C++, Java and Perl are like Brockian Ultra Cricket or Dragon Poker - mountains of rules and variations thereof, more than any one person could ever really learn. But that's still better than C# and VB.Net, which are like TEGWAR - the rules seem to slip and slide around at random and no one will tell you all of them, and eventually you end up under the table with a massive headache.)

Python is more like, say, your typical video game. It has …

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

Well, for a design document, I suppose it's a start. You would need a lot more detail, however, even before you could consider writing any actual code.

If your actual goal is to write a photo editing program, well, that's about as complex as any project you could have chosen. I think I personally would tackle just about anything else first before trying something that difficult... and I do systems programming as a hobby.

BTW, despite this book's title and the opinions of far too many 'educators', neither C nor C++ make a good language for beginners; they are both designed for experienced, professional coders, especially C, and they both are far too difficult for most newcomers. I would recommend a language like Python or Ruby as a better place to start, though that is a personal opinion and completely subjective (actually, I would really recommend Scheme, but there you're getting a bit too outré for most people).

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

I'm afraid we'll need more information than just the assignment statement. Is there anything in particular that confuses you?

  • Do you know how to use multiple source and header files?
  • Do you know what a pointer is, and how to use one?
  • Do you know how to define a class, and where you would define it?
  • Do you know what a member (or instance) variable is, and how to declare one?
  • Do you know what a member function (also called an instance method) is, and how to define and implement one? Do you know where you should implement them?
  • Do you know what accessors and mutators (i.e., getters and setters) are, and how to implement them?
  • Do you know what a queue is, and how to define and implement a class that acts as one?
iamthwee commented: solid advice +14
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

I was hoping to coax the OP into solving the issue, or at the very least go over the specific problems it had with us explicitly, but oh well.

If it helps any (which I doubt, but who knows), here is how I would solve this problem:

#include <iostream>

struct TaxRate
{
    int bracket;
    double rate;
};


int main()
{
    float income = 0;
    float tax = 0;


    const TaxRate tr[6] = {
        {0, 0.0},
        {10000, 0.1},
        {30000, 0.2},
        {50000, 0.3},
        {70000, 0.4},
        {100000, 0.5}};

    std::cout << "Enter income: ";
    std::cin >> income;

    if (income > tr[5].bracket)
    {
        tax = income * tr[5].rate;
    }
    else
    {
        for (int i = 5; i > 0; i--)
        {
            if (income > tr[i-1].bracket && income <= tr[i].bracket)
            {
                tax = income * tr[i-1].rate;
                break;
            }
        }
    }

    std::cout << "Income tax is :" << tax << std::endl;

    return 0;
}

Since you're course probably hasn't covered arrays and structs yet, and might not even have covered loops yet for all I know, this isn't going to help you in your particular assignment, but it might give you some idea of how to solve it in a bit more professional manner.

ddanbe commented: Nice code +14
sujanthi.kumari commented: thanks +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh dear, not this argument again :( It seems as if this argument flares up every three months or so, and frankly, it is purely a waste of effort.

Let's first define our terms: a programming language is a language is capable of describing a sequence of actions for a computer to take, either explicitly (as in procedural or OOP languages) or implicitly (as in functional or logic languages). A script is a program which is primarily used for controlling the invocation of othe rprograms. A scripting language is a programming language used primarily for writing scripts.

Note tha there are two crucial facts here: first, that scripting languages are programming languages, and second, that by this definition, Python and Ruby are not scripting languages. While they can be used for writing scripts, and often are, neither are used exclusively for scripting (even Perl, which is mostly used for scripting, is entirely a scripting language). This leaves the rather bogus term 'scripting language' for those languages which really are used exclusively for scripting, such as the various shell script languages, or Windows batch scripts.

Octet commented: A Good Summary, and I am going to agree and step out of the discussion now. +5
sepp2k commented: Well said. +5