PDA

View Full Version : A few Questions


chaos
July 23rd, 2007, 02:08
I had a thread a while ago about C Programming. Basically, it was decided that I should learn assembler, and so I looked into it. I tried a few Programs out, but I never had too much time to play with it. In reality, I was totally confused at everything I was reading, especially because every tutorial I found required a different program. So, lately I've been playing around with some more C, and I've managed to come up with some more questions:

1) Would you guys recommend using a Linux (Ubuntu) environment to learn C? The GCC tools seem very nice, and everything seems to be working way better than the Windows compilers I had. That said, I don't have access to as many of the header files as I did in Windows, but I suppose I can make do.

2) How would you recommend I go about learning programming? I recall (as I said earlier) Assembler was mentioned, but all that I found was archaic obsolete information. In fact, one forum was saying that good compilers can already do an excellent job of making code efficient anyways. Recommended programs? I was thinking about Linux Assembler, but maybe not.

3) Is C useful enough to invest time into, or is it becoming obsolete?

4) How can I take my code that I am writing in C have a nice UI? I remember when I learned Visual Basic, and we had things like forms that would be the visual portion of the display. I recall something about wrapping C in Java, and using Java to make a nice UI, but when I googled it, I got confused :( I don't know a thing about Java, all I want is to have a nice button or two that call on my C functions. Or I suppose I could go get the free version of Visual C, but that's probably the worst way to learn to program well.

Thanks guys!

inimino
July 23rd, 2007, 09:54
1) Would you guys recommend using a Linux (Ubuntu) environment to learn C?

Yes, without question.

Incidentally, you can set up a similar development environment on Windows, using something like Cygwin or MinGW, but as long as you have access to a GNU/Linux box, you are much better off.

The GCC tools seem very nice, and everything seems to be working way better than the Windows compilers I had. That said, I don't have access to as many of the header files as I did in Windows, but I suppose I can make do.

I'm not sure what you mean here. You have access to not just header files, but the complete source code for the entire operating system and everything that runs on it. If you mean Windows-specific headers, you should aim to write portable C which will run on any OS. Windows-specific headers are of no use unless you want to write Windows-specific programs. One of the great strengths of C is that it is highly portable, so if you write a program in standard C you can compile and run that program an almost any computer.

2) How would you recommend I go about learning programming?

I really should write an article on this topic...

I recall (as I said earlier) Assembler was mentioned, but all that I found was archaic obsolete information. In fact, one forum was saying that good compilers can already do an excellent job of making code efficient anyways.

Of course, modern compilers are quite good (although not as good as humans). However, this utterly misses the point of learning assembly language. The point is not that you're going to be writing software in it for the rest of your career, the point is that you will understand how your processor actually works. If you work through the Knuth, you'll learn an assembly language created for purely pedagogical purposes.

3) Is C useful enough to invest time into, or is it becoming obsolete?

It's worth learning, and will serve you well in your understanding of any other programming language. Of course, there are other languages worth considering as well.

4) How can I take my code that I am writing in C have a nice UI?

If you're learning C, forget about GUI. The user interface is text.

You can certainly write GUI applications in C, but that's just not a good way to learn the language, and learning a GUI toolkit at the same time as C will slow you down. Get comfortable with the command line, and the Unix way, and you'll have no trouble at all learning C.

chaos
July 23rd, 2007, 19:43
Thanks for the advice, I sort of figured I could count on a thorough answer from you :). Yes, I have no problems working with the Linux environment. In fact, I have been meaning to spend more time becoming proficient with it, but various needs lately have kept me constrained to my Windows machine. I actually have a book that explains Linux programming in great detail (not specific languages, just the tools and how the kernel interacts with hardware).

I'm not sure what you mean here. You have access to not just header files, but the complete source code for the entire operating system and everything that runs on it. If you mean Windows-specific headers, you should aim to write portable C which will run on any OS. Windows-specific headers are of no use unless you want to write Windows-specific programs. One of the great strengths of C is that it is highly portable, so if you write a program in standard C you can compile and run that program an almost any computer.

Precisely! A lot of the tutorials for C I have come across are expecting me to be using Windows, so they are often making use of Windows header files. Not a big deal though, as I am decent enough with programming in general (and I have played around with C/C++ for a while before this), that I can find workarounds. Now, when you say making programs that run on any machine, do you mean "compile" on any machine? I was giving this a lot of thought the other day, and I don't really understand this. When I write a program in C, and type the following commands:


gcc test.c
./a.out


...what exactly am I running? Is this a binary file, or assembly code? Would a.out work on any Linux machine, or would I have to recompile it for their machine? Basically, how is it that companies make programs that are put on shelves and can be installed on pretty much anyones Windows machine (is it compiled on each machine during install, or is there some sort of a framework that is talking to the CPU)? I'm confused.

I really should write an article on this topic...
:lol: Yes, I saw your posts on another thread, especially regarding Python. How about if I briefly tell you a little about what I intend to do with this. Right now I am still in high school. Last year I took a course in Visual Basic in school because it was a prerequisite to the C course. Unfortunately, due to a lack of interest the C course was dropped. Right now my two main interests are Math and Computers. I really want to go into a professional programming field, but for right now I am just learning stuff for hobby. VB was entertaining, but too simple (and did not benefit any future job expertise). So, here I am caught between the want to have fun making usable programs for myself, and also trying to learn a few things for the future. Hence my wanting to put GUI's on the programs, because it was what made learning VB more fun. That was what made PHP entertaining was that I could have visual results without adding any extra code.


now, on top of the questions I put in my replys, I also have a few more that are a little more specific to C.

1) What is this cast thing that the compiler keeps whining about?

2) According to all the documents I have read, when defining a string variable (chr), you need to put a maximum length that the word can be. Why is it that if I declare a length of 5, it doesn't really matter if the user inputs 8 characters, because the variable still seems to store all of the letters?

inimino
July 24th, 2007, 00:39
Thanks for the advice, I sort of figured I could count on a thorough answer from you :).

Hehe, you're welcome. ;)

I actually have a book that explains Linux programming in great detail (not specific languages, just the tools and how the kernel interacts with hardware).

There is a big difference betwee Linux programming and generic C programming. Linux, by the way, is actually just the kernel, not the entire operating system. Not having seen your book, I don't know what all it covers, but as you learn C you will want to learn the standard C which is the same everywhere, and try to avoid things that are specific to the linux kernel, or to any other environment.

Precisely! A lot of the tutorials for C I have come across are expecting me to be using Windows, so they are often making use of Windows header files.

In that case you should look for better tutorials, or simply not use tutorials at all. Tutorials are, in my opinion, a reasonable way to get a "hello world" project set up quickly, i.e. to make *something* work and compile and run on your own machine. Beyond that, tutorials are an ineffective learning tool, and suggest a way of learning that involved having someone explain how to do a each specific task to you, which actually stunts, rather than develops, the very skills you most need for figuring out an approach to a new problem and finding or figuring out the information on your own.

Now, when you say making programs that run on any machine, do you mean "compile" on any machine?

Yes, compiling is a prerequisite to running, so I meant both compile and run, on any architecture that has a C compiler available, which is for all practical purposes, all of them.

I was giving this a lot of thought the other day, and I don't really understand this. When I write a program in C, and type the following commands:


gcc test.c
./a.out


...what exactly am I running?

First you are running gcc which compiles and links test.c and produces a binary containing machine code. Since you didnt' use the -o argument to gcc to specify the filename for the output, it uses the default which is a.out (for historical reasons).

Your second command runs this new file. The leading ./ instructs your shell to find the file in this directory (".") rather than in your path, where ordinary commands like gcc would be found.

Is this a binary file, or assembly code?

It's a binary file, which contains machine code (it has already been assembled). In reference to Windows the term "executable" tends to be often used, along with the extension ".exe". On Unix, they are also called "binaries", typically have no "extension" (which is not a Unix concept), and are often found in directories like /bin or /usr/bin.

Would a.out work on any Linux machine, or would I have to recompile it for their machine?

It will run on any machine that is "close enough" to the one you compiled it on, in a few ways, including processor or processor family, and availability and versions of any libraries you linked against, including the standard C library itself.

On any machine that is not "close enough" you could recompile the source. So I could run it on my PowerPC Debian box, or on any of the other 20+ machine architectures that Debian runs on, or under Mac OS X, or even Windows. That's what "portability" means.

Basically, how is it that companies make programs that are put on shelves and can be installed on pretty much anyones Windows machine

Because Windows is a homogeneous environment which only runs on one architecture. Windows runs on Intel Pentium machines, and never made any serious effort to support anything else. As a result, alternative processor architectures have had no chance to compete and succeed in the market. AMD simply made chips that worked about the same as Intel chips. The 64-bit chips from AMD now are still able to run 32-bit code and had to support this in the hardware, adding considerable complexity (I can only imagine) to those chips, because otherwise there would be no way to run Windows and all of that proprietary software that people run on it otherwise. This is what the environment looks like when the industry is dominated by a single, closed platform.

Compare this to Debian, where if there are people using an architecture, and a C compiler is available for it, you can port the software over and get anything you want running on that hardware. So when AMD64 came out it just required recompiling the kernel and all the other software, and it could all run on the new platform, in native mode, not in a 32-bit compatibility mode. For any hardware platform (and free software operating systems support quite a few) anyone who cares about that hardware platform can do the work, because the source code is available and the necessary legal freedoms to do this are protected.

(is it compiled on each machine during install, or is there some sort of a framework that is talking to the CPU)? I'm confused.

It's not compiled, because the model of proprietary software development that exists today is based on not releasing the source code. So you can't compile it, fix it, understand it, or validate that it actually does what it claims to (and nothing else) you can only run it on the architecture and operating system it was originally compiled for. The portability benefits of C are only benefits if you have the C source.

So, here I am caught between the want to have fun making usable programs for myself, and also trying to learn a few things for the future.

Focus on learning the fundamentals, and do that by completing projects that interest you.

Hence my wanting to put GUI's on the programs, because it was what made learning VB more fun. That was what made PHP entertaining was that I could have visual results without adding any extra code.

PHP is just outputting text too, it's just that that text happens to be HTML. You can write programs in C to output HTML as well, just like you can also write GUI programs in C.

1) What is this cast thing that the compiler keeps whining about?

You will need a good C reference. I would highly recommend the K&R. Casting refers to changing the compiler's idea of the datatype of a particular variable. You might think you know what I just said, but really you don't, so read the K&R. ;)

2) According to all the documents I have read, when defining a string variable (chr), you need to put a maximum length that the word can be. Why is it that if I declare a length of 5, it doesn't really matter if the user inputs 8 characters, because the variable still seems to store all of the letters?

Most likely because you are misunderstanding what your program is actually doing. If you declare a character array and assign a string that does not fit in the array, this is a buffer overflow and it is one of the primary sources of problems in C programs. It may occassionally "work", by luck, in a few rare circumstances.

chaos
July 24th, 2007, 01:38
OK, I now have a pretty vague understanding of how Windows works, and the constant need to recompile stuff on Linux. Many thanks.

So, let me see if I am understanding your advice for learning programming.

a) You recommend I get this (http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29) book for reference in C.

b) You recommend I learn Assembly from this (http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming) book before delving too deeply into my Higher level studies. This book is pretty pricey, and from what I read of it on the internet, it's a bit over my head (the extent of my math work is Acc. Algebra 2).

c) Stay with Linux for learning programming, and try to keep my C programs such that they don't require platform specific headers.

---------------------

Question:

a) I remember fairly well an article that described several key differences between AMD and Intel chip machine language. Are these differences minor, or does AMD have a compatibility mode on top of its normal commands list?

b) So the Executables for windows are basically still the assembly counter part, just in a form more readable to the processor? Basically just changing it from text to 1s and 0s, or is it actually doing some major changes/conversions to the structure?

c) In thoughts of Java, I remember my programmer friend saying how Java is preferred because it's Virtual machine allows it to run well on all different types of architectures/os's. Does this mean that the code is not compiled, or does it mean that the Java VM is acting as a software interface between the program and the hardware?

-----------------

Many thanks! It's great to know people like you who can explain the problems I run into in a subject I know little about. The buffer overflow idea makes sense, and it explains why it's seemingly working (my program only has 2 variables, and with only a small amount of my system resources being taken up, there is a good chance that an overflow would work no problem).

inimino
July 24th, 2007, 02:18
a) You recommend I get this (http://en.wikipedia.org/wiki/The_C_Programming_Language_%28book%29) book for reference in C.

Yes.

b) You recommend I learn Assembly from this (http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming) book before delving too deeply into my Higher level studies. This book is pretty pricey, and from what I read of it on the internet, it's a bit over my head (the extent of my math work is Acc. Algebra 2).

It is expensive, long, and somewhat advanced. However, it starts out relatively simply. I wouldn't necessarily recommend that you drop everything else and start studying TAoCP exclusively. Consider it as some kind of wellspring of understanding and inspiration that you will go back to now and then as you are able to absorb it. It's not something you can work through in a weekend. Or a year. Also, it won't teach you practical assembly programming, the assembly language is introduced as a pedagogical aid. Don't be put off by it, though. The fundamental ideas of programming are the same everywhere. This is a way to cut straight to the heart of those ideas. If we are talking about, for example, Java, the fundamental ideas you need to know to be a good Java programmer are the same as those presented in TAoCP with an invented assembly language. The difference is that in Java there are additional layers above all that which obscure the fundamental principles.

c) Stay with Linux for learning programming, and try to keep my C programs such that they don't require platform specific headers.

Yes.

a) I remember fairly well an article that described several key differences between AMD and Intel chip machine language. Are these differences minor, or does AMD have a compatibility mode on top of its normal commands list?

There is a basic x86 instruction set, and each processor family adds additional instructions to meet some specific goal. Typical Windows programs are compiled to a Pentium target, meaning that they will not use any newer extensions but will run on any Pentium or later processor (including those from AMD). To make use of other features, software must be recompiled by a compiler that knows about the features of that CPU, and then will not run on CPUs that lack those instructions. (Cf. gcc's -march option.)

b) So the Executables for windows are basically still the assembly counter part, just in a form more readable to the processor? Basically just changing it from text to 1s and 0s, or is it actually doing some major changes/conversions to the structure?

It's a file that can be loaded into RAM by the operating system and then begin executing on the CPU. The details vary by operating system but it always includes the machine code for the program itself and some boilerplate to identify the executable file format, load other library code, etc.

c) In thoughts of Java, I remember my programmer friend saying how Java is preferred because it's Virtual machine allows it to run well on all different types of architectures/os's. Does this mean that the code is not compiled, or does it mean that the Java VM is acting as a software interface between the program and the hardware?

It's compiled to a virtual machine target, meaning that it's actually a machine code for another invented machine (rather like Knuth's MMIX, in that regard). In Java this is called bytecode, and the Java Virtual Machine is typically provided by an interpreter, or native machine code can be created in real time by a "just-in-time" compiler.

chaos
July 24th, 2007, 02:50
Excellent! I'll keep a look out for those books and pick them up as soon as I can. So you're suggesting that I should read that "Art of Programming" book in a fashion similar to the bible ... where you're absorbing wisdom, but not in any real order or with any great urgent need. :)

Now, I am curious as to why when I am going to download a Linux distribution, or even linux software for that matter, do I need to pick a CPU architecture? Why should it matter?

Oh, and how does Ubuntu for instance compile when it installs if the compiler has yet to be compiled? I suppose if Ubuntu doesn't compile, then this question doesn't matter, but I would assume that the OS would be compiled... so is the primary compiler written in machine code for the Architecture type I choose when I downloaded it?

Thanks! All these questions must be taking up a lot of your time, as your answers have been quite lengthy. I do believe my onslaught of questions is coming to an end right now, as my questions are beginning to exceed what I know to ask about. :lol: A lot of these questions are more for grasping concepts, rather than application to a specific project, so thank you for the thorough answers.

Edit: It looks like I might be able to get those books at Half Priced Bookstore for pretty cheap (like $10 a piece, but doesn't the Art of Programming have several books?). Brand new, the C book was like $40, and Art of Programming was like 100+ for the three pack.

inimino
July 25th, 2007, 03:40
Now, I am curious as to why when I am going to download a Linux distribution, or even linux software for that matter, do I need to pick a CPU architecture? Why should it matter?

Distributions don't generally require you to compile everything when you install. Instead, compiled software is released through the distribution packaging system, and you must choose the package that was compiled for the correct architecture. The exception is Gentoo, where code is downloaded and compiled on the local machine, with all the optimizations for your actual CPU and with any other options you choose.

Another exception is downloading and installing software yourself. For example, if you visit the Apache HTTP server page and download the software, you will get the source code, which you can then compile and install on any supported architecture.

Oh, and how does Ubuntu for instance compile when it installs if the compiler has yet to be compiled? I suppose if Ubuntu doesn't compile, then this question doesn't matter, but I would assume that the OS would be compiled... so is the primary compiler written in machine code for the Architecture type I choose when I downloaded it?

The process of compiling a compiler when there is no existing compiler is called bootstrapping. Typically you do this by installing an already-compiled compiler for your architecture, and then using that to compile the compiler you want. If you are porting a compiler to a new architecture, you might need to cross-compile (which means compiling on one architecture, but producing a binary that will run on a different architecture). Bootstrapping isn't an issue for Ubuntu, but it is for Gentoo, or for installing a system yourself from scratch.

Edit: It looks like I might be able to get those books at Half Priced Bookstore for pretty cheap (like $10 a piece, but doesn't the Art of Programming have several books?). Brand new, the C book was like $40, and Art of Programming was like 100+ for the three pack.

TAoCP has seven volumes, but only three have been published so far. Knuth is still working on volume 4, which itself is being published in sections, called fascicles, as he finishes them. All you need to worry about at this point is getting a copy of the third edition of volume 1.

chaos
July 25th, 2007, 06:06
Very cool, I'll probably have a chance to go to the bookstore later this week. Now, as expected, I have another question for you, and this one should be easy. What is the "-lm" operator on the end of GCC for? I saw in a forum that I should use it when I am making use of sqrt();, and while it works, I have no idea what it's doing. :lol:

Oh, and I did manage to write my own program today from scratch (not even a book or tutorial, just compiler errors ;). Basically, its a simple program that I have written a lot, and it's intention is to rapidly provide the two solutions for an equation put into Quadratic form. The one I wrote for my TI-84 Calculator did a lot more than this one did (it actually attempted to factor the problem as well if there was a possible solution that was factorable). So here it is, if you see me making any terrible mistakes or using any libraries that I shouldn't, please mention it:

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

int a,b,c;
char catch[10];
int retval;
char currentval[1];
int solutions[1][2];


int prompt(currentval) {
printf("Please Input the value of %s:\n",currentval);
scanf("%s",catch);
retval = atoi(catch);
return retval;
}

int quadrat() {
int answer1, answer2;

answer1 = ((b * (-1)) + (sqrt((b*b) - (4*a*c)))/(2 * a));
answer2 = ((b * (-1)) - (sqrt((b*b) - (4*a*c)))/(2 * a));

solutions[1][1] = answer1;
solutions[1][2] = answer2;
}

int main() {

a = prompt("a");
b = prompt("b");
c = prompt("c");

quadrat();
printf("Solution 1 = %i:\n",solutions[1][1]);
printf("Solution 2 = %i:\n",solutions[1][2]);
}

inimino
July 25th, 2007, 06:58
Now, as expected, I have another question for you, and this one should be easy. What is the "-lm" operator on the end of GCC for?

The -l option indicates libraries that must be linked against. Aside: the correct term is "option" not "operators". Unix command lines include the command name followed by arguments, some of which are options, usually introduced by the hyphen-minus "-" character. In this case the 'm' is actually an argument to the option, indicating that you want to link against the math library.

You can also check the man page—run 'man gcc' and use the "/" command to search quickly for whatever option you want to find.

So here it is, if you see me making any terrible mistakes or using any libraries that I shouldn't, please mention it:

You can actually have scanf() parse the integer for you, rather than using scanf to get a string and calling atol(). If you installed them, there are man pages for all the library functions, so you can enter "man 3 scanf" and read all about it, or you can look up the glibc manual online.

You're using int[1][2] where you should simply use int[2].

There are also inputs in response to which your program will crash, I'll leave it up to you to figure out what those are. ;)

Apart from that, doesn't look too bad.

BigBison
July 25th, 2007, 12:50
I've neglected to mention UNIX Systems Programming by Robbins and Robbins, it covers most of the fundamental stuff in this thread, works its way through POSIX threads, and wraps up with some pretty cool Internet projects -- covering web servers, caches, proxies and gateways and even gets into Internet radio. ISBN 0-13-042411-0

Study of the final chapter led to a business decision on my part to "just use Java" primarily for XSLTC (http://xml.apache.org/xalan-j/xsltc/) and the Resin Pro (http://caucho.com/resin-3.1/) webserver in a threaded architecture using an UltraSPARC T1 processor (/casts longing glance (http://www.sun.com/servers/blades/6000/) sideways... an x64 blade or two running the non-threaded apps like Dovecot (http://dovecot.org/) with the rest scaling our app on UltraSPARC T2 (http://realworldtech.com/page.cfm?ArticleID=RWT090406012516)'s). We're closing in on three years of development, using Java, which is better that than the six it would take to do C right. Although I'd prefer if the next version were not tied to Java, such an approach is not financially feasible for most startups.

The argument in favor of Java is that, particularly using an application server like Resin Pro, a web application scales across multiple servers in one big virtual machine, and takes most of the difficulty of dealing with threads out of the coder's way. Load balancing and failover between nodes is likewise not something you need to worry about, particularly (again) if you're developing web apps. Since we don't often mention it here, I'd like to point out that many web apps are written in Cold Fusion (http://en.wikipedia.org/wiki/Adobe_ColdFusion) which is now a Java application. Now, here's a crucial thing about Java -- JVMs are only optimized on Solaris running on SPARC chips, in which case the whole thing is 64-bit. In order to be compatible for other systems, i.e. Linux in all its flavors on both AMD and Intel hardware, the result is 32-bit with no optimization.

The reason Java performs so well, is if you have a four-way or eight-way motherboard running either AMD or Intel chips on either Linux or Windows or any other OS Java runs on, Java will thread as well as the OS lets it between the CPU cores. Here's where Microsoft is falling off the radar as not even Vista scales well across CPU cores -- there's only so much a VM can do. But Sun only spends the real money making Java run wicked-fast on their CPU architecture, and their OS which is optimized for such chips. Development can be done on any system, for a server running Solaris + SPARC, with the same source code. But you're not compiling your code, Java is interpreting it -- the JVM is what gets compiled, and that bytecode is only optimized for Sun's platform, although this is bound to change now that Java's open-source. Something tells me that SPARC + Solaris will run JVMs faster than anything else for several years to come, though.

Which is where straight C can still open a can of whup-ass on Java any day. If your code is portable, then any C compiler ought to be able to turn it into executable byte code optimized for the system the compiler is running on, like say you're running Gentoo or a Gentoo-ish (http://fabrice.bellard.free.fr/tcc/tccboot.html) system (http://gentoo-wiki.com/Alba_Experiment) and know your way around a compiler and know how to write sound C code and have the patience to optimize it through rigorous testing... and you'll be lucky if you pick up 15% over Java after a couple of years. If you're using a small C httpd (server) (http://www.iwdn.net/showthread.php?t=6472) you can top Resin Pro for performance on one box easily enough, but you have to work out all the threading and cacheing yourself, and how to scale across multiple CPUs if you want to really maximize scalability.

So the reality is, an awful lot of code these days is written in Java and performs awfully well out-of-the-box without tripping over its own threads without a whole lot of effort, compared to paying attention to every last detail hand-optimizing source code through iterative performance testing. For my part, once the Java code is generating income it makes sound financial sense to replace it, one piece at a time, with secure C (http://dovecot.org/doc/securecoding.txt) (although D is intriguing (http://www.digitalmars.com/d/)) code developed from the ground up by a small team who know what they are doing (i.e. understand assembly language and compilers) without relying too much, if at all, on OPC (Other People's Code).

There are definite advantages in security and performance and choice of OS/CPU over the long haul going this direction instead of using a framework like Java, yet few companies invest in Research and Development any more (Sun is a refreshing exception, also AMD no longer just copies Intel but leapfrogs them), too often focusing on just the next quarter. PHP and Java skills are in demand now, but in ten years these frameworks may be relegated to the dustbin like COBOL -- never disappearing but unable to keep up. So ask yourself when learning to code, are you learning a framework or are you learning the underlying technology? HTTP is the most mis-implemented technology out there. Most people are unaware of the deficiencies because they only deal with HTTP through a framework. Try dealing with it directly.

Java and Resin Pro are great, but we spend an awful lot of time forcing them to behave when it comes to HTTP. To code an HTTP server from the ground up which implements XProc (http://www.w3.org/TR/xproc/) and XSLT would take even more time than hammering a Java-based system into shape, but I'd feel a lot better about maintaining it over the long term instead of always having to understand that various sections of the source code are workarounds for deficiencies in Java or any Java-based framework.

I'd much prefer if the code were purpose-built for what it does, instead of coded to fake out some other layer like a VM into bass-ackwardsly accomplishing a task -- with the added drawback that the code must be altered to undo these problems as each new version of the JVM tends to fix things. Well-written C code using POSIX threads just seems more forwards-compatible over the long term, to me, barring any earth-shattering change in mankind's understanding of computers.

I try to take a twenty-year view of things. As the years pass, I want the code to stay relatively stable even if the CPU architecture changes a few times, even if newer and better compilers come along for these new CPU architectures. I don't feel that will be the case if the original Java code keeps getting patched as the years go by, to keep on top of changes in the Java language and implementation. I want off that train ASAP, which requires an R & D investment derived from operating income and, most likely, C.

Summing up, the choice between C and Java can be a difficult one. Technically speaking, C is better, but pragmatically speaking Java often has the advantage. For example, if you want to code a GUI app for your desktop, use the Eclipse Rich Client Platform (http://wiki.eclipse.org/index.php/Rich_Client_Platform) using Java and you'll be running on Windows and UNIX without all the tedium of writing code to do things like line-wrapping or cut-and-paste.

chaos
July 26th, 2007, 02:49
That's all very interesting, though I must say that some of that Java/Sun stuff is just a little bit too much for me to take in right now.

Aside: the correct term is "option" not "operators".
My mistake. Sorry :)

You can actually have scanf() parse the integer for you, rather than using scanf to get a string and calling atol(). If you installed them, there are man pages for all the library functions, so you can enter "man 3 scanf" and read all about it, or you can look up the glibc manual online.

You're using int[1][2] where you should simply use int[2].

There are also inputs in response to which your program will crash, I'll leave it up to you to figure out what those are.

Apart from that, doesn't look too bad.

Many thanks for taking the time to look through that. As of right now, all I have to go on is "C For Dummies" :lol: Wouldn't you know that I did in fact try to scanf() for an integer, but it didn't work. Silly me, I forgot the '&', and was just referencing the variable. It will take a lot of practice to get used to remembering to do that. I suppose it would be better to just say int[2], I just wasn't sure if I needed to define rows and columns in a particular order or not. As for the inputs that wouldn't work, I know there are several holes in the logic portion so far. The problem was that I was porting this off what I wrote for the TI, but the TI will tell me if the answer is not real, whereas a C program would just crash. There is a ton more that this program needs to function correctly, so I'll try and come up with a factoring algorithm tonight. Thanks!

Question: Where did you find those manuals? :? Apparently I didn't install them, and I couldn't see any immediate possibilities on Google.

chaos
July 26th, 2007, 07:55
Yes, I do believe I got the script working a little better. It checks for unreal answers, though I have yet to see any values that would have crashed the original program (unless you are referring to the fact that I only allowed the user 10 characters). I would now like to know what I should do to make the program handle decimals. I've been sticking with integers, but when I branched out and tried out floats and doubles, I get some strange answers that I didn't really want (mostly Answer 1 = 0, and Answer 2 = 1024). I remember this being an issue last time I tried writing this program in C++. As I recall, I never did fix it :(

Here's what I have thus far:
#include <stdio.h>
#include <math.h>

int a,b,c;
char catch[10];
int retval;
char currentval[1];
int solutions[2];

int prompt(currentval) {
printf("Please Input the value of %s:\n",currentval);
scanf("%i",&retval);
return retval;
}

int quadrat() {
if(((b^2) - (4*a*c)) >= 0) {
solutions[1] = (-b + (sqrt(pow(b,2)-(4*a*c))))/(2*a);
solutions[2] = (-b - (sqrt(pow(b,2)-(4*a*c))))/(2*a);
printf("Solution 1 = %i:\n",solutions[1]);
printf("Solution 2 = %i:\n",solutions[2]);
}
else {
printf("\nSorry, no real solutions. We aren't skilled enough to provide a complex answer\n");
}
}

int main() {
puts("------------------------------------------------------------------------------------------");
puts("Welcome to the Quadratic Calculator!");
a = prompt("a");
b = prompt("b");
c = prompt("c");
quadrat();
puts("------------------------------------------------------------------------------------------");
}


I cleaned up what you mentioned earlier, and thus freed myself of another library (don't need stdlib if I am not using ATOI).

inimino
July 27th, 2007, 00:04
It checks for unreal answers, though I have yet to see any values that would have crashed the original program (unless you are referring to the fact that I only allowed the user 10 characters).

No, I was referring to specific numbers that might be entered. Always consider the case, for any numeric input, that it may be negative, or zero, or one, or the multiplicative or additive inverse of any of your constants. (Particularly when doing division... hint, hint.)

I cleaned up what you mentioned earlier, and thus freed myself of another library (don't need stdlib if I am not using ATOI).

It looks better.

Question: Where did you find those manuals? :? Apparently I didn't install them, and I couldn't see any immediate possibilities on Google.

apt-get install manpages-dev glibc-doc

http://www.gnu.org/software/libc/manual/
(You probably want "one HTML page per node".)

chaos
July 27th, 2007, 02:06
I don't see what the problem could be with the formula. It's the standard formula for finding the roots (zeros) of a quadratic polynomial in standard notation. The formula should already be able to handle any inputs (including 0). If you are referring to the fact that I am dividing by "2*a" and that any number divided by 0 is undefined, then all I need to do is throw in another check for that. Would it really crash the program? Wouldn't it just give a really strange answer? I don't have the app in front of me right now to check, as I have Windows up right now. I'll look into it this evening. Fortunately I am through enough math to see the formula issues, though I don't really know how it's going to respond. Just a thought, because 'a' can't be zero and still have a quadratic polynomial, there should be no reason why a user would input it. You would just have a standard "bx+c".

Any thoughts on what kind of value I should use for numbers with fairly long decimals, and a negative or positive value? I'll look through the manual, but the explanations I saw elsewhere weren't very descriptive.

inimino
July 27th, 2007, 02:55
If you are referring to the fact that I am dividing by "2*a" and that any number divided by 0 is undefined, then all I need to do is throw in another check for that. Would it really crash the program?

Yes.

Wouldn't it just give a really strange answer?

If you consider "Floating point exception" on the standard error stream to be a really strange answer, then yes. ;)

In fact, the behavior of a C program in the case of division by zero is undefined, meaning that it is up to the implementation (i.e. the compiler and/or the operating system) to decide what to do. Typically it will simply kill the program with an error message similar to the above.

Any thoughts on what kind of value I should use for numbers with fairly long decimals, and a negative or positive value? I'll look through the manual, but the explanations I saw elsewhere weren't very descriptive.

The glibc manual isn't a good way to learn C, it's just a reference for the functions (such as scanf()) provided by the GNU standard C library. You should probably wait till you get the K&R, which will tell you all about the numeric types including float and double.

chaos
July 27th, 2007, 04:01
Alrighty then! I'll play around with it this evening (I seem to have the most problem solving abilities in the evening :)), and get back with what I come up with. I intend to add a check to verify that the user did in fact put a non-zero value for "a", and then I'll begin implementing the crude factoring script. I say crude, because it only works with simple factors. When I looked up an algorithm for true factoring, I came up with some pretty wild stuff like sieving (http://www.math.uiuc.edu/~landquis/quadsieve.pdf). I know the algorithm for solving them with Pencil+Paper, but they really don't convert well into computer talk (you can brute force solve it, but this is ridiculously inefficient for most scenarios, considering that there is a good chance there are no factors to find :lol:

chaos
July 27th, 2007, 08:09
Hey Cheers!!! I think I've made some serious progress. The problem I was having with using floats earlier was that I was forgetting to swap all my %i's with %f's. :) Now all's I gots to do is some more tweaking, and it'll rival my calculator version.

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

int a,b,c;
float retval;
char currentval[1];
float solutions[2];

int prompt(currentval) {
printf("Please Input the value of %s:\n",currentval);
scanf("%f",&retval);
return retval;
}

int quadrat() {
if(((b^2) - (4*a*c)) >= 0) {
solutions[1] = (-b + (sqrt(pow(b,2)-(4*a*c))))/(2*a);
solutions[2] = (-b - (sqrt(pow(b,2)-(4*a*c))))/(2*a);
printf("Solution 1 = %f:\n",solutions[1]);
printf("Solution 2 = %f:\n",solutions[2]);

if(solutions[1] == floor(solutions[1]) && solutions[2] == floor(solutions[2])) {
printf("\n Though you probably already knew this, these are easily factored\n");
printf("Factors of the polynomial: \n(x");
if(solutions[1] > 0) {
printf("+%f)",solutions[1]);
}
else {
printf("%f)",solutions[1]);
}
printf("And (x");
if(solutions[2] > 0) {
printf("+%f)",solutions[2]);
}
else {
printf("%f)",solutions[2]);
}
}

}
else {
printf("\nSorry, no real solutions. We aren't skilled enough to provide a complex answer\n");
}
}

int main() {
puts("------------------------------------------------------------------------------------------");
puts("Welcome to the Quadratic Calculator!");
a = prompt("a");
b = prompt("b");
c = prompt("c");
if(a == 0) {
printf("\nWhat are you trying to pull? This is not a quadratic polynomial!!!\n Let's try and see if you can't come up with a better value for the leading coefficient.\n");
main();
}
else {
quadrat();
}
puts("\n------------------------------------------------------------------------------------------");
}