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

I just noticed (or rather, figured out why it was happening) a problem with the code as above, so here is a fixed version:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

#define BUFSIZE 1024

/* function prototypes */
long string2long(char* rep, unsigned int base);
void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();

char buffer[BUFSIZE];

long string2long(char* rep, unsigned int base)
{
    unsigned int len, i, digit;
    long sub_result, result = 0;
    len = strlen(rep); /* get the length of the string */
    for (i = 0; i < len; i++)
    {
        /* take the ASCII value of the digit
        and subtract it by the ASCII value of '0' */
        digit = rep[i] - '0';
        sub_result = digit * (long) pow(base, len - (i + 1));
        result += sub_result; /* add sub_result to the rolling total */
    }
    return result;
}

void Binary2Decimal()
{
    long result;

    printf("[BINARY TO DECIMAL CONVERSION]\n");

    printf("Enter a Binary number: ");
    fgets(buffer, BUFSIZE, stdin);
    buffer[strlen(buffer) - 1] = '\0'; /* eliminate the trailing newline */
    result = string2long(buffer, 2);
    printf("\n\n");
    printf("Decimal equivalent is: %d\n", result);
}

void Octal2Decimal()
{
    long result;

    printf("[OCTAL TO DECIMAL CONVERSION]\n");

    printf("Enter an Octal number: ");
    fgets(buffer, BUFSIZE, stdin);
    buffer[strlen(buffer) - 1] = '\0';
    printf("\n\n");

    result = string2long(buffer, 8);

    printf("Decimal equivalent is: %d\n", result);
}


void Hexa2Decimal()
{
    long result;

    printf("[HEXADECIMAL TO DECIMAL CONVERSION]\n");

    printf("Enter a Hexadecimal number: ");
    fgets(buffer, BUFSIZE, stdin);
    buffer[strlen(buffer) - 1] = '\0';
    printf("\n\n");

    result = string2long(buffer, 2);

    printf("Decimal equivalent is: %d\n", result);
}

int main()
{ …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's see how it does using fgets() instead, then:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>

#define BUFSIZE 1024

/* function prototypes */
long string2long(char* rep, unsigned int base);
void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();

char buffer[BUFSIZE];

long string2long(char* rep, unsigned int base)
{
    unsigned int len, i, digit;
    long sub_result, result = 0;
    len = strlen(rep) - 1; /* get the length of the string */
    for (i = 0; i < len; i++)
    {
        /* take the ASCII value of the digit
        and subtract it by the ASCII value of '0' */
        digit = rep[i] - '0';
        sub_result = digit * (long) pow(base, len - (i + 1));
        printf("%d\n", sub_result);
        result += sub_result; /* add sub_result to the rolling total */
    }
    return result;
}

void Binary2Decimal()
{
    long result;

    printf("[BINARY TO DECIMAL CONVERSION]\n");

    printf("Enter a Binary number: ");
    fgets(buffer, BUFSIZE, stdin);
    result = string2long(buffer, 2);
    printf("\n\n");
    printf("Decimal equivalent is: %d\n", result);
}

void Octal2Decimal()
{
    long result;

    printf("[OCTAL TO DECIMAL CONVERSION]\n");

    printf("Enter an Octal number: ");
    fgets(buffer, BUFSIZE, stdin);

    printf("\n\n");

    result = string2long(buffer, 8);

    printf("Decimal equivalent is: %d\n", result);
}


void Hexa2Decimal()
{
    long result;

    printf("[HEXADECIMAL TO DECIMAL CONVERSION]\n");

    printf("Enter a Hexadecimal number: ");
    fgets(buffer, BUFSIZE, stdin);

    printf("\n\n");

    result = string2long(buffer, 2);

    printf("Decimal equivalent is: %d\n", result);
}



int main()
{
    char value;
    char answer;

    do
    {
        printf("Conversion from any base to base 10\n\n");
        printf("a - Binary\n");
        printf("b - Octal\n");
        printf("c - Hexadecimal\n");

        printf("Select a value to be converted: \n");
        fgets(buffer, BUFSIZE, stdin); …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, as I've told you a few times already, you really want that to be int main(). I know that Turbo C++ accepts void as the type of main(), but even at the time TC++ came out, it was incorrect according to the (then brand-new) ANSI C89 standard. Oh, and don't forget the return 0; at the end of main(), too.

To address the question, I suspect it's a consequence of using scanf(), a function which tends to cause endless trouble. What you need to do is add an small function to eat the garbage that is stuck in the input buffer:

void clear_stdin()
{
    while((c = getchar()) != '\n' && c != EOF);
}

call this after each use of scanf() and you should be able to eliminate some of these problems. Alternately, use fgets() instead, and parse the resulting strings with sscanf() when reading in numbers (that is, when you aren't trying to use your own conversion function to do it).

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

Wait, what? 101(base 2) is 5(base 10). That's correct.

100b = 4   \
              4 + 1 = 5
  1b = 1   /
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Take a look at what variables the Octal2Decimal() and Hexa2Decimal() functions are actually printing before you come to the conclusion that your conversion code is correct.

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

If you look down the C++ forum page to the previous thread, you'll see that I gave a detailed answer already.

Would you do us all a favor and not create a new thread each time you log in? It is much easier for everyone if you continue the existing conversations rather than jumping to a new one all over the place. Thank you.

Stuugie commented: If I didn't know better I would say john.kane ignored you on this one. +5
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, let's take a closer look at the Binary2Decimal() function and see what we find.

void Binary2Decimal()
{
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");

    long b2,f2=1,d2=0;
    gotoxy(1,15);
    printf("Enter a Binary number: ");
    scanf("%d", &b2);

    printf("\n");

    while(b2>0)
    {
        if((b2%10)==1)
        {
            d2=d2+f2;
        }
        b2=b2/10;
        f2=f2*2;
    }
    printf("Decimal equivalent is: ", d2);
}

Now, you start by asking for the user to enter a number in binary - that is to say, a string of ones and zeroes. However, you then have the scanf() function read in a value which is being interpreted as an int, as a decimal number, and putting that value into a long. This means that the value is not being treated as binary. Even if you had told the function to interpret the value as a binary, it would read it into the long as a two's complement binary representation. All well and good, except you then try to treat that number as if it were a character string! In essence, you are confusing two different representations of the same data, the same as if you had confused the word 'Manila' with the city of Manila.

What you want to do, first off, is change the declaration of the variable that you are reading the value into. Let's use a better variable name while we're at it:

char binary_rep[33];   // enough to hold 32 bits, plus one delimiter

Here I've declared a 33 element array of characters, which we'll use to hold our input string. …

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

The primary thing that leaps out at me is that you dropped the left brace on line 5.

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

Woooee's advice is spot on, as far as it goes. However, if you are trying to repeat something without knowing how many times to repeat it, what you would want is a while: loop.

pagechoice = '1'
while pagechoice != '0':
    pagechoice = input("Please choose one:")

    #Now it will determine which page you choose.

    if pagechoice == '1':
        print(""" This is page one """)
    elif pagechoice == '2':
        print(""" This is page two """)
    elif pagechoice == '3':
        print(""" This is page three """)
    elif pagechoice == '4':
        print(""" This is page four """)
    elif pagechoice == '5':
        print(""" This is page five """)
    elif pagechoice == '6':
        print(""" This is page six """)
    else:
        print("Sorry, but what you have typed in is invalid,\nPlease try again.")

this will keep asking for a page number until the user enters a zero. On the gripping hand, if you have something where you want to repeat a fixed number of times - say, one time for each member of a list - you can use a for: loop:

for x in ['a', 'd', 'm', 'e', 'h']:
    print(x)

With a for: loop, it will set the index variable (in this case x) to the next member of the list until it reaches the end of the list. So on the first pass, x would equal 'a', on the second, x would equal 'd', and so forth.

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

Unfortunately, you still aren't indenting your code, making it virtually impossible to read the program. Allow me to (once again) run your code through Astyle and format it sensibly:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>


char value;
char t, u, v;
char answer;

void Binary2Decimal()
{
    gotoxy(1,13);
    printf("[BINARY TO DECIMAL CONVERSION]");

    long b2,f2=1,d2=0;
    gotoxy(1,15);
    printf("Enter a Binary number: ");
    scanf("%d", &b2);

    printf("\n");

    while(b2>0)
    {
        if((b2%10)==1)
        {
            d2=d2+f2;
        }
        b2=b2/10;
        f2=f2*2;
    }
    printf("Decimal equivalent is: ", d2);
}

void Octal2Decimal()
{
    gotoxy(1,13);
    printf("[OCTAL TO DECIMAL CONVERSION]");

    long number4,dec7,rem7,i7,sum7;
    gotoxy(1,15);
    printf("Enter an Octal number: ");
    scanf("%o", &number4);

    printf("\n");

    dec7=printf("%d", number4);
    {
        rem7=dec7%8;
        sum7=sum7 + (i7*rem7);
    }
    printf("Decimal equivalent is: %d", number4);
}

void Hexa2Decimal()
{
    gotoxy(1,13);
    printf("[HEXADECIMAL TO DECIMAL CONVERSION]");

    long hex,dec8,rem8,i8,sum8;
    gotoxy(1,15);
    printf("Enter a Hexadecimal number: ");
    scanf("%X", &hex);

    printf("\n");

    dec8=printf("%d", hex);
    {
        rem8=dec8%16;
        sum8=sum8 + (i8*rem8);
    }
    printf("Decimal equivalent is: %d", hex);
}

void main()

{
    do {
        clrscr();
        gotoxy(1,3);
        printf("Conversion from any base to base 10");
        gotoxy(1,5);
        printf("a - Binary");
        gotoxy(1,6);
        printf("b - Octal");
        gotoxy(1,7);
        printf("c - Hexadecimal");
        gotoxy(1,11);
        printf("Select a value to be converted: ");
        scanf("%c", &value);

        switch(value) {
        case 'a':
            Binary2Decimal();
            break;
        case 'b':
            Octal2Decimal();
            break;
        case 'c':
            Hexa2Decimal();
            break;
        default:
            printf("Wrong input");
        }

        gotoxy(1,20);
        printf("Do you want to continue NUMBER CONVERSION?(y/n) ");
        scanf("%c", &answer);
    }

    while(answer == 'y');
    getch();
}

I cannot emphasize this matter enough; the fact that your professor is accepting unformatted code is a disturbing confirmation that she isn't fit to teach programming, IMAO - I would not accept such code at …

ddanbe commented: More than helpfull +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As I explained in my previous response, what you are trying to write is a lexical analyzer. I gave links to some helpful posts and resources in that post that you should have gone over by now.

No one here is going to write this program for you. We can only guide you in this project; we cannot and will not help you cheat on it by doing it for you. Please show us what you have done so far so we can give you advice, otherwise there isn't much we can do.

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

My prof said that she will not accept my program because she said that cout,cin & etc... are not allowed use only the older style..

Hold on for a moment. Is this a course in C++, or in C? Most C++ compilers (including Turbo C++) will also compile C programs. If the course is supposed to be in C, it would explain why the professor only wants the C-style libraries.

Otherwise, I would say you professor is an incompetent and you should find a better instructor, or perhaps a better university. Of course, I also feel that way about choosing Turbo C++ as the compiler in the first place, but I know that some countries have standardized on it for all programming courses (though as far as I am aware the Philippines is not one of them), so there may not be much the professor can do about that.

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

Please go back and read what I had to say about int main() and proper formatting. I know it may seem trivial, but these are important, even in Turbo C++. Maybe especially in Turbo C++.

As for writing a function, well, the good news it, you already know how to do that. The main() function may be privileged, but it is still basically a function (mostly) like any other. If you want to add a function of your own, there are basically three things to do:

  • Figure out what the function is supposed to do, and what parameters (inputs from the function calling it) it will need, and what kind of value it will return. Let's start with the menu() function; all it has to do is print out the menu, so it doesn't take any parameters and returns no value.

    void menu()

This is the function's delcaration, or its head, so to speak; it says what the function's name is, what its parameters are (none) and what its return type is (void, or no return value). The next thing after the function declaration comes the implementation or body: in this case, it's just the code to print the menu. Together, they look like this:

void menu()
{
    clrscr();

    cout<<"Conversion from any base to base 10"<<endl;
    cout<<endl;

    cout<<"a - Binary"<<endl;
    cout<<"b - Octal"<<endl;
    cout<<"c - Hexadecimal"<<endl;
    cout<<endl;
}

Now, before you can use the function, you need to tell the function that is going to call it …

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

Well, the first part (display user instructions) seems straightforward; simply write a function that displays the instruction message. While you can probably hard-code the instructions and get credit for it, I would recommend storing them in a data file which the program can read at initialization.

BTW, part four is already in the code (lines 21-29), though separating it out as a function would be advisable. If you had written this yourself, you would know this; but this has all the earmarks of a program written by an instructor as a skeleton which the students are expected to expand upon.

Oh, and while it is not strictly relevant, if you have a compiler and library that supports (part of) C++11, you may be able to replace srand() and rand() with default_random_engine and uniform_int_distribution<int> objects from the <random> library to get a less biased distribution of numbers (the rand() %n method has an inherent bias towards the lower part of the range, IIRC).

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

NO.

This code relies on the old Turbo C++ compiler, and isn't even remotely viable with any modern C++ compiler.

The real answer is, it depends on the operating system you are writing for and the graphics libraries you are using. C++ doesn't not have any standard graphics support, or even console support for that matter; only the very bare-bones stream I/O is part of the standard library. Everything involving things like background is dependent on the graphics software you are using.

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

The problem seems to be the simplest of all: in the if() statement, you compare sex to "F" (capital F) instead of "f" (lowercase f). This can be solved simply by changing the character being compared, though I would actually recommend a more general solution, by forcing the characters to one case or the other before testing:

int femalecount=0,malecount=0,total;
char race, office, sex;

for(int i=0; i<2; i++)
{
    cout<<"\nwhat is your sex?? answer using f(female) or m(male) ";
    cin>>sex;
    sex = toupper(sex);
    cout<<"\nwhat is your race?? answer using b(black) or w(white) ";
    cin>>race;
    race = toupper(race);
    cout<<"\ndo you work in a office?? y(yes) n(no)";
    cin>>office;
    office = toupper(office);
    if((sex == 'F')||(sex =='M') && race=='W' && office=='Y' )
    {
        cout<<"\nyou are allowed to enter the clan ";
        cout<<endl;
    }

You'll need to #include <cctype> to get the toupper() function.

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

Oh, I see. That puts you in a rather sticky position, as the instructor doubtless is expecting the program to work with the Turbo compiler. I normally would recommend Code::Blocks with the MinGW GCC compiler, and still would suggest that you get it for your own use, but for classwork, it sounds like you're stuck with TC++.

(BTW, there is a compiler which is the lineal descendant of Turbo, sort of, namely Embarcadero C++ Builder XE5. However, it is commercial software - though there is a free demo, you have to pay to use it past the trial period - and is so radically different from Turbo C++ that they are for all intents and purposes unrealted compilers.)

The Turbo C++ compiler dates from 1989, which is nine years before the new headers were introduced, so no, it won't work with those. It also won't run on modern versions of Windows (i.e., Vista and later) without a DOS emulator such as DosBox. Turbo C++ is a dead-end technology, but at this stage I'm not sure what you can do about it if the coursework requires it.

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

While it is unfortunate that it took so long for one of us to get back to you, you have to understand that this can and often does happen on these fora; we are doing this on a volunteer basis, and there isn't always someone able or willing to answer a given question on the forum. That having been said, I'll address several issues with your code:

  • First off, you are using the older style of headers; the standard C++ headers (since 1998) omit the '.h' extensions, and the C library headers are pre-pended with a 'c'. Thus, you would need to use <iostream> and <cstdio> when using a modern compiler.
  • The header <conio.h> is not a standard header, and while some compilers have a version of it, you should aviod it. It was originally specific to a particular MS-DOS compiler from 1989 (Turbo C), and has never been part of the language. DO NOT USE IT IN NEW PROGRAMS, PERIOD.
  • The return type of main() is int. It always has been, and should never be anything else. void main() is simply wrong, and most compilers will warn you about using that.
  • Your code is not formatted; you should always apply some kind of indentation to your code. If the code isn't formatted in some manner, most experienced programmers won't even try to work with it. This may well be the reason you didn't get any responses.
  • You mix C and C++ stream I/O functions, which is allowable …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Which compiler are you using, and have you tried compiling the second version of the program without running it at the same time (usually by selecting 'Build' or 'Compile' rather than 'Run')?

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

OK, so what you actually need is a lexical analyzer, also called a tokenizer from it's main mode of operation, which is to break a stream of characters into tokens. There are several discussions of this topic on DaniWeb, if you do a search on 'tokenizer'. You might want to check out this post, for example, as well as the StateMachine class in my own Suntiger Algol compiler.

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

OK, as an aside, what is with these '213xxxxx' usernames? Is this one person creating multiple accounts, or are these student IDs all from a single school, or what?

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

In essence, a lambda expression is an anonymous function, which can be used in a context where a regular named function could be used, but where the function in question exists for a single purpose and thus should not be given a name (to avoid using up the namespace). They are most often used as a function argument for a higher-order function (that is, a function that operates on other functions, either by taking a function as a parameter or by returning a function as a value, or both). For example (in pseudo-code), if you have a function map() which applies a function to every element of a list or array,

map(increment, [1, 2, 3, 4, 5]) -> [2, 3, 4, 5, 6]

then you could have a lambda expression that squares its argument like so:

map(lambda(x) { return x * x }, [1, 2, 3, 4, 5]) -> [1, 4, 9, 16, 25]

This is exactly how the map() function in many functional languages works, in fact. To give the above example in Scheme,

(map (lambda (x) 
        (* x x))
     '(1 2 3 4 5))  

or in Haskell (if I am recalling it right):

map (\x -> x * x) [1, 2, 3, 4, 5]

(I am deliberately not giving you an example in C#, as that would be too close to doing your homework for you.)

The name comes from the lambda calculus, a model of mathematics which is …

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

It would help a lot if you told us what was going wrong; while we can surmise a lot from the code, to be as accurate as possible, we would need to know the exact error messages you are getting.

That having been said, I can see three major problems, offhand, two of which would lead to a compile time error, the other to a runtime error.

The first is a common mistake made by many new C++ programmers, which is that you are confusing function prototypes and function calls, and possibly function implementations as well. A function prototype is a description of the function; it gives the name of the function, the return type, and the name and type of its parameters, like so:

double choiceC(double balance, double totalServCharge)

You would place this before any calls to the function are made. The header of a function implementation looks very similar, and in fact must match the prototype, at least as far as the function name and the types are concerned:

double choiceC(double balance, double totalServCharge)
{
   // the body of the function ...
}

This can be before or after the function is used, so long as you have a prototype for the function before the calls. Finally (and this is where you are having trouble), a function call consists of the name of the function and a list of actual parameters (i.e., arguments), but does not include the types of the parameters.

choice(myBalance, …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

In C/C++, command-line arguments (AKA shell arguments) are passed through optional parameters to the main() function. These parameters, by convention named argc and argv, are an integer count of the arguments passed to it, and a pointer to an array of char arrays, which hold the string values of the arguments themselves. Under most (but for some reason, not all) systems, argv[0] is the name of the program itself.

For example, you can write a program that echoes its arguments simply by looping on argc:

#include <iostream>

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++)
    {
        std::cout << argv[i] << std::endl;
    }
    return 0;
}

The downside to using shell arguments is that there is no checking for the type or number of arguments passed; thus, you need to check argc to make sure that it is a legitimate number of arguments, then parse the arguments for their values.

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

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

And if you think you won't get caught by your professor... think again.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic …

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

I do recommend that you go over the new code carefully, and familiarize yourself with what I did and how it works. If you have any questions, especially regarding the activation record, feel free to ask.

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

OK, I'm going to break the usual rules regarding how much we can do, but I have a reason for doing so. I worked out a solution for the problem, but the code I wrote involes using some techniques you are almost certainly unaware of at this time. The main things I have done are A) moved the function(s) past the end of the main code, so that they ae no longer embedded in the program; B) re-written the print function as two functions, one of which, print_array, calls the second, print_array_line; C) used parameter passing in the functions to make them more general and modular; and D) applied stack discipline to hold an activation record for the print_array function. I have also used a few features of SPIM which are not supported by MARS, but changing the code to work in MARS is simply a matter of replacing the symbolic constants with the equivalent literals. The SPIM=specific version should be a good deal easier to read, but the MARS version should work in both emulators.

    .data

#stack offsets
fp.ra = 4
fp.a0 = 8
fp.a1 = 12
fp.a2 = 16
fp.a3 = 20
fp.s0 = -4
fp.s1 = -8
fp.s2 = -12
fp.s3 = -16
fp.s4 = -20
fp.s5 = -24
fp.s6 = -28
fp.s7 = -32
################################################################################
#System calls
print_int   = 01 #$a0  = integer
print_float = 02 #$f12 = float
print_double= 03 #$f12 = double
print_string= 04 #$a0  = string
read_int    = 05 #returns integer …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It would be impossible for us to tell you how to describe a lesson we haven't seen ourselves. I can make a few guesses on things, but I can't be certain they are correct.

  • I think you have the relationship between Raspberry π and the Python language interpreter reversed. The Raspberry Pi is a small computer that usually runs a variant of the Linux operating system. The Python interpreter is a program that runs on the computer.
  • As for the last part, I suspect that what the instructor wrote would have been something like:

    • Edit - typing the program into the Python interpreter or into a file
    • Run - executing the program; in the interpreter, hitting the 'Enter' key will start the snippet of code you've entered running
  • In general, 'input' is the process of getting information from someplace (e.g., the keyboard) into the program. In this case, the instructor probably is referring to the input() function, which is what you use to get input from the user - it will type out a string (a sequence of letters or other characters) and then wait until the user types something and hits the 'Enter' key. Once the user hits 'Enter', whatever they typed is sent to the program. For example:

    x = input('Please enter your name: ')
    

will put whatever the user has typed (which you hope is their name) into the variable x (a variable is a place in memory …

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

Could you please tell us what system or emulator you are using? There are small but sometimes important differences in the way different emulators (e.g., SPIM, MARS) work, especially in terms of the assembly directives they accept, and it may be relevant. For now, I'll assume you are using SPIM, but if you are using a different one such as MARS or MIPSym, or an actual hardware MIPS system such as a Playstation 2, please let us know.

As for how to print exactly five values per line, there are two simple solutions: first you can have an inner loop with a counter variable, which would repeat five times. The psuedo-code for this would be something like:

a = your array
p = pointer to a
x = 10
while x != 0
    y = 5
    while y != 0
        print 0(p)
        p += 4
        y--
    end while

    print newline
    x--
end while

The other solution is to simply unroll the loop, and have one loop which hs five print operations:

a = your array
p = pointer to a
x = 2
while x != 0
    print 0(p)
    p += 4
    print 0(p)
    p += 4
    print 0(p)
    p += 4
    print 0(p)
    p += 4
    print 0(p)
    p += 4
    print newline
    x--
end while    

On a guess, the first is what you instructor is looking for.

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

As sheikh.islampollob said, the language that you use to implement the project is less relevant to the solution than the design of the program is. One thing I will tell you right now is that the project as described will take more than a month to finish correctly; indeed, if it is mission-critical as it sounds, I would allocate a month or more simply to the planning stages, even if I were applying Agile principles to the project.

If I had to make a suggestion regarding the language, I would start by asking what language(s) you are most familiar with; if you aren't fluent in any language, then tha is a showstopper, as a solid grasp of the language you are working in is necessary for any programming work of any sort.

Since it sounds like you are not a professional programmer yourself, and this is a significant professional project, I would delegate the work of programming it to a dedicated software contractor. For a medical application, simply trying to cowboy your way through the project when you aren't an experienced developer yourself is a recipe for disaster.

ddanbe commented: "A recipe for disaster", is mildly spoken +15
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

How so? Saying it isn't helpful doesn't tell us what would be helpful. Please give us more to go on, if we are to help you.

As I said, the first step here would be to write a function that returns accpets the Celsius value and returns the Fahrenheit value. Before we can do that, though, we need to work out just how to convert a Celsius value to Fahrenheit. As it happens, this part was already given to you:

f = 9 / 5 * c + 32

So, taking this one step at a time, let's see how this works. If you open up the Python interpreter, and enter

c = 0

then enter the formula above, followed by

f

you should get back the value 32.0. OK, then! Now what you need to do is make the function, which would simply be

def celsius2fahr(c):
    return 9 / 5 * c + 32

basically, all we've done is give the formula above a name, celsius2fahr(). To test it, try entering

celsius2fahr(100)

this should give you 212.0 as the result. you now have a way of repeatedly getting a Fahrenheit value from a Celsius value.

I've got to go now, but this should at least move you in the right direction.

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

Hold on for a moment, here. Is this supposed to be a C++ program, or a C program? While most C code is also valid C++, as a rule in C++ you want to avoid using certain C idioms and functions, with malloc(), free() and the standard C I/O functions (e.g., printf()) near the top of the list. If you are writing a C program, it would be advisable to post your questions in the C forum, to avoid confusion.

On a related note, why are you allocating the arrays dynamically, when you are using fixed array sizes?

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

If you are of a mathematical bent, you might try the exercises on Project Euler.

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

What, if anything, do you have already?

I would recommend starting with a simple function that takes a Celsius value and returns the Fahrenheit equivalent. If you don't know how to write a function, let us know and we'll explain it for you.

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

We can start by explaining how to post code in this forum correctly, and while we're at it, how to format Java code according to the usual conventions. The forum software does not, by default, retain indentation; in order to post code samples, you need to indent the code by four spaces. Fortunately, the forum software includes a 'Code' button at the top of the editing menu, which makes it easier to paste code in at one go:

import javax.swing.*;
import java.util.Scanner;

class RadiusOfCircle {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); // read the keyboard
        System.out.println("Enter radius:"); // print to screen
        double radius = sc.nextDouble(); // read in a double from keyboard

        // use the formulas for circle properties
        double area = Math.PI * radius * radius; // d/2
        double circ = Math.PI * radius * 2; // c = pi*d = 2 * pi * r

        // construct a string to show on the screen
        String output = "Radius: " + d/2 + "\n";
        output += "Area: " + area + "\n";
        output += "Circumference: " + circ;

        // give it a title
        String title = "Here's the result!";

        // the type
        int type = JOptionPane.PLAIN_MESSAGE;

        JOptionPane.showMessageDialog(null, output, title, type);
    } // end main
} // end class

(Note that I made a couple of minor changes to the code, starting with the class name. HTH.)

Now that we can read your code, can you tell us what errors you are getting?

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

Yes, I got confused. I shouldn't post when only half awake...

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

The two errors you mention come from the same source: line 2. The directive you want is use namespace std;; note the semi-colon, and the difference is the word use versus using, as well as the need to actually give the namespace you want to make visible (in this case, std, the standard library namespace).

You have a number of other problems with this code, most notably that you need to put the left braces after the conditional of the for() loops.

    for (d=0; d<b; d+1)
    {
        if (d=c)
            cout<<"*";
        else
            cout<<" ";
    }

Note, again, that the fields of the coditional need to be separated with semi-colons, not commas.

Also, keep in mind that C++ is case-sensitive; Cout and cout are two different identifiers.

Finally, I would recommend learning how to indent your code in a suitably helpful manner. Note how the nesting in the code is revealed when you indent the code effectively.

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

Oh, my, we have a bit of a problem here. You are lucky if anyone responds to this at all, and if they do, it will be rather irate.

Why? Well, first off, you are reviving a long-dead old thread. Second, you are hijacking that thread for a question unrelated to the original question. Third, and worst of all, you posted a homework problem without demonstrating any evidence that you had made an effort to solve it yourself.

DON'T DO THOSE THINGS.

If you have a new question, start a new thread. Ask actual questions, rather than demanding an answer be given to you. And most of all, show your work. No one, and I mean NO ONE here is going to do your work for you. We will answer questions, and give advice, but we won't help you cheat.

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

I would not really be inclined to send you or anyone else here my email, and I doubt anyone else here would either. Public discourse is highly prized here and strongly preferred. In any case, it is likely that only certain parts of the program are failling to compile; posting the relevent code and error messages here would be more fruitful for all involved.

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

We would need to see the code, or at least the parts that are experiencing difficulties. We'd also need to know the errors you are getting. Finally, it would help if you could tell us what the porgram is for, and how it is meant to work.

Are you certain about the size of the code base? Fifty megabytes of code is indeed massive, and more than any one of us could reasonably review. I don't know if VC++ could compile something that large in a single unit. How many source files are part of that, and are you certain you aren't including things like the project files in the size?

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

OK, while Ciprian 2 says is broadly correct, the post overlooks an important first step: lexical analysis, the process of identifying lexemes (also called tokens) in the input stream. While Ciprian2 mentions tokenizing, it gets handwaved in the post, which isn't really fair; lexing is a fairly involved subject by itself. Aside from defining a Token type, as C2 showed, you need to have a means for determing what is and isn't a valid token, and for categorizing the valid tokens. Let's revisit the Token class with a minor refinement in the form of a TokenType enumeration:

enum TokenType {
     INVALID, EOF,
     IDENTIFIER, RESERVED,
     INTEGER_LITERAL, 
     LPAREN, RPAREN, 
     ADDOP, MULOP, ASSIGN,
     COMMA, SEMICOLON
};

struct Token {
    int startPos;
    std::string text;
    TokenType type;
};

We'll ignore whitespace for the moment; most languages today use whitespace primarily as a separator, though there are exceptions. What you will need is a function that reads the input stream one character at a time, and based on the first character and thopse which follow, determines what kind of token you are reading, until it comes to the end of the token.

So, the first thing we need is function that reads in a single character, and keeps track of the position in the input stream. Fortunately, all you need for this is cin and a counter, which can be done like so:

int pos = 0;

char readchar(ifstream f)
{
    char in; 
    f >> in;
    if (in != EOF && f.good())
    { …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, it does say Java, in the second assignment description. I suspect, however, that it was an error - my guess is, they use the same basic assigment in both the C++ and Java courses, and the instructor made a mistake when editing the assignment.

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

As Moschops says, the Turbo C++ compiler dates from 1989, and was for a older operating system that is no longer supported by Windows' backwards compatibility. If you are using a version of Windows newer than XP (that is, Vista, 7, or 8), then there is no way to run the compiler without using an emulator such as DosBox.

Unless you absolutely must use TC++ (for whatever reason), I would recommend downloading either Visual C++ Express or Code::Blocks. Both of these are free IDEs which include compilers along with them (Microsoft Visual C++ and GCC, repsectively). My suggestion is to try Code::Blocks, as it is a bit easier for newcomers to use (IMHO).

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

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

And if you think you won't get caught by your professor... think again.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic …

Ancient Dragon commented: Great advice :) +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You say that the code compiles without problem, but I can see an extraneous open brace at the top of the code which would be a showstopper. This may simply be an artifact of copying the code to the forum, however.

I recommend you indent your code effectively, according to a style you find aesthetically pleasing and helpful; the specific style doesn't matter much, so long as you apply some sort of indentation, and are consistent in using the same style across the board. Here is your code again, suitably indented in Allman style (sans the extra brace at the top, and the unneeded Microsoft pre-compiled header, and with the modern headers for the remaining ones):

#include <iostream>
#include <cstdio>
#include <cstring>

class inventory
{
private:
    int prodID;
    char prodDescription[20];
    int qtyInStock;

public:
    inventory() //default constructor
    {
        prodID = 0;
        strcpy(prodDescription,"-");
        qtyInStock = 0;
    }

    inventory(int a, char *b, int c) //constructor that initializes a new Inventoryobjects with the values passed as arguments
    {
        prodID = a;
        strcpy(prodDescription,b);
        qtyInStock = c;
    }
};

int main(int argc, char* argv[])
{
    inventory obj(1,"cotton tshirt",4);
    return 0;
}

I assume that you are using Visual C++ for this, given the use of the <stdafx.h> header. Can you tell us the version you are using? The use of the older style headers (e.g., <iostream.h> rather than <iostream>, <stdio.h> instead of <cstdio>) should have raised a warning with any recent versions of the compiler. Do you know what level of warnings …

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

What is happening here is that you are actually calling the input() operation separately each time you are testing for it, which means that if the value of the first entry is not '1' (and note that it is the string '1', not the numeric literal 1), then the value is discarded - you never save it anywhere. Then, when you get to the first elif clause, you call input() a second time, reading a new value in and testing that. Likewise, the second elif clause reads for a third time, and tests the third value entered.

To avoid this, you want to call input() only once, and save the value in a variable, which you would then test for the three values:

        selection = input()
        if selection == '1':#This is fine.
            print('Okay, you\'re heading to {}\'s tavern.'.format(self.name))  

        elif selection == '2':#This has to be typed in twice.
            print('Okay, you\'re heading to {}\'s inn.'.format(self.name))     

        elif selection == '3':#This has to be typed in three times.
            print('Okay, you\'re heading to {}\'s city hall.'.format(self.name))          

        else:#Four times.
            self.cityMenu()

This should solve the problem nicely.

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

We cannot simply give you code; that would be cheating. However, I can offer you the algorithm which you can use; I'm a bit short on time right now, but I should be able to get back to you in a couple of hours.

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

Oh, and for the future, please do not use ALL CAPS in your postings like that. It is universally considered quite rude, as it is seen as the equivalent of shouting at the top of your lungs. Proper punctuation, grammar and netiquette are quite important in fora like these, especially in an international venue like DaniWeb.

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

First off, could you give more detail as to what you need? As I understand it, Kirchhoff's First Law is an equation regarding electrical flow across circuit intersections; Wikipedia gives the informal form of it as:

At any node (junction) in an electrical circuit, the sum of currents flowing into that node is equal to the sum of currents flowing out of that node, or: The algebraic sum of currents in a network of conductors meeting at a point is zero.

When you say you need the program to 'illustrate' Kirchhoff's First Law, do you mean it should calculate the values coming into and out of the node, from and to the given circuits; or that you need to simulate the circuits visually, as a circuit diagram (which would require the former computations, as well as the graphics handling)? Do you need to simulate a specific circuit that can be hard-coded into the program, or (more likely) does it need to be able to take a set of circuit definitions and translate those into the combined circuit?

Also, could you show us what work you've already done on the project? One of the rules of DaniWeb is that you need to show your effort on the project, in part so that we know where you are in it and don't duplicate work you've alrady done, and partly so we can tell that you have put a good-faith effort into the project yourself before asking for help. What code …

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

Please do not hijack existing threads with unrelated questions like this; in the future, start your own thread. In any case, the question is too broad, and has too many unknowns (regarding your state of knowledge, the context in which the question comes up, etc.) to be easily answered; it also comes across as a homework problem, and while we are willing to help you solve your homework, we won't do it all for you.