Sams Teach Yourself C# in 21 Days Reviews


Teach Yourself C in 21 Days

Previous chapter Next chapter Contents


- i -

Getting Started with C

  • A Brief History of the C Language
  • Why Use C?
  • Preparing to Program
  • The Program Development Wheel
    • Creating the Source Lawmaking
    • Compiling the Source Code
    • Linking to Create an Executable File
    • Completing the Development Wheel
  • Your Commencement C Plan
    • Inbound and Compiling Hullo.C
  • Summary
  • Q&A
  • Workshop
    • Quiz
    • Exercises

Welcome to Sams' Teach Yourself C in 21 Days! This affiliate starts you toward becoming a proficient C programmer. Today you volition learn

  • Why C is the best choice among programming languages
  • The steps in the program evolution cycle
  • How to write, compile, and run your first C programme
  • Almost error messages generated by the compiler and linker

A Brief History of the C Language

Yous might exist wondering about the origin of the C linguistic communication and where it got its name. C was created by Dennis Ritchie at the Bell Telephone Laboratories in 1972. The language wasn't created for the fun of it, but for a specific purpose: to design the UNIX operating system (which is used on many computers). From the beginning, C was intended to exist useful--to allow busy programmers to become things done.

Because C is such a powerful and flexible linguistic communication, its use speedily spread across Bell Labs. Programmers everywhere began using it to write all sorts of programs. Soon, however, different organizations began utilizing their own versions of C, and subtle differences between implementations started to crusade programmers headaches. In response to this problem, the American National Standards Institute (ANSI) formed a committee in 1983 to establish a standard definition of C, which became known as ANSI Standard C. With few exceptions, every modern C compiler has the ability to attach to this standard.

Now, what about the proper noun? The C language is so named because its predecessor was called B. The B language was developed by Ken Thompson of Bell Labs. Y'all should exist able to judge why it was chosen B.

Why Use C?

In today's globe of calculator programming, there are many high-level languages to cull from, such equally C, Pascal, BASIC, and Coffee. These are all excellent languages suited for most programming tasks. Fifty-fifty so, there are several reasons why many computer professionals feel that C is at the elevation of the list:

  • C is a powerful and flexible language. What you tin can accomplish with C is limited but by your imagination. The linguistic communication itself places no constraints on you lot. C is used for projects as diverse as operating systems, give-and-take processors, graphics, spreadsheets, and even compilers for other languages.
  • C is a popular linguistic communication preferred by professional person programmers. As a result, a broad variety of C compilers and helpful accessories are available.
  • C is a portable language. Portable ways that a C plan written for i figurer system (an IBM PC, for example) tin be compiled and run on another arrangement (a DEC VAX arrangement, perchance) with little or no modification. Portability is enhanced by the ANSI standard for C, the gear up of rules for C compilers.
  • C is a language of few words, containing only a handful of terms, chosen keywords, which serve as the base on which the language's functionality is built. You might think that a language with more than keywords (sometimes chosen reserved words) would be more powerful. This isn't true. Every bit you program with C, you will find that it tin be programmed to do whatever task.
  • C is modular. C code tin can (and should) be written in routines chosen functions. These functions tin be reused in other applications or programs. By passing pieces of information to the functions, you can create useful, reusable code.

As these features show, C is an excellent selection for your first programming language. What about C++? You might take heard about C++ and the programming technique called object-oriented programming. Peradventure you're wondering what the differences are between C and C++ and whether you should be education yourself C++ instead of C.

Non to worry! C++ is a superset of C, which means that C++ contains everything C does, plus new additions for object-oriented programming. If you do go on to learn C++, well-nigh everything you learn near C volition all the same apply to the C++ superset. In learning C, you are not only learning one of today'southward about powerful and pop programming languages, but y'all are also preparing yourself for object-oriented programming.

Another language that has gotten lots of attending is Java. Java, like C++, is based on C. If later you lot decide to learn Java, you will find that almost everything yous learned about C tin can be practical.

Preparing to Program

You should take certain steps when yous're solving a problem. First, you must define the problem. If you don't know what the problem is, you can't find a solution! Once you know what the problem is, yous can devise a plan to prepare it. Once you have a plan, you tin can ordinarily implement it. Once the plan is implemented, you lot must exam the results to see whether the problem is solved. This aforementioned logic can exist practical to many other areas, including programming.

When creating a program in C (or for that affair, a computer plan in any language), you should follow a similar sequence of steps:

1. Make up one's mind the objective(s) of the programme.
2. Make up one's mind the methods yous want to employ in writing the program.
3. Create the programme to solve the problem.
iv. Run the plan to see the results.

An example of an objective (encounter step 1) might exist to write a give-and-take processor or database program. A much simpler objective is to display your name on the screen. If you lot didn't have an objective, you wouldn't be writing a program, so you already accept the outset stride done.

The second step is to determine the method you want to use to write the programme. Do yous demand a reckoner program to solve the trouble? What information needs to be tracked? What formulas volition be used? During this step, you should try to determine what y'all need to know and in what lodge the solution should be implemented.

As an example, assume that someone asks you to write a plan to make up one's mind the area inside a circle. Step i is consummate, because you know your objective: determine the area within a circumvolve. Footstep 2 is to determine what you need to know to ascertain the expanse. In this example, assume that the user of the program will provide the radius of the circle. Knowing this, you tin can apply the formula prtwo to obtain the answer. Now you take the pieces you need, and then you lot tin can keep to steps three and 4, which are chosen the Program Development Cycle.

The Program Development Cycle

The Program Development Cycle has its own steps. In the first step, you apply an editor to create a disk file containing your source code. In the second step, yous compile the source code to create an object file. In the third step, you lot link the compiled code to create an executable file. The fourth step is to run the program to run across whether it works as originally planned.

Creating the Source Lawmaking

Source code is a series of statements or commands that are used to instruct the reckoner to perform your desired tasks. As mentioned, the first step in the Program Development Cycle is to enter source lawmaking into an editor. For example, hither is a line of C source code:

printf("Hi, Mom!");      

This argument instructs the computer to display the bulletin Hello, Mom! on-screen. (For now, don't worry about how this statement works.)

Using an Editor

Most compilers come with a born editor that tin be used to enter source code; still, some don't. Consult your compiler manuals to run into whether your compiler came with an editor. If it didn't, many alternative editors are available.

Most computer systems include a program that tin be used every bit an editor. If you're using a UNIX arrangement, you tin use such editors every bit ed, ex, edit, emacs, or vi. If you're using Microsoft Windows, Notepad is available. If you're using MS/DOS 5.0 or afterwards, yous tin can utilise Edit. If you're using a version of DOS before 5.0, you can utilize Edlin. If you're using PC/DOS six.0 or later, you tin employ E. If you lot're using OS/two, you tin employ the E and EPM editors.

Well-nigh word processors use special codes to format their documents. These codes can't be read correctly by other programs. The American Standard Code for Information Interchange (ASCII) has specified a standard text format that most any program, including C, can use. Many word processors, such as WordPerfect, AmiPro, Discussion, WordPad, and WordStar, are capable of saving source files in ASCII form (as a text file rather than a document file). When you want to save a word processor'south file equally an ASCII file, select the ASCII or text pick when saving.

If none of these editors is what yous want to apply, you can ever purchase a different editor. There are packages, both commercial and shareware, that accept been designed specifically for entering source lawmaking.


Annotation: To notice alternative editors, you tin can check your local computer store or reckoner postal service-order catalogs. Another place to await is in the ads in calculator programming magazines.

When you save a source file, y'all must give information technology a proper noun. The proper name should describe what the program does. In addition, when you save C programme source files, requite the file a .C extension. Although you lot could requite your source file any name and extension, .C is recognized as the advisable extension to utilise.

Compiling the Source Code

Although you lot might exist able to understand C source code (at least, after reading this book you will exist able to), your computer can't. A computer requires digital, or binary, instructions in what is called car language. Before your C plan tin run on a computer, it must be translated from source code to machine language. This translation, the 2nd step in program evolution, is performed by a program called a compiler. The compiler takes your source code file as input and produces a deejay file containing the motorcar language instructions that correspond to your source code statements. The machine language instructions created past the compiler are called object lawmaking, and the disk file containing them is called an object file.


NOTE: This volume covers ANSI Standard C. This means that it doesn't matter which C compiler you use, every bit long every bit information technology follows the ANSI Standard.

Each compiler needs its own control to exist used to create the object lawmaking. To compile, you typically use the command to run the compiler followed by the source filename. The post-obit are examples of the commands issued to compile a source file called RADIUS.C using various DOS/Windows compilers:

Compiler Command
Microsoft C cl radius.c
Borland'south Turbo C tcc radius.c
Borland C bcc radius.c
Zortec C ztc radius.c

To compile RADIUS.C on a UNIX machine, use the following command:

cc radius.c      

Consult the compiler manual to determine the exact command for your compiler.

If you're using a graphical development environment, compiling is even simpler. In virtually graphical environments, you tin can compile a plan list by selecting the compile icon or selecting something from a menu. Once the code is compiled, selecting the run icon or selecting something from a bill of fare volition execute the plan. You should cheque your compiler's manuals for specifics on compiling and running a program.

Later you lot compile, you accept an object file. If you await at a list of the files in the directory or folder in which you compiled, yous should find a file that has the same name equally your source file, simply with an .OBJ (rather than a .C) extension. The .OBJ extension is recognized as an object file and is used by the linker. On UNIX systems, the compiler creates object files with an extension of .O instead of .OBJ.

Linking to Create an Executable File

One more pace is required before y'all can run your programme. Function of the C linguistic communication is a function library that contains object code (code that has already been compiled) for predefined functions. A predefined function contains C code that has already been written and is supplied in a ready-to-employ grade with your compiler parcel.

The printf() function used in the previous example is a library function. These library functions perform frequently needed tasks, such as displaying information on-screen and reading data from disk files. If your program uses any of these functions (and hardly a programme exists that doesn't use at least i), the object file produced when your source lawmaking was compiled must be combined with object lawmaking from the function library to create the final executable plan. (Executable means that the programme can exist run, or executed, on your computer.) This process is called linking, and it's performed by a program called (you guessed it) a linker.

Figure 1.i shows the progression from source code to object lawmaking to executable program.

Figure 1.ane. The C source code that yous write is converted to object code by the compiler so to an executable file past the linker.

Completing the Development Cycle

Once your program is compiled and linked to create an executable file, yous tin can run it by entering its name at the system prompt or just similar you would run any other program. If you lot run the programme and receive results different from what you thought you would, you need to go back to the first step. Yous must place what caused the problem and correct it in the source lawmaking. When yous make a change to the source lawmaking, you demand to recompile and relink the program to create a corrected version of the executable file. You go on following this cycle until you get the program to execute exactly as yous intended.

One final note on compiling and linking: Although compiling and linking are mentioned every bit two carve up steps, many compilers, such as the DOS compilers mentioned before, exercise both as one step. Regardless of the method past which compiling and linking are accomplished, understand that these two processes, even when done with one command, are two separate deportment.

The C Development Bike

Footstep ane Use an editor to write your source code. By tradition, C source code files have the extension .C (for example, MYPROG.C, DATABASE.C, and and then on).
Step 2 Compile the program using a compiler. If the compiler doesn't find any errors in the program, it produces an object file. The compiler produces object files with an .OBJ extension and the same proper name equally the source code file (for example, MYPROG.C compiles to MYPROG.OBJ). If the compiler finds errors, it reports them. Y'all must return to step i to make corrections in your source code.
Step three Link the program using a linker. If no errors occur, the linker produces an executable program located in a deejay file with an .EXE extension and the same name every bit the object file (for example, MYPROG.OBJ is linked to create MYPROG.EXE).
Footstep four Execute the program. You should test to decide whether it functions properly. If not, start over again with step one and make modifications and additions to your source code.

Figure 1.2 shows the program development steps. For all but the simplest programs, you might go through this sequence many times earlier finishing your program. Even the most experienced programmers can't sit and write a complete, error-gratuitous program in just one step! Considering y'all'll be running through the edit-compile-link-test bike many times, it's important to go familiar with your tools: the editor, compiler, and linker.

Figure 1.ii. The steps involved in C program development.

Your Showtime C Programme

You're probably eager to endeavor your commencement plan in C. To help you get familiar with your compiler, hither's a quick program for you to work through. You lot might not understand everything at this betoken, but you should get a experience for the process of writing, compiling, and running a real C programme.

This demonstration uses a program named HELLO.C, which does zero more than display the words Hello, World! on-screen. This program, a traditional introduction to C programming, is a skilful one for you to learn. The source code for HELLO.C is in Listing 1.one. When you blazon in this listing, you lot won't include the line numbers or colons.

Listing i.1. Hello.C.

ane: #include <stdio.h> two: iii: principal() iv: { v:     printf("Hello, World!\northward"); 6:     return 0; 7: }      

Exist sure that y'all have installed your compiler equally specified in the installation instructions provided with the software. Whether you are working with UNIX, DOS, or any other operating organization, make sure you lot empathize how to use the compiler and editor of your selection. Once your compiler and editor are set up, follow these steps to enter, compile, and execute HELLO.C.

Entering and Compiling HELLO.C

To enter and compile the HELLO.C programme, follow these steps:

1. Make active the directory your C programs are in and first your editor. As mentioned previously, any text editor can be used, merely well-nigh C compilers (such as Borland's Turbo C++ and Microsoft's Visual C/C++) come with an integrated development environment (IDE) that lets y'all enter, compile, and link your programs in i convenient setting. Bank check the manuals to run across whether your compiler has an IDE bachelor.
2. Use the keyboard to type the HELLO.C source code exactly every bit shown in List one.one. Press Enter at the end of each line.

Note: Don't enter the line numbers or colons. These are for reference only.
3. Salve the source code. Yous should proper noun the file Hi.C.
iv. Verify that HELLO.C is on disk by listing the files in the directory or folder. You should see Hullo.C within this listing.
v. Compile and link How-do-you-do.C. Execute the appropriate command specified past your compiler'south manuals. Y'all should become a message stating that there were no errors or warnings.
half dozen. Check the compiler messages. If you receive no errors or warnings, everything should be okay.
If you made an fault typing the program, the compiler will catch it and display an error bulletin. For example, if you lot misspelled the word printf equally prntf, you would run across a message similar to the following:
Error: undefined symbols:_prntf in hullo.c (hi.OBJ)
      
7. Go back to footstep ii if this or any other fault message is displayed. Open up the Howdy.C file in your editor. Compare your file's contents carefully with Listing 1.ane, brand whatsoever necessary corrections, and continue with step 3.
8. Your start C program should at present exist compiled and gear up to run. If you brandish a directory listing of all files named HELLO (with any extension), you should run across the post-obit:
Hello.C, the source code file you created with your editor
HELLO.OBJ or HELLO.O, which contains the object code for HELLO.C
HELLO.EXE, the executable program created when you compiled and linked Hullo.C
9. To execute, or run, How-do-you-do.EXE, simply enter how-do-you-do. The bulletin How-do-you-do, World! is displayed on-screen.

Congratulations! You accept just entered, compiled, and run your first C program. Admittedly, HELLO.C is a uncomplicated program that doesn't do anything useful, only it's a start. In fact, most of today's good C programmers started learning C in this same fashion--by compiling Hello.C--so you're in skilful company.

Compilation Errors

A compilation error occurs when the compiler finds something in the source lawmaking that it can't compile. A misspelling, typographical error, or any of a dozen other things can crusade the compiler to choke. Fortunately, modernistic compilers don't just choke; they tell you what they're choking on and where it is! This makes it easier to detect and correct errors in your source lawmaking.

This point tin be illustrated by introducing a deliberate error into HELLO.C. If you worked through that example (and you should have), you at present have a copy of How-do-you-do.C on your disk. Using your editor, move the cursor to the end of the line containing the phone call to printf(), and erase the terminating semicolon. Howdy.C should now expect like List one.2.

Listing 1.2. HELLO.C with an error.

1: #include <stdio.h> 2: iii: main() 4: { 5:     printf("Hullo, World!") 6:     return 0; 7: }      

Next, salvage the file. You're now ready to compile information technology. Practice so by entering the control for your compiler. Because of the fault you introduced, the compilation is non completed. Rather, the compiler displays a message similar to the post-obit:

hello.c(6) : Error: `;' expected      

Looking at this line, you can see that it has three parts:

how-do-you-do.c The name of the file where the error was found

(six) : The line number where the fault was plant

Error: `;' expected A description of the error

This message is quite informative, telling you that in line 6 of HELLO.C the compiler expected to find a semicolon only didn't. However, you know that the semicolon was actually omitted from line five, so there is a discrepancy. Y'all're faced with the puzzle of why the compiler reports an error in line 6 when, in fact, a semicolon was omitted from line 5. The respond lies in the fact that C doesn't intendance about things similar breaks betwixt lines. The semicolon that belongs after the printf() statement could accept been placed on the side by side line (although doing and so would be bad programming practice). Simply after encountering the adjacent command (return) in line 6 is the compiler certain that the semicolon is missing. Therefore, the compiler reports that the error is in line half dozen.

This points out an undeniable fact about C compilers and error messages. Although the compiler is very clever about detecting and localizing errors, it's no Einstein. Using your knowledge of the C linguistic communication, you must translate the compiler's messages and determine the bodily location of any errors that are reported. They are often found on the line reported by the compiler, but if not, they are near always on the preceding line. Y'all might accept a bit of trouble finding errors at commencement, but you should soon go better at information technology.


Annotation: The errors reported might differ depending on the compiler. In most cases, the fault bulletin should give you an idea of what or where the problem is.

Before leaving this topic, allow's look at another example of a compilation fault. Load HELLO.C into your editor again and make the following changes:

1. Supervene upon the semicolon at the end of line 5.
2. Delete the double quotation mark just before the give-and-take How-do-you-do.

Save the file to deejay and compile the plan once more. This time, the compiler should brandish error letters similar to the post-obit:

hullo.c(5) : Error: undefined identifier `Hello' hi.c(7) : Lexical mistake: unterminated string Lexical fault: unterminated cord Lexical error: unterminated string Fatal error: premature stop of source file      

The beginning error bulletin finds the mistake correctly, locating it in line five at the word How-do-you-do. The error message undefined identifier means that the compiler doesn't know what to make of the word Hello, because information technology is no longer enclosed in quotes. However, what nearly the other 4 errors that are reported? These errors, the meaning of which you don't need to worry about now, illustrate the fact that a single error in a C plan can sometimes cause multiple error messages.

The lesson to learn from all this is every bit follows: If the compiler reports multiple errors, and you tin find only one, get ahead and fix that error and recompile. You might find that your single correction is all that'due south needed, and the plan will compile without errors.

Linker Fault Messages

Linker errors are relatively rare and commonly event from misspelling the proper name of a C library function. In this case, you get an Error: undefined symbols: fault bulletin, followed past the misspelled name (preceded by an underscore). One time you correct the spelling, the trouble should get away.

Summary

After reading this chapter, you should experience confident that selecting C as your programming language is a wise choice. C offers an unparalleled combination of power, popularity, and portability. These factors, together with C's shut human relationship to the C++ object-oriented language as well equally Java, make C unbeatable.

This chapter explained the diverse steps involved in writing a C program--the procedure known equally program development. You should have a articulate grasp of the edit-compile-link-exam cycle, as well as the tools to apply for each step.

Errors are an unavoidable part of program evolution. Your C compiler detects errors in your source code and displays an error message, giving both the nature and the location of the mistake. Using this information, you tin edit your source lawmaking to correct the error. Call up, nevertheless, that the compiler tin't always accurately report the nature and location of an mistake. Sometimes you demand to utilise your knowledge of C to track down exactly what is causing a given error message.

Q&A

Q If I want to give someone a plan I wrote, which files practice I demand to give him?
A I of the nice things nigh C is that it is a compiled language. This means that after the source lawmaking is compiled, you have an executable programme. This executable program is a stand-solitary plan. If you lot wanted to give Hi to all your friends with computers, you could. All you demand to requite them is the executable plan, Hi.EXE. They don't need the source file, HELLO.C, or the object file, Howdy.OBJ. They don't need to ain a C compiler, either.
Q After I create an executable file, do I need to keep the source file (.C) or object file (.OBJ)?
A If yous get rid of the source file, you accept no way to make changes to the program in the future, then you should keep this file. The object files are a unlike matter. There are reasons to continue object files, simply they are across the scope of what you're doing at present. For at present, y'all can get rid of your object files once yous take your executable file. If you need the object file, y'all can recompile the source file.
Near integrated evolution environments create files in addition to the source file (.C), the object file (.OBJ or .O), and the executable file. As long equally you lot keep the source file (.C), you can ever recreate the other files.
Q If my compiler came with an editor, practice I have to use information technology?
A Definitely not. You can apply any editor, equally long as it saves the source code in text format. If the compiler came with an editor, yous should endeavour to employ it. If you lot like a different editor better, use it. I use an editor that I purchased separately, even though all my compilers have their own editors. The editors that come with compilers are getting meliorate. Some of them automatically format your C lawmaking. Others colour-code different parts of your source file to make it easier to find errors.
Q Can I ignore alarm messages?
A Some warning messages don't touch how the programme runs, and some do. If the compiler gives you a alert message, information technology's a signal that something isn't right. About compilers let you set the warning level. By setting the warning level, you can go just the nearly serious warnings, or you tin get all the warnings, including the most infinitesimal. Some compilers fifty-fifty offering various levels in-betwixt. In your programs, you should look at each warning and make a conclusion. It's always best to try to write all your programs with absolutely no warnings or errors. (With an error, your compiler won't create the executable file.)

Workshop

The Workshop provides quiz questions to help you lot solidify your understanding of the fabric covered and exercises to provide you with experience in using what yous've learned. Endeavor to understand the quiz and exercise answers before standing to the next chapter. Answers are provided in Appendix G, "Answers."

Quiz

1. Give iii reasons why C is the best choice of programming linguistic communication.
ii. What does the compiler do?
three. What are the steps in the program development wheel?
4. What command do y'all demand to enter in order to compile a program called PROGRAM1.C with your compiler?
v. Does your compiler do both the linking and compiling with just one command, or exercise you lot accept to enter separate commands?
half-dozen. What extension should you lot use for your C source files?
vii. Is FILENAME.TXT a valid name for a C source file?
eight. If y'all execute a program that y'all have compiled and it doesn't piece of work equally you expected, what should yous do?
9. What is motorcar language?
10. What does the linker do?

Exercises

i. Use your text editor to look at the object file created by Listing ane.1. Does the object file look like the source file? (Don't salvage this file when you leave the editor.)
two. Enter the following program and compile it. What does this plan do? (Don't include the line numbers or colons.)
1: #include <stdio.h> 2: 3: int radius, area; four: 5: main() vi: { 7:     printf( "Enter radius (i.e. x): " ); eight:     scanf( "%d", &radius ); nine:     area = (int) (3.14159 * radius * radius); 10:    printf( "\due north\nArea = %d\n", expanse ); 11:    return 0; 12: }
      
3. Enter and compile the post-obit plan. What does this programme exercise?
1: #include <stdio.h> 2: three: int ten,y; 4: 5: main() half-dozen: { 7:     for ( x = 0; x < 10; 10++, printf( "\n" ) ) 8:         for ( y = 0; y < 10; y++ ) 9:             printf( "X" ); 10: 11:    return 0; 12: }
      
iv. BUG BUSTER: The following plan has a trouble. Enter it in your editor and compile it. Which lines generate error messages?
1: #include <stdio.h> ii: 3: main(); iv: { v:     printf( "Keep looking!" ); half dozen:     printf( "Yous\'ll find it!\north" ); vii:     render 0; viii: }
      
5. BUG BUSTER: The following program has a problem. Enter it in your editor and compile it. Which lines generate problems?
one: #include <stdio.h> 2: 3: master() iv: { 5:     printf( "This is a plan with a " ); vi:     do_it( "problem!"); seven:     return 0; 8: }
      
6. Make the following change to the program in do 3. Recompile and rerun this program. What does the program practice now?
9: printf( "%c", 1 );

Previous chapter Next chapter Contents

© Copyright, Macmillan Reckoner Publishing. All rights reserved.

yancymeleat.blogspot.com

Source: http://www.ossh.com/c/ch01/ch01.htm

0 Response to "Sams Teach Yourself C# in 21 Days Reviews"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel