Heroes of Might and Magic Community
visiting hero! Register | Today's Posts | Games | Search! | FAQ/Rules | AvatarList | MemberList | Profile


Age of Heroes Headlines:  
5 Oct 2016: Heroes VII development comes to an end.. - read more
6 Aug 2016: Troubled Heroes VII Expansion Release - read more
26 Apr 2016: Heroes VII XPack - Trial by Fire - Coming out in June! - read more
17 Apr 2016: Global Alternative Creatures MOD for H7 after 1.8 Patch! - read more
7 Mar 2016: Romero launches a Piano Sonata Album Kickstarter! - read more
19 Feb 2016: Heroes 5.5 RC6, Heroes VII patch 1.7 are out! - read more
13 Jan 2016: Horn of the Abyss 1.4 Available for Download! - read more
17 Dec 2015: Heroes 5.5 update, 1.6 out for H7 - read more
23 Nov 2015: H7 1.4 & 1.5 patches Released - read more
31 Oct 2015: First H7 patches are out, End of DoC development - read more
5 Oct 2016: Heroes VII development comes to an end.. - read more
[X] Remove Ads
LOGIN:     Username:     Password:         [ Register ]
HOMM1: info forum | HOMM2: info forum | HOMM3: info mods forum | HOMM4: info CTG forum | HOMM5: info mods forum | MMH6: wiki forum | MMH7: wiki forum
Heroes Community > Other Side of the Monitor > Thread: Introduction to Programming ( with C )
Thread: Introduction to Programming ( with C ) This thread is 2 pages long: 1 2 · NEXT»
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 03, 2006 04:38 PM bonus applied.
Edited by dimis at 16:35, 09 Dec 2006.

Introduction to Programming ( with C )

The aim of this thread is to assist people who want to learn how to program, yet they don't have a clue where to start or what is really needed in order to write their own programs. Moreover, this thread is going to be an introduction to programming with C language, rather than an introduction to C. This might sound vague right now but the main idea is that throughout this thread general programming concepts will be discussed (in a way that they apply to any high-level programming language) and more particularly we'll discuss/analyze their implementation in C.
As is the case with any human language, programming languages need practice and examples so that someone can feel confident with whatever he wants to do. For this reason, this post will also serve as a table of contents for all aspects that are going to be discussed on this thread.


Table of Contents.
Page 1
* Setting up a lab: Compiler & Editor
* Your first program: Hello world!
* Basic Data Types
* sizeof operator
* Extensions for printf and scanf functions.
* COMPILER HOWTO: Naming Executables, Show All Warnings.
* Valid Source Code, ANSI C, and other dialects
* Commenting source code
* Complete Reference for printf and scanf functions

Page 2
* Conditions [aka Expressions]
* Branching [if-then-else, ?-:, switch]
* Assignment Conventions
* Loops [while, do-while, for]
* Find maximum of N integers that are given sequentially




References
References below are not at all complete and will be updated as time goes by. Note that if you are going to buy a book from Amazon, it is recommended to use this search engine which will also make a contribution in this community. For more info check out here.
Books
[1] The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie. This is an excellent book if you have prior programming experience in any language. On the other hand, if you have no programming experience, then this book requires maturity as you read it in order to learn C. When you learn the basics, this book will serve as an excellent reference in your book-shelf, and it will save you from trouble countless times.
[2] C: How to Program by Deitel & Deitel. Please use my link above to have a glance on the frontcover of the book. If you are going to buy it (which will worth every penny you pay if you have no prior programming experience) please remember to use HC's search engine for Amazon here. Regarding the poor 2 out of 5 stars that is given to this book currently on Amazon, have a closer look on what this fellow says: If you have 4th edition, then you probably have 95% of 5th edition. This might be true, but the rating of the book should not be based on the amount of new info the book provides with respect to the earlier version. The rating should reflect the completeness and accuracy of what is written. You might also want to have a look on critics for earlier versions, for example 4th and 3rd. Pay special attention on the amount of people that agree/disagree with each review and you 'll realize what I mean. Also, have some time to read the bad reviews and judge on your own, whether or not those "bad" things described actually apply on you. Furthermore, you might not want to spend so much money. That's fine. Try to buy a former edition of the book and/or search for a used one. It will save you from lots of money probably.
Finally, note that each version covers also an introduction to C++, which makes this book ideal for an introduction in both of these languages. Editions 3 and 4 state that they have an introduction to Java as well. I certainly support though author's decision on putting Allegro in 5th edition (instead of Java). This certainly makes the book a whole more interesting than earlier version.
This is a 5 out of 5 stars book (if you want to learn a programming language and you have no prior experience). Don't hesitate to buy it.

Online Material
[3] Learning GNU C is an online tutorial for C. It seems that it is currently being developed as well, so, some things might not be covered.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 03, 2006 05:44 PM
Edited by dimis at 03:21, 10 Nov 2006.

Setting up a lab: Compiler & Editor

First things first. How do people write programs and create executables?
The idea is that they describe in a convenient language (aka programming language) step-by-step instructions of what they want to be done. Computers on the other hand, can only "realize" 0s and 1s and make arithmetic operations real fast. But a high-level (human-intuitive) programming language (like C) is by no means a bunch of 0s and 1s. So, here comes the need for an artifact that is going to stand somewhere in between a human and a computer, so that whatever is written in a human-intuitive language is rephrased to a computer-intuitive language (aka machine language). This artifact is called a compiler.
A small note here: Not all programming languages allow a user to generate executables. In these cases the artifact of translation is called interpreter. The idea in these cases is, that the interpreter plays the role of the "man-in-the-middle" (just like the compiler does), but contrary to the compiler, it does not generate an executable so that someone can run it any time with a simple command in a shell(e.g. command prompt). Its work is exactly what the name implies. It interprets the program the human wrote (aka source code) to instructions recognized by a computer (machine code); these instructions are directly given for execution and the user is presented with the result of his/her instructions. As an example of an interpreted programming language you can check out LOGO (the drawing turtle).
Back on topic: We are going to discuss about programming with C language, hence you are going to need a compiler in order to be able to generate your own programs. If you have a computer with Unix/Linux, then you are done and you can skip the part with instructions on setting up a compiler on your system. However, if your OS is Windows, keep reading ():



Compiler: DJGPP
I spent some time with various free compilers for C that you can find on the internet. I ended up recommending DJGPP since it is a pretty small package + easy installation combo.
Installation Instructions: I noticed that some mirrors on their site are outrageously slow, hence I mirror your download package here.
Download from my link above and unzip contents on the root directory (c:\) of your pc by preserving directory structure inside the zipped file. You are set! You now have a C/C++ compiler in your pc!
----
Minimal Installation:
Visit the homepage of DJGPP. Follow Zip Picker link (in the introduction section). The choices I made on the link above (DJGPP.tar.gz):
Basic Functionality:
* Build and run programs with DJGPP.
* Windows 2000/XP
* Yes
* C (no other check on rest languages)
Integrated Development Environment and Tools
(no check on all 3)
* Yes on GDB
Extra Stuff
* Extra documentation formats
----

The packages for the above choices (which can be found on the tar.gz above) are the following:


----

Now let's add some functionality and convenience for your lab: Open My Computer-> Hard Drive C-> DJGPP (view DJGPP folder's contents).
Create a new folder named "sources".
Right click on white space and create a new text-document. Name this empty file "djgpp.bat". Right click this new file and select edit (or open it up with notepad), and write inside:
Quote:
@echo off
set PATH=C:\DJGPP\bin;%PATH%
set DJGPP=C:\DJGPP\djgpp.env
cd C:\DJGPP\sources
cmd
Close all windows and create a shortcut on your desktop (i.e. right click on empty space of your desktop, then New->Shortcut).
On the location, fill with:
C:\DJGPP\djgpp.bat
and on the name for this shortcut:
DJGPP Shell
You are done!



----
If this is your first time in programming, skip the Editor part that follows and procceed to the next post. This way you are going to test your settings and write your first program in C.
----



Editor: Crimson or Vim
There are plenty of good editors around, so the choice was pretty hard actually.

Crimson Editor: The homepage of this editor is here and you can get it here (current version 3.7).
I think the best plus this editor has is the Windows-oriented GUI which is going to make easy for everyone to adapt. After all, the two most important things an editor must have is syntax highlighting and line numbering.

Vim: The homepage of this editor can be found here and you can get it here. Note that if you don't download the Self-Installing executable you have to download runtime files as well.
As you can view from the download section the big plus this editor has is its platform-diversity. In other words, if you plan to change your OS one day, you can be proficient in an editor that already exists in your new OS. A tutorial can be found here.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 03, 2006 06:01 PM
Edited by dimis at 02:53, 05 Nov 2006.

Hello World!

This is the all-time-classic introductory example, so no deviations here.
Open Notepad and write:

Save file as "hello.c" under C:\DJGPP\sources directory and close Notepad. Double click your DJGPP Shell shortcut and give:
gcc hello.c
Logically, if you typed correctly exactly what I wrote inside hello.c file you'll get no error/warning. If this is the case, you have just created your first program.
Give on command line:
a
and check the output!

A closer look
Let's have a closer look on the small program that was just written.
Line 1: This line directs the compiler to include (hence #include) the stdio library. What is stdio.h? This is another source-code file written in C which defines some Standard Input-Output operations. Obviously, you don't have to start from scratch each and every time you write a program. You can use built-in procedures/functions that help you accomplish what you want to do. An example is the built-in printf function (line 5) which takes as an argument a series of symbols inside quotation marks (In this case the argument was "Hello World!\n"). A series of symbols is commonly referred to as a string.
Line 3: All programing languages accomplish things via functions/procedures. These are small components of source code that establish a specific job. Usually, people give intuitive names to their functions. However, main is an exception. As the name implies, it is the main function of the program and is necessary in order to build an executable with C (i.e. you can not generate an executable if you don't have a definition for main in your source code). It is the function that is called on program's startup. However, exactly after the name main you can see a left and right parenthesis and nothing in between. This means that main does not expect to take any arguments (compare with printf) when called. The operations that take place inside a function definition are always embraced between '{' and '}'. An omission on one of these will result in an error at compilation time (i.e. while you execute gcc filename.c) - you are strongly encouraged to try these so that you can realize how your compiler behaves.
Line 5: In this line we use a built-in function of the stdio library, namely printf. On the single argument that we pass to printf we imply that we want the words: "Hello World!" to be displayed on screen. The \n is an escape-character to indicate our will to start a new line. Again you are encouraged to play with this, e.g. omit the '\n' character and recompile and run your program. Note the difference. Or even add two or more '\n' at the end and check out what happens.
Further notes: Every command that is given should end with a semi-column to indicate this. As an example, if you remove the ';' at end of printf statement (aka command), the compiler will indicate you that you have a syntax error somewhere near there.
Moreover (obvious?), you can place two or more similar commands in a consecutive manner. For instance, you can have the same output, by simply replacing line 5 with the following lines:
Quote:
printf("Hel");
printf("lo ");
printf("Wo");
printf("rld!");
printf("\n");


A more detailed presentation of the printf command is going to be placed soon on a subsequent post.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
pandora
pandora


Honorable
Legendary Hero
The Chosen One
posted November 03, 2006 06:04 PM

{filler so you can keep posting }
____________
"In the end, we will remember not the words of our enemies, but the silence of our friends."

 Send Instant Message | Send E-Mail | View Profile | PP | Quote Reply | Link
Khaelo
Khaelo


Honorable
Supreme Hero
Underwater
posted November 03, 2006 09:27 PM

uh oh

The DGGBB Shell insists on naming itself "djgbb.bat.txt", it has a text document icon, and it says that it is a Text document.  The shortcut wizard informs me that "C:\DJGPP\djgpp.bat" does not exist, and I can only create a shortcut if I add the .txt ending.  "Hello" has identified itself as a C document.  How do I make the shell identify its type properly?

The operating system is WinXP, SP 2.
____________
 Cleverly
disguised as a responsible adult

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 04, 2006 12:43 AM
Edited by dimis at 01:09, 04 Nov 2006.

Quote:
The DGGBB Shell insists on naming itself "djgbb.bat.txt" ...
I guess it was my omission, sorry. In windows there is an option to hide "known file name extensions". Two simple solutions:
(1)
Start->Run
cmd
cd C:\DJGPP
ren djgpp.bat.txt djgpp.bat

(2)
Uncheck the following:
My Computer->Tools->Folder Options->View->Hide extensions for known file types.
You will now be able to view all sort of extensions that various files have on your system. Move to DJGPP folder and rename djgpp.bat.txt to djgpp.bat.
---
I believe that the above should work.

NOTE: I changed the last line of djgpp.bat file. Replace "command" with "cmd".
For some reason, if you open a command prompt with "command" instead of "cmd" and you want to close this window by simply pressing X (on the upper right-hand corner of the window) it gives you a message that it is not responding... :S Anyway, this modification will make X work (close window normally).
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
Khaelo
Khaelo


Honorable
Supreme Hero
Underwater
posted November 04, 2006 07:21 AM
Edited by Khaelo at 07:27, 04 Nov 2006.

Thanks, that was the problem.  In WinXP, the un-check option is in Control Panel/Folder Options.  I removed the .txt extension, and the file immediately converted into a "MS-DOS Batch" file.  To edit it, I put the .txt back on the filename, and it changed into a text document again.  Very nice.  

New problem!  I told the shell "gcc hello.c" and it said:
Quote:
hello.c:6:2 warning: no newline at end of file

Guessing, I added an extra "enter" at the end of the Hello file.  Now the shell gives me another prompt when told "gcc hello.c".  The screen looks like this:
Quote:
C:\DJGPP\sources> gcc hello.c

C:\DJGPP\sources>_


Underscore represents the cursor.  No more warning, but it's not doing anything else either.  Is that correct?

(Edit: spelling acronym, clarify)
____________
 Cleverly
disguised as a responsible adult

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 04, 2006 10:33 AM
Edited by dimis at 02:52, 10 Nov 2006.

Warnings and running executables

Quote:
New problem!  I told the shell "gcc hello.c" and it said:
Quote:
hello.c:6:2 warning: no newline at end of file

Guessing, I added an extra "enter" at the end of the Hello file.  Now the shell gives me another prompt when told "gcc hello.c".  The screen looks like this:
Quote:
C:\DJGPP\sources> gcc hello.c

C:\DJGPP\sources>_


Underscore represents the cursor.  No more warning, but it's not doing anything else either.  Is that correct?

Yes. This is all correct. You have just created your first program which is called a.exe and is in the same folder of your hello.c file. You can also see that there is another executable named a.out. I believe this is out of convention since the compiler gcc when not directed to give a specific name to the resulting executable, it gives the name a.out.
So what remains to be done in order to run/execute your program is to give its name on command prompt, i.e.
Quote:
Give on command line:
a
and check the output!

By the way, note also that at the first time you received only a warning, i.e. the executable was made and was ready to run.
Now delete the semicolumn at end of line 5, save and try to compile the program again (i.e. gcc hello.c). This time you won't generate files a.exe and a.out because the compiler will give you error(s) at compilation (of course, in order to observe that, you have to delete files a.exe and a.out beforehand).
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
antipaladin
antipaladin


Promising
Legendary Hero
of Ooohs and Aaahs
posted November 04, 2006 11:06 AM

can u post in pascal assistence? help me case and array!
____________
types in obscure english

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 04, 2006 01:43 PM

Hi Antipaladin,
I found a good online tutorial for Pascal: here.
Click on "table of contents" and then click "case". This will provide you with the info you want to know asap. Similarly, you can find information regarding 1-dimensional arrays and multidimensional arrays on the respective links on the table of contents (under data structures).

I would appreciate if you could delete your post on thread since I want to stay on one programming language and I've already made up my mind with C.

There are many reasons why I want this. First of all, if I start answering to random questions on thread, the whole thread will be a mess. No flow on thoughts, many languages and some people will lose interest. Don't you agree?
Besides, some people that start right now on thread don't even know the existence of even simpler things. As a result, this is what I can do for you:
After reading the tutorial instructions on the link above; if you still have questions please wait until this thread reaches the point of your questions. Now, if your queries still exist by the time these mechanisms are presented on this thread, then IM me to give you my mail so that you can send me a specific question (source code included).

I hope that I have convinced you for the policy on thread. Once you delete your post above, I will do so with this one here (don't forget to bookmark the tutorial link above).
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
antipaladin
antipaladin


Promising
Legendary Hero
of Ooohs and Aaahs
posted November 04, 2006 01:55 PM

tbenks it rules!!! i needed help becouse i'm studing it in school.and i did 1 final for it last year one while,if and for,and this year nearly started with hard things like case and 1 dimensional array..
i got a question thought..


in here
http://www.taoyue.com/tutorials/pascal/pas3cb.html

you can see that statement1 is ended with a ';' but with otherwise(else) after it why isent this an error??

____________
types in obscure english

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 04, 2006 10:57 PM

Introducing variables

Offtopic: I want to thank Pandora for the +QP on this thread. I appreciate it.

So far we can only create programs that print output on screen. However, computers are usually used to ... compute things! So, let's start extending the power of our programs.
As an example suppose we want to add two numbers (assume integers ..., -2, -1, 0, 1, 2, ...).
If we consider this as a step-by-step procedure, then we are given numbers a and b and we want to compute their sum. If we did this on a piece of paper (assume large numbers a and b that force us to write them down) then the outcome would be written on a separate place. In other words we need space to write down 3 different numbers. How can we perform something like this with a programming language? Obviously the space for each one of these 3 different numbers should be some space in RAM of your pc. In other words, we must somehow declare that we need space to store 3 different integers.
The following piece of code declares that we want space to store 3 different integers (hence the reserved word int in lines 5 and 6), which we conveniently name as a, b and result. Note that we can declare them all in one line (separated by commas), or in multiple lines. In lines 8 and 9 we assign numbers 3 and 10 in variables a and b respectively. Finally, in line 11 we compute and store in variable result the sum of numbers a and b.
Code:

Of course, this piece of code is rather problematic. The reason is that we compute the sum of numbers a and b in result variable, but we don't show this thing on screen!
Let's do it then. Add the following line after the computation performed in line 11:
Quote:
printf("The result is: %d\n", result);

Save your file again, recompile and run. Now the outcome is presented on your screen.
Let's have a closer look on the last printf statement (command). You already know the escape sequence '\n'. The new 'symbol' inside quotation marks is the '%d'. This directs printf to place there an integer. The integer that is going to appear at run-time there is the number stored in variable result (the second argument of printf).
However, if you want to perform addition between two different numbers you have to re-edit your source file, recompile and re-run. The following code uses scanf (another built-in function) to get user input.
Code:

A small note on scanf: As you can see it expects at least two arguments (exactly 2 in example above). The first one is the %d directive described in printf above, while the second argument is the memory address of the a (or b) variable. The idea is that the ampersand operator & in front of variable a extracts its address in RAM. If you can conceptually accept this we are done for now. I will soon make a post explaining in more detail various basic data types (like int) as well as a longer description for printf and scanf functions.

Till then try to generate some programs like the one presented above. For starters try to generate two programs that perform substraction and multiplication with two numbers (perhaps even more than two numbers).
Try to perform division as well. What do you notice if all variables are declared as int like in the example above?

Regards,
- dimis -

____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 07, 2006 12:40 PM
Edited by dimis at 14:06, 07 Nov 2006.

Basic Data Types

Apart from int data type, other types are provided as well. Let's have a look at them:
char : This is the smallest data type you can have. Its size is 1 byte and is used (just like its name implies) to store characters. Note that it can also be used to store small integers in the range -128...127.
double : This data type indicates that variables of this type are double precision floating point numbers.

For starters, I would recommend using only char, int and double data-types until you have some familiarity with them and operations on them.



Apart from the ones listed above, you can also have the following data types:

float : This is another floating point data-type. The difference with the double data type is that it generates variables with single (compared to double) precision. Hence, it uses half of the memory a double variable uses. On the other hand, as you might already guess, the handicap is that it has much more limited accuracy when used. I think it would be safe to say, that apart from some storage-critical applications that can work with single precision arithmetic, this type tends to extinguish. In modern world, with about 50-100KBytes of RAM / 1cent (!), it seems rather weird to use floats instead of doubles.

Unsigned Variables:
In some/most applications, you might know in advance that some variables will never be negative numbers. In these cases you might want to make full use of your space (bitwise) and use all bits so as to represent "bigger" numbers [for simplicity (for now) - but not accuracy - you can think of 1 bit being used internally so as to store the sign of each number and the rest bits for its absolute value].
unsigned : You can use this identifier before char or int data types. Practically, in these cases you can manipulate (non-negative) numbers twice as large as in the signed case. For example a variable x declared as unsigned char can take values in the range 0...255.

Short / Long Variables:
short and long are some extra identifiers commonly used with int data types. Their sizes are machine (OS/compiler) dependent. Usually, in 32-bit processors/OSs short int has size of 2 bytes while long int has size of 4 bytes (i.e. long ints are treated like ints in these situations).

I know you need an example in handling these things; this is going to be my next post.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 07, 2006 01:28 PM
Edited by dimis at 01:43, 22 Nov 2006.

sizeof() operator and extensions for printf() and scanf()

Sizes of Basic Data Types
First of all, it would be wise to check out the sizes that various basic data types have on your system. The following piece of code uses the sizeof operator (yet another built-in function), which returns the value (integer) in bytes a specific data structure (data type) requires / reserves.

Now, let's check the output on my pc. Pinpoint differences and similarities with the numbers returned by sizeof operator in your machine:




Escape sequences in printf:
The only escape sequence we have seen so far in printf is the sequence \n, which prints a new line character. Similar sequences allow us to "print" on screen various difficult-to-type or invisible characters. Let's have a look on all of them:
\n : This is the new-line character. Result should be(*) the same as \r\f.
\t : This sequence inserts a tab.
\b : This is the backspace character. Note that the default behaviour is not to delete a character!
\" : This is used to place quotation marks; otherwise you wouldn't be able to print quotation marks in a text printed on user's screen.
\a : When this sequence is used, a system alert beep will sound. This also reminds me to check connections in my pc, because I can't hear it...
\r : This is the carriage return character. It rewinds your cursor at the first position in current line.
\f : This is the form-feed character. It places your cursor on the next line.
\\ : This is used so that someone can print a backslash (\).
%% : Prints a single percent sign (see example next to the following one).
Let's see an example with all these escape-characters:

(*) I tested the above ^ source code under DJGPP, but unfortunately, I realized it has a problem with the \f sequence. If however, it behaves well on your pc, please report. Correct output and behaviour is shown above.



Extending printf:
New data types have been introduced. Let's see ways of assigning values to variables of specific type as well as ways to present output on user's screen.

Part 1
Have a look on the following sample code:

First of all, check out that we can assign values to variables at the time we declare them. Further notes:
* When directing printf to print a character with %c directive, the character is printed in ASCII format. However, if we ask to interpret this variable as an integer (in fact the prototype for %d is for long integers) we are presented number 68, which is consistent with Wikipaedia's table for ASCII printable characters (visit link)
* In order to print % sign, another escape sequence is required: %% (i.e. 2 percent signs consecutively on first argument = 1 percent sign on output).
* The %s directive indicates that in this place a string is going to be placed. Remember a string is series of printable characters and / or special symbols. In fact this is placed here as a future reference. Perhaps its discussion should be declined until we reach arrays of characters which compose strings. Until, then, you can think of it as an extension on printf.
* In a glance, the most important directives seem to be %c, %d, %u, %f, %lf
Let's have a look on the output:

Note that our single precision (float) variable s_precision already has ... precision problems.

Part 2
This part is an aid so that you can print neatly numbers (primarily) and strings. Let's see the following code:

which results in the following output:

Of course my list above regarding the use of printf is by no means complete; but most likely techniques described above will suffice for 90+% of your programs / cases.

A Closer Look:
As you can see from the above sample code, we can place numbers between the percent sign (%) and the identifier we are willing to use (e.g. d). Have a look at line 13. What is written there is number 12 which results in reserving space of 12 characters so that the number is printed in there. By default, the number is printed with right justification. If however, you want to reserve the (possibly) extra space but justify the output of the number (or string) on the left, then you can use the minus (-) sign (check out for clarity the entire example on strings). If you want to fill empty spaces with zeroes you can do so by preceding the number of spaces with the number zero (just like in lines 16, 23). If you want to force the plus sign to appear on  non-negative numbers, then you must indicate so by placing the + sign (check lines 14 and 26). As a result, you can very well use something like %+-12d (no such example above). Finally, if you prefer a blank ' ' (what's inside quotation marks) you can indicate so by leaving a blank after the % sign (check lines 15 and 27). I believe the above are intuitive explanations for starters. I will soon give a reference (on a following post in this page) which is more formal.



Extending scanf:
Extending the use of scanf is rather straightforward once someone knows how to handle various data types in printf.
For instance, let's say you want to store a floating point number to a variable named floatingVar of type long double. Then the following command can do this for you:
Quote:
scanf("%Lf", &floatingVar);
ampersand ( & ) above is in bold for emphasis.

Note that, although you don't know yet how to store a string, you can very well get single characters!
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
pandora
pandora


Honorable
Legendary Hero
The Chosen One
posted November 07, 2006 02:50 PM

filler

...
____________
"In the end, we will remember not the words of our enemies, but the silence of our friends."

 Send Instant Message | Send E-Mail | View Profile | PP | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 11, 2006 02:12 AM
Edited by dimis at 02:26, 11 Nov 2006.

COMPILER HOWTO: Name Executables, Show All Warnings.

Naming Executable
So far we generate executables and each one is named as a.exe. Obviously, if you want to have fun with all your executables at once (i.e. without the need to recompile them or rename them after compilation) you can pass as parameter to the compiler the desired name for your executable. For example, let's go back to our first program, hello.c. Open DJGPP Shell and give:
Quote:
gcc hello.c -o hello
dir
You can pinpoint now that files hello and hello.exe have been created just like we wanted!
NOTE: It doesn't matter which argument is -o as well as the executable_name as long as you place them together, i.e. the following command will have the same effect:
Quote:
gcc -o hello hello.c



Enable All Warnings
However, all programs that we have created so far are not strictly complete. We can implicitly ask from the compiler to present all warnings for our program with the -Wall command line argument. For example, let's try to recompile hello.c but this time enable all warnings:
Quote:
gcc -Wall hello.c -o hello
During compilation we are presented with the following:
Quote:
hello.c:4: warning: return type defaults to `int'
hello.c: In function `main':
hello.c:6: warning: control reaches end of non-void function

These warnings give me a good starting point for my next post. But before we reach that point let's fix the program. Transform your hello.c file into the following:

and recompile with the -Wall option. Compiler is mute again!
You can also play with the source code in Part 1 of extend printf section above. Try for instance to change the %lf directive inside printf (@line 23) to %f and recompile with all warnings enabled (of course add int in front of main @line 3 and add a final line with return 0;). This is going to make it easier for you (I hope!) to realize when we really need to place the modifiers h, l and L in front of the type identifiers d and f (inside printf and scanf); as well as a direct comparison of the warnings with the output of the sizes program (the only one that uses sizeof so far). If not, just ignore this last comment for now.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 20, 2006 12:03 AM

Valid Source Code - DJGPP History

A brief history of C.
Most successful compilers were released based on book The C Programming Language by Dennis Ritchie and Brian Kernighan which was published in 1978. However, definitions given on the book are pretty loose with the further consequence that each individual who built a compiler for C could end up treat same subjects in a different manner compared to another individual who built a compiler for C. So, in order to set the limits and strictly define the language, in 1983, the American National Standards Institute (ANSI) set up a committee to make accurate definitions for C. This was the birth of ANSI C. ANSI C is also known as C89 or even ISO C. In fact, when I started this thread, I thought this was the standard up to now. But, some research I did on the internet clearly showed me I had wrong impressions. ANSI committee had another meeting in 1999, and the revised standard of the language is (if I am correct this time) C99.
There are also some other dialects in C. Most notable are gnu89 and gnu99.


DJGPP history.
For a brief history on the compiler you are working on, check out here.



Forgive me for not giving references for further reading yet. I just want to build a solid conceptual base within my next few posts. Once I am done with that, I can give you references and most likely we'll speed up the evolution of this thread.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
Khaelo
Khaelo


Honorable
Supreme Hero
Underwater
posted November 21, 2006 10:50 PM

filler

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 22, 2006 02:06 AM

Commenting Source Code

Nearly always you are going to find some need to place some comments in your source code. Comments, are simple things you write in your source code, that most of the time help you remember what your commands are doing in the near-by area and/or general ideas on how you've done things work. Some other times, they might help you document your source code in a more general fashion.
An ANSI comment starts when placing together characters '/' and '*' and ends when it finds them in opposite direction, i.e. '*' followed by '/'. Sometimes people want to create multiple line comments and ... tend to draw with them on their source code.

An overuse of comments is shown in the following example:


Note that you can start a one-line comment by simply writing '//'. What ever follows, until the end of the line is treated as a comment. For instance, you can replace line 17 above with:
Quote:
// Print something on user's screen.

____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
dimis
dimis


Responsible
Supreme Hero
Digitally signed by FoG
posted November 22, 2006 02:39 AM

Complete Reference for printf() and scanf() functions ...

Ok, I owe you some online references for the things we 've seen so far, mainly for printf() and scanf().

printf()
A complete/formal list (along with explanations) on the identifiers used in printf can be found here. However (to my surprise), nothing is written about escape (control) sequences. For this reason you can have a look here.

scanf()
Similarly, you can find more info about scanf() here.

I believe definitions given on the above links, can help explain my comment (final paragraph) 3 posts earlier.
____________
The empty set

 Send Instant Message | Send E-Mail | View Profile | Quote Reply | Link
Jump To: « Prev Thread . . . Next Thread » This thread is 2 pages long: 1 2 · NEXT»
Post New Poll    Post New Topic    Post New Reply

Page compiled in 0.1786 seconds