X
تبلیغات
بانک مقالات علمی

بانک مقالات علمی

آموزش زبان c قسمت 5:

The C programming language uses the "=" character for assignment. A statement of the form a=10; should be interpreted as take the numerical value 10 and store it in a memory location associated with the integer variable a. The "=" character should not be seen as an equality otherwise writing statements of the form:

a=a+10;

will get mathematicians blowing fuses! This statement should be interpreted as take the current value stored in a memory location associated with the integer variable a; add the numerical value 10 to it and then replace this value in the memory location associated with a.


Decimal Number Variables

As described above, an integer variable has no fractional part. Integer variables tend to be used for counting, whereas real numbers are used in arithmetic. C uses one of two keywords to declare a variable that is to be associated with a decimal number: float and double. They are each offer a different level of precision as outlined below.

float

A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store.

double

A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store.

For example:

float total;

double sum;

To assign a numerical value to our floating point and double precision variables we would use the following C statement:

total=0.0;

sum=12.50;


Character Variables

C only has a concept of numbers and characters. It very often comes as a surprise to some programmers who learnt a beginner's language such as BASIC that C has no understanding of strings but a string is only an array of characters and C does have a concept of arrays which we shall be meeting later in this course.

To declare a variable of type character we use the keyword char. - A single character stored in one byte.

For example:

char c;

To assign, or store, a character value in a char data type is easy - a character variable is just a symbol enclosed by single quotes. For example, if c is a char variable you can store the letter A in it using the following C statement:

c='A'

Notice that you can only store a single character in a char variable. Later we will be discussing using character strings, which has a very real potential for confusion because a string constant is written between double quotes. But for the moment remember that a char variable is 'A' and not "A".


Assignment Statement

Once you've declared a variable you can use it, but not until it has been declared - attempts to use a variable that has not been defined will cause a compiler error. Using a variable means storing something in it. You can store a value in a variable using:

name = value;

For example:

a=10;

stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actually very useful! Who wants to store a known value like 10 in a variable so you can use it later? It is 10, always was 10 and always will be 10. What makes variables useful is that you can use them to store the result of some arithmetic.

Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C would use these operations on two float variables a and b.

add

a+b

subtract

a-b

multiply

a*b

divide

a/b

Note that we have used the following characters from C's character set:

+     for add

-     for subtract

*     for multiply

/     for divide

BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?

a=10/3

The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader to find out the answer for a of type char.

Two points to note from the above calculation:

  1. C ignores fractions when doing integer division!
  2. when doing float calculations integers will be converted into float. We will see later how C handles type conversions.

Arithmetic Ordering

Whilst we are dealing with arithmetic we want to remind you about something that everyone learns at junior school but then we forget it. Consider the following calculation:

a=10.0 + 2.0 * 5.0 - 6.0 / 2.0

What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that answer by following each instruction as if it was being typed into a calculator. A computer doesn't work like that and it has its own set of rules when performing an arithmetic calculation. All mathematical operations form a hierarchy which is shown here. In the above calculation the multiplication and division parts will be evaluated first and then the addition and subtraction parts. This gives an answer of 17.

Note: To avoid confusion use brackets. The following are two different calculations:

a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

You can freely mix int, float and double variables in expressions. In nearly all cases the lower precision values are converted to the highest precision values used in the expression. For example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int to a float and then multiplying. The final result is, of course, a float but this may be assigned to another data type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not rounded. In other words, in nearly all cases you can ignore the problems of converting between types.

This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints, floats and doubles. This will shock any programmer who has used another language, as it's another example of C getting us closer than is customary to the way the machine works. A character is represented as an ASCII or some other code in the range O to 255, and if you want you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte integer variable that can hold a number in the range O to 255, which can optionally be interpreted as a character. Notice, however, that C gives you access to memory in the smallest chunks your machine works with, i.e. one byte at a time, with no overheads.


Something To Declare

Before you can use a variable you have to declare it. As we have seen above, to do this you state its type and then give its name. For example, int i; declares

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:40 قبل از ظهر  توسط کامران  | 

آموزش زبان ز قسمت 6:

an integer variable. You can declare any number of variables of the same type with a single statement. For example:

int a, b, c;

declares three integers: a, b and c. You have to declare all the variables that you want to use at the start of the program. Later you will discover that exactly where you declare a variable makes a difference, but for now you should put variable declarations after the opening curly bracket of the main program.

Here is an example program that includes some of the concepts outlined above. It includes a slightly more advanced use of the printf function which will covered in detail in the next part of this course:

/*

/*

    Program#int.c

 

    Another simple program

    using int and printf

*/

 

#include

 

main()

{

    int a,b,average;

    a=10;

    b=6;

    average = ( a+b ) / 2 ;

    printf("Here ");

    printf("is ");

    printf("the ");

    printf("answer... ");

    printf("\n");

    printf("%d.",average);

}

[program]


More On Initialising Variables

You can assign an initial value to a variable when you declare it. For example:

int i=1;

sets the int variable to one as soon as it's created. This is just the same as:

int i;

i=l;

 

but the compiler may be able to speed up the operation if you initialise the variable as part of its declaration. Don't assume that an uninitialised variable has a sensible value stored in it. Some C compilers store 0 in newly created numeric variables but nothing in the C language compels them to do so.


Summary

Variable names:

  • should be lowercase for local variables
  • should be UPPERCASE for symbolic constants (to be discussed later)
  • only the first 31 characters of a variables name are significant
  • must begin with a letter or _ (under score) character

 


 

 

Input and Output Functions


Objectives

Having read this section you should have a clearer idea of one of C's:

  1. input functions, called scanf
  2. output functions, called printf

On The Run

Even with arithmetic you can't do very much other than write programs that are the equivalent of a pocket calculator. The real break through comes when you can read values into variables as the program runs. Notice the important words here: "as the program runs". You can already store values in variables using assignment. That is:

a=100;

stores 100 in the variable a each time you run the program, no matter what you do. Without some sort of input command every program would produce exactly the same result every time it was run. This would certainly make debugging easy! But in practice, of course, we need programs to do different jobs each time they are run. There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you would use:

scanf("%d",&a);

For the moment don't worry about what the %d or the &a means - concentrate on the difference between this and:

a=100;

When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press , or , to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result!

The final missing piece in the jigsaw is using the printf function, the one we have already used to print "Hello World", to print the value currently being stored in a variable. To display the value stored in the variable a you would use:

printf("The value stored in a is %d",a);

The %d, both in the case of scanf and printf, simply lets the compiler know that the value being read in, or printed out, is a decimal integer - that is, a few digits but no decimal point.

Note: the scanf function does not prompt for an input. You should get in the habit of always using a printf function, informing the user of the program what they should type, before a scanf function.


Input and Output Functions in More Detail

One of the advantages of C is that essentially it is a small language. This means that you can write a complete description of the language in a few pages. It doesn't have many keywords or data types for that matter. What makes C so powerful is the way that these low-level facilities can be put together to make higher level facilities.

The only problem with this is that C programmers have a tendency to reinvent the wheel each time they want to go for a ride. It is also possible to write C programs in a variety of styles which depend on the particular tricks and devices that a programmer chooses to use. Even after writing C for a long time you will still find the occasionally construction which makes you think, "I never thought of that!" or, "what is that doing?"

One attempt to make C a more uniform language is the provision of standard libraries of functions that perform common tasks. We say standard but until the ANSI committee actually produced a standard there was, and still is, some variation in what the standard libraries contained and exactly how the functions worked. Having said that we had better rush in quickly with the reassurance that in practice the situation isn't that bad and most of the functions that are used

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آوزش زبان c قسمت 7:

frequently really are standard on all implementations. In particular the I/O functions vary very little.

It is now time to look at exactly how scanf and printf work and what they can do - you might be surprised at just how complex they really are!

The original C specification did not include commands for input and output. Instead the compiler writers were supposed to implement library functions to suit their machines. In practice all chose to implement printf and scanf and after a while C programmers started to think of them as if these functions were I/O keywords! It sometimes helps to remember that they are functions on a par with any other functions you may care to define. If you want to you can provide your own implementations of printf or scanf or any of the other standard functions - we'll discover how later.


printf

The printf (and scanf) functions do differ from the sort of functions that you will created for yourself in that they can take a variable number of parameters. In the case of printf the first parameter is always a string (c.f. "Hello World") but after that you can include as many parameters of any type that you want to. That is, the printf function is usually of the form:

printf(string,variable,variable,variable...)

where the ... means you can carry on writing a list of variables separated by commas as long as you want to. The string is all-important because it specifies the type of each variable in the list and how you want it printed. The string is usually called the control string or the format string. The way that this works is that printf scans the string from left to right and prints on the screen, or any suitable output device, any characters it encounters - except when it reaches a % character. The % character is a signal that what follows it is a specification for how the next variable in the list of variables should be printed. printf uses this information to convert and format the value that was passed to the function by the variable and then moves on to process the rest of the control string and anymore variables it might specify. For example:

printf("Hello World");

only has a control string and, as this contains no % characters it results in Hello World being displayed and doesn't need to display any variable values. The specifier %d means convert the next value to a signed decimal integer and so:

printf("Total = %d",total);

will print Total = and then the value passed by >total as a decimal integer.

If you are familiar other programming languages then you may feel happy about the printf function because something like:

printf("Total = %d",total);

looks like the sort of output command you might have used before. For example, in BASIC you would write:

PRINT "Total = ",total

but the C view of output is at a lower level than you might expect. The %d isn't just a format specifier, it is a conversion specifier. It indicates the data type of the variable to be printed and how that data type should be converted to the characters that appear on the screen. That is %d says that the next value to be printed is a signed integer value (i.e. a value that would be stored in a standard int variable) and this should be converted into a sequence of characters (i.e. digits) representing the value in decimal. If by some accident the variable that you are trying to display happens to be a float or a double then you will still see a value displayed - but it will not correspond to the actual value of the float or double.

The reason for this is twofold.

  1. The first difference is that an int uses two bytes to store its value, while a float uses four and a double uses eight. If you try to display a float or a double using %d then only the first two bytes of the value are actually used.
  2. The second problem is that even if there wasn't a size difference ints, floats and doubles use a different binary representation and %d expects the bit pattern to be a simple signed binary integer.

This is all a bit technical, but that's in the nature of C. You can ignore these details as long as you remember two important facts:

  1. The specifier following % indicates the type of variable to be displayed as well as the format in which that the value should be displayed;
  2. If you use a specifier with the wrong type of variable then you will see some strange things on the screen and the error often propagates to other items in the printf list.

If this seems complicated then I would agree but I should also point out that the benefit is being able to treat what is stored in a variable in a more flexible way than other languages allow. Other languages never let on to the programmer that what is in fact stored in a variable is a bit pattern, not the decimal value that appears to be stored there when you use a printf (or whatever) statement. Of course whether you view this as an advantage depends on what you are trying to do. It certainly brings you closer to the way the machine works.

You can also add an 'l' in front of a specifier to mean a long form of the variable type and h to indicate a short form (long and short will be covered later in this course). For example, %ld means a long integer variable (usually four bytes) and %hd means short int. Notice that there is no distinction between a four-byte float and an eight-byte double. The reason is that a float is automatically converted to a double precision value when passed to printf - so the two can be treated in the same way. (In pre-ANSI all floats were converted to double when passed to a function but this is no longer true.) The only real problem that this poses is how to print the value of a pointer? The answer is that you can use %x to see the address in hex or %o to see the address in octal. Notice that the value printed is the segment offset and not the absolute address - to understand what we am going on about you need to know something about the structure of your processor.


The % Format Specifiers

The % specifiers that you can use in ANSI C are:

      Usual variable type           Display

 

%c        char                     single character

%d (%i)   int                      signed integer

%e (%E)   float or double          exponential format

%f        float or double          signed decimal

%g (%G)   float or double          use %f or %e as required

%o        int                      unsigned octal value

%p        pointer                  address stored in pointer

%s        array of char            sequence of characters

%u        int                      unsigned decimal

%x (%X)   int                      unsigned hex value

 


Formatting Your Output

The type conversion specifier only does what you ask of it - it convert a given bit pattern into a sequence of characters that a human can read. If you want to format the characters then you need to know a little more about the printf function's control string.

Each specifier can be preceded by a modifier which determines how the value will be printed. The most general modifier is of the form:

flag width.precision

The flag can be any of:

flag          meaning

 

   -         left justify

   +         always display sign

   space     display space if there is no sign

   0         pad with leading zeros

   #         use alternate form of specifier

 

The width specifies the number of characters used in total to display the value and precision indicates the number of characters used after the decimal point.

For example, %10.3f will display the float using ten characters with three digits after the decimal point. Notice that the ten characters includes the decimal point, and a - sign if there is one. If the value needs more space than the width specifies then the additional space is used - width specifies the smallest space that will be used to display the value. (This is quiet reassuring, you won't be the first programmer whose program takes hours to run but the output results can't be viewed because the wrong format width has been specified!)

The specifier %-1Od will display an int left justified in a ten character space. The specifier %+5d will display an int using the next five character locations and will add a + or - sign to the value.

The only complexity is the use of the # modifier. What this does depends on which type of format it is used with:

 

%#o    adds a leading 0 to the octal value

%#x    adds a leading 0x to the hex value

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت 8:

%#f or

%#e    ensures decimal point is printed

%#g    displays trailing zeros

           

Strings will be discussed later but for now remember: if you print a string using the %s specifier then all of the characters stored in the array up to the first null will be printed. If you use a width specifier then the string will be right justified within the space. If you include a precision specifier then only that number of characters will be printed.

For example:

printf("%s,Hello")

will print Hello,

printf("%25s ,Hello")

will print 25 characters with Hello right justified and

printf("%25.3s,Hello")

will print Hello right justified in a group of 25 spaces.

Also notice that it is fine to pass a constant value to printf as in printf("%s,Hello").

Finally there are the control codes:

 

\b       backspace

\f       formfeed

\n       new line

\r       carriage return

\t       horizontal tab

\'       single quote

\0       null

 

If you include any of these in the control string then the corresponding ASCII control code is sent to the screen, or output device, which should produce the effect listed. In most cases you only need to remember \n for new line.


scanf

Now that we have mastered the intricacies of printf you should find scanf very easy. The scanf function works in much the same way as the printf. That is it has the general form:

scanf(control string,variable,variable,...)

In this case the control string specifies how strings of characters, usually typed on the keyboard, should be converted into values and stored in the listed variables. However there are a number of important differences as well as similarities between scanf and printf.

The most obvious is that scanf has to change the values stored in the parts of computers memory that is associated with parameters (variables).

To understand this fully you will have to wait until we have covered functions in more detail. But, just for now, bare with us when we say to do this the scanf function has to have the addresses of the variables rather than just their values. This means that simple variables have to be passed with a preceding >&. (Note for future reference: There is no need to do this for strings stored in arrays because the array name is already a pointer.)

The second difference is that the control string has some extra items to cope with the problems of reading data in. However, all of the conversion specifiers listed in connection with printf can be used with scanf.

The rule is that scanf processes the control string from left to right and each time it reaches a specifier it tries to interpret what has been typed as a value. If you input multiple values then these are assumed to be separated by white space - i.e. spaces, newline or tabs. This means you can type:

3 4 5

or

3

4

5

 

and it doesn't matter how many spaces are included between items. For example:

scanf("%d %d",&i,&j);

will read in two integer values into i and j. The integer values can be typed on the same line or on different lines as long as there is at least one white space character between them.

The only exception to this rule is the %c specifier which always reads in the next character typed no matter what it is. You can also use a width modifier in scanf. In this case its effect is to limit the number of characters accepted to the width.

For example:

scanf("%lOd",&i)

would use at most the first ten digits typed as the new value for i.

There is one main problem with scanf function which can make it unreliable in certain cases. The reason being is that scanf tends to ignore white spaces, i.e. the space character. If you require your input to contain spaces this can cause a problem. Therefore for string data input the function getstr() may well be more reliable as it records spaces in the input text and treats them as an ordinary characters.


Custom Libraries

If you think printf and scanf don't seem enough to do the sort of job that any modern programmer expects to do, you would be right. In the early days being able to print a line at a time was fine but today we expect to be able to print anywhere on the screen at any time.

The point is that as far as standard C goes simple I/O devices are stream-oriented - that is you send or get a stream of characters without any notion of being able to move the current position in the stream. If you want to move backwards and forwards through the data then you need to use a direct access file. In more simple terms, C doesn't have a Tab(X,Y) or Locate(X,Y) function or command which moves the cursor to the specified location! How are you ever going to write your latest block buster game, let alone build your sophisticated input screens?

Well you don't have to worry too much because although C may not define them as standard, all C implementations come with an extensive graphics/text function library that allows you to do all of this and more. Such a library isn't standard, however the principles are always the same. The Borland and Microsoft offerings are usually considered as the two facto standards.


Summing It Up

Now that we have arithmetic, a way of reading values in and a way of displaying them, it's possible to write a slightly more interesting program than "Hello World". Not much more interesting, it's true, but what do you expect with two instructions and some arithmetic?

Let's write a program that adds two numbers together and prints the result. (I told you it wasn't that much more interesting!) Of course, if you want to work out something else like Fahrenheit to centigrade, inches to centimetres or the size of your bank balance, then that's up to you - the principle is the same.

The program is a bit more complicated than you might expect, but only because of the need to let the user know what is happening:

 

#include

main()

 {

   int a,b,c;

   printf("\nThe first number is ");

   scanf("%d",&a);

   printf("The second number is ");

   scanf("%d",&b);

   c=a+b;

   printf("The answer is %d \n",c);

 }

 

[program]

The first instruction declares three integer variables: a, b and c. The first two printf statements simply display message on the screen asking the user for the values. The scanf functions then read in the values from the keyboard into a and b. These are added together and the result in c is displayed on the screen with a suitable message. Notice the way that you can include a message in the printf statement along with the value.

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت 9:

Type the program in, compile it and link it and the result should be your first interactive program. Try changing it so that it works out something a little more adventurous. Try changing the messages as well. All you have to remember is that you cannot store values or work out results greater than the range of an integer variable or with a fractional part.


 

 

Control Loops


Objectives

Having read this section you should have an idea about C's:

  1. Conditional, or Logical, Expressions as used in program control
  2. the do while loop
  3. the while loop
  4. the for loop

Go With The Flow

Our programs are getting a bit more sophisticated, but they still lack that essential something that makes a computer so necessary. Exactly what they lack is the most difficult part to describe to a beginner. There are only two great ideas in computing. The first is the variable and you've already met that. The second is flow of control.

When you write a list of instructions for someone to perform you usually expect them to follow the list from the top to the bottom, one at a time. This is the simple default flow of control through a program. The C programs we have written so far use this one-after-another default flow of control.

This is fine and simple, but it limits the running time of any program we can write. Why? Simply because there is a limit to the number of instructions you can write and it doesn't take long for a computer to read though and obey your list. So how is it that we have programs that run for hours on end if need be? The answer is statements that alter the one-after-another order of obeying instructions. Perhaps the most useful is the loop.

Suppose we ask you to display "Hello World!" five times on the screen. Easy! you'd say:

 

#include

main()

 {

   printf("Hello World!\n");

   printf("Hello World!\n");

   printf("Hello World!\n");

   printf("Hello World!\n");

   printf("Hello World!\n");

 }

Indeed, this does exactly what was asked. But now we up the bet and ask you to do the same job for 100 hellos or, if you're still willing to type that much code, maybe 1,000 Hello World's, 10,000 Hello World's, or whatever it takes you to realise this isn't a sensible method!

What you really need is some way of repeating the printf statements without having to write it out each time. The solution to this problem is the while loop or the do while loop.


The while and do while Loops

You can repeat any statement using either the while loop:

while(condition) compound statement;

or the do while loop:

do compound statement while(condition);

The condition is just a test to control how long you want the compound statement to carry on repeating.

Each line of a C program up to the semicolon is called a statement. The semicolon is the statement's terminator. The braces { and } which have appeared at the beginning and end of our program unit can also be used to group together related declarations and statements into a compound statement or a block.

In the case of the while loop before the compound statement is carried out the condition is checked, and if it is true the statement is obeyed one more time. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement. So you can see that the instruction really means while something or other is true keep on doing the statement.

In the case of the do while loop it will always execute the code within the loop at least once, since the condition controlling the loop is tested at the bottom of the loop. The do while loop repeats the instruction while the condition is true. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement.


Conditions or Logical Expressions

The only detail we need to clear up is what the condition (or Logical Expression) can be. How, for example, do we display 100 or 10,000 "Hello World!" messages? The condition can be any test of one value against another. For example:

a>0

is true if a contains a value greater than zero;

b<0

is true if b contains a value less than zero.

The only complication is that the test for 'something equals something else' uses the character sequence == and not =. That's right: a test for equality uses two equal-signs, as in a==0, while an assignment, as in a=0, uses one. This use of the double or single equal sign to mean slightly different things is a cause of many a program bug for beginner and expert alike!

So what about answering the question? What about the 100 "Hello World"s? Well, for the moment we know easily how to produce an infinite number of Hello Worlds! using while loop:

 

#include

  main()

   {

    while (1 == 1) printf("Hello World!\n");

   }

and using the do while loop:

 

#include

  main()

   {

    do

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت دهم:

      printf("Hello World!\n");

    while (1 == 1)

   }

If you type either of these programs in and run it you will find that your screen fills with a never ending list of "Hello World!"s. Why? Because the condition to keep the repeat going is ( 1 == 1 ), one equals one in plain English, which is always true! So how do we stop the loop? In some cases it could be by pulling the plug out - but usually you can stop an infinite loop by pressing Ctrl-Break or Ctrl-C.

An infinite loop is sometimes useful - I certainly hope the program controlling the nearest nuclear power station is an infinite loop that never receives a Ctrl-Break signal! Most loops, however, have to stop some time.

To solve our problem of printing 100 "Hello World!"s we need a counter and a test for when that counter reaches 100. A counter is a simple variable that has one added to it each time through the loop, using an instruction like this:

a=a+1;

This always confuses beginners, because they aren't used to seeing the variable on both sides of the equal-sign. All this means is that a has one added to it to produce a new value, and this value is stored back in the location called <B>a. If you're worried, try thinking about it as:

 

temp = a+l;

a    = temp;

 

The two approaches are more or less the same. C is a language where anything that's used often can be said concisely, so it lets you say "add one to a variable" using the shorter notation:

++a;

The double plus is read "increment a by one". Make sure you know that ++a; and a=a+1; are the same thing because you will often see both in typical C programs.

The increment operator ++ and the equivalent decrement operator --, can be used as either prefix (before the variable) or postfix (after the variable). Note: ++a increments a before using its value; whereas a++ which means use the value in a then increment the value stored in a.

Now it is easy to print "Hello World!" 100 times using the while loop:

 

#include

 main()

  {

   int count;

   count=0;

   while (count < 100)

    {

      ++count;

      printf("Hello World!\n");

    }

  }

[program]

or the do while loop:

 

#include

 main()

  {

   int count;

   count=0;

   do

    {

      ++count;

      printf("Hello, World!\n");

    } while (count < 100)

  }

[program]

Note: the use of the { and } to form a compound statement; all statements between the braces will be executed before the loop check is made.

The integer variable count is declared and then set to zero, ready to count the number of times we have gone round the loop. Each time round the loop the value of count is checked against 100. As long as it is less, the loop carries on. Each time the loop carries on, count is incremented and "Hello World!" is printed - so eventually count does reach 100 and the loop stops. These little programs are just a bit more subtle than you might think. Ask yourself, do they really print exactly 100 times? Ask yourself: what is the final value of count? If you want to make sure you are right change the printf to:

printf("count is %d",count);

and add a printf after the loop:

printf("final value is %d",count);

Make sure you understand why you get the results that you do. What would happen if you changed the initial value of count to be one rather than zero?


Looping the Loop

We have seen that any list of statements enclosed in curly brackets is treated as a single statement, a compound statement. So to repeat a list of statements all you have to do is put them inside a pair of curly brackets as in:

 

while (condition)

 {

   statementl;

   statement2;

   statement3;

 }

which repeats the list while the condition is true. Notice that the statements within the curly brackets have to be terminated by semicolons as usual. Notice also that as the while statement is a complete statement it too has to be terminated by a semi-colon - except for the influence of one other punctuation rule. You never have to follow a right curly bracket with a semi-colon. This rule was introduced to make C look tidier by avoiding things like

};};};}

at the end of a complicated program. You can write the semi-colon after the right bracket if you want to, but most C programmers don't. You can use a compound statement anywhere you can use a single statement.


The for Loop

The while, and do-while, loop is a completely general way of repeating a section of program over and over again - and you don't really need anything else but... The while loop repeats a list of instructions while some condition or other is true and often you want to repeat something a given number of times.

The traditional solution to this problem is to introduce a variable that is used to count the number of times that a loop has been repeated and use its value in the condition to end the loop. For example, the loop:

 

i=l;

while (i<10)

 {

   printf("%d \n",i);

   ++i;

 }

repeats while i is less than 10. As the ++ operator is used to add one to i each time through the loop you can see that i is a loop counter and eventually it will get bigger than 10, i.e. the loop will end.

The question is how many times does the loop go round? More specifically what values of i is the loop carried out for? If you run this program snippet you will find that it prints 1,2,3... and finishes at 10. That is, the loop repeats 10 times for values of i from 1 to 10. This sort of loop - one that runs from a starting value to a finishing value going up by one each time - is so common that nearly all programming languages provide special commands to implement it. In C this special type of loop can be implemented as a for loop.

 

for ( counter=start_value; counter <= finish_value; ++counter )

  compound statement

 

which is entirely equivalent to:

 

counter=start;

while (couner <= finish)

 {

  statements;

  ++counter;

 }

 

The condition operator <= should be interpreted as less than or equal too. We will be covering all of C's conditions , or logical expressions, in the next section.

For example to print the numbers 1 to 100 you could use:

for ( i=l; i <= 100; ++i ) printf("%d \n",i);

You can, of course repeat a longer list of instructions simply by using a compound statement.

The C for loop is much more flexible than this simple description. Indeed, many would be horrified at the way we have described the for loop without displaying its true generality, but keep in mind that there is more to come.

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت یازدهم:

In the meantime consider the following program, it does a temperature conversion, but it also introduces one or two new concepts:

  1. our counter does not have to be incremented (decremented) by 1; we can use any value.
  2. we can do calculations within the printf statement.

 

#include

 

main()

{

    int fahr;

 

    for ( fahr = 0 ; fahr <= 300 ; fahr = fahr + 20)

        printf("%4d %6.1f\n" , fahr , (5.0/9.0)*(fahr-32));

 

}

 

[program]

and here's another one for you to look at:

 

#include

 

main()

{

    int lower , upper , step;

    float fahr , celsius;

 

    lower = 0  ;

    upper = 300;

    step  = 20 ;

 

    fahr  = lower;

 

    while ( fahr <= upper ) {

                             celsius = (5.0 / 9.0) * (fahr - 32.0);

                             printf("%4.0f %6.1f\n" , fahr , celsius);

                             fahr = fahr + step;

                            }

}


 

 

Conditional Execution


Objectives

Having read this section you should be able to:

  1. Program control with if , if-else and switch structures
  2. have a better idea of what C understands as true and false.

Program Control

It is time to turn our attention to a different problem - conditional execution. We often need to be able to choose which set of instructions are obeyed according to a condition. For example, if you're keeping a total and you need to display the message 'OK' if the value is greater than zero you would need to write something like:

if (total>O) printf("OK");

This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if statement allows you to evaluate a > condition and only carry out the statement, or compound statement, that follows if the condition is true. In other words the printf will only be obeyed if the condition total > O is true.

If the condition is false then the program continues with the next instruction. In general the if statement is of the following form:

if (condition) statement;

and of course the statement can be a compound statement.

Here's an example program using two if statements:

 

 

#include

 

main()

{

    int a , b;

 

    do {

 

        printf("\nEnter first number: ");

        scanf("%d" , &a);

 

        printf("\nEnter second number: ");

        scanf("%d" , &b);

 

        if (a

        if (b

 

       } while (a < 999);

}

 

[program]

Here's another program using an if keyword and a compound statement or a block:

 

#include

 

main()

{

    int a , b;

 

    do {

 

        printf("\nEnter first number: ");

        scanf("%d" , &a);

 

        printf("\nEnter second number: ");

        scanf("%d" , &b);

 

        if (a

                  printf("\n\nFirst number is less than second\n");

                  printf("Their difference is : %d\n" , b-a);

                  printf("\n");

                 }

 

        printf("\n");

 

       } while (a < 999);

}

 

 

[program]

The if statement lets you execute or skip an instruction depending on the value of the condition. Another possibility is that you might want to select one of two possible statements - one to be obeyed when the condition is true and one to be obeyed when the condition is false. You can do this using the

if (condition) statement1;

else statement2;

form of the if statement.

In this case statement1 is carried out if the condition is true and statement2 if the condition is false.

Notice that it is certain that one of the two statements will be obeyed because the condition has to be either true or false! You may be puzzled by the semicolon at the end of the if part of the statement. The if (condition) statement1 part is one statement and the else statement2 part behaves like a second separate statement, so there has to be semi-colon terminating the first statement.


Logical Expressions

So far we have assumed that the way to write the conditions used in loops and if statements is so obvious that we don't need to look more closely. In fact there are a number of deviations from what you might expect. To compare two values you can use the standard symbols:

> 

(greater than)

< 

(less than)

>=

(for greater than or equal to )

<=

(for less than or equal to)

==

(to test for equality)

The reason for using two equal signs for equality is that the single equals sign always means store a value in a variable - i.e. it is the assignment operator. This causes beginners lots of problems because they tend to write:

if (a = 10) instead of if (a == 10)

The situation is made worse by the fact that the statement if (a = 10) is legal and causes no compiler error messages! It may even appear to work at first

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت دوازدهم:

because, due to a logical quirk of C, the assignment actually evaluates to the value being assigned and a non-zero value is treated as true (see below). Confused? I agree it is confusing, but it gets easier. . .

Just as the equals condition is written differently from what you might expect so the non-equals sign looks a little odd. You write not equals as !=. For example:

if (a != 0)

is 'if a is not equal to zero'.

An example program showing the if else construction now follows:

 

#include

 

main ()

 {

   int num1, num2;

 

   printf("\nEnter first number ");

   scanf("%d",&num1);

 

   printf("\nEnter second number ");

   scanf("%d",&num2);

 

   if (num2 ==0) printf("\n\nCannot devide by zero\n\n");

   else          printf("\n\nAnswer is %d\n\n",num1/num2);

 }

 

[program]

This program uses an if and else statement to prevent division by 0 from occurring.


True and False in C

Now we come to an advanced trick which you do need to know about, but if it only confuses you, come back to this bit later. Most experienced C programmers would wince at the expression if(a!=0).

The reason is that in the C programming language dosen't have a concept of a Boolean variable, i.e. a type class that can be either true or false. Why bother when we can use numerical values. In C true is represented by any numeric value not equal to 0 and false is represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to write

if(a != 0) just as if(a)

because if a isn't zero then this also acts as the value true. It is debatable if this sort of shortcut is worth the three characters it saves. Reading something like

if(!done)

as 'if not done' is clear, but if(!total) is more dubious.


Using break and continue Within Loops

The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop is immediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops. You can have as many statements within a loop as you desire. It is generally best to use the break for special purposes, not as your normal loop exit. break is also used in conjunction with functions and case statements which will be covered in later sections.

The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.

 

#include

 

main()

{

    int x ;

 

    for ( x=0 ; x<=100 ; x++) {

                               if (x%2) continue;

                               printf("%d\n" , x);

                              }

}

 

 

[program]

Here we have used C's modulus operator: %. A expression:

a % b

produces the remainder when a is divided by b; and zero when there is no remainder.

Here's an example of a use for the break statement:

 

#include

 

main()

{

    int t ;

 

    for ( ; ; ) {

                 scanf("%d" , &t)   ;

                 if ( t==10 ) break ;

                }

    printf("End of an infinite loop...\n");

 

}

 

[program]


Select Paths with switch

While if is good for choosing between two alternatives, it quickly becomes cumbersome when several alternatives are needed. C's solution to this problem is the switch statement. The switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:

 

switch(expression)

{

  case constant1:   statement sequence; break;

  case constant2:   statement sequence; break;

  case constant3:   statement sequence; break;

  .

  .

  .

  default:   statement sequence; break;

}

 

Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional. If all matches fail and default is absent, no action takes place.

When a match is found, the statement sequence associated with that case are executed until break is encountered.

An example program follows:

 

#include

 

main()

 {

  int i;

 

  printf("Enter a number between 1 and 4");

  scanf("%d",&i);

 

  switch (i)

   {

     case 1:

      printf("one");

      break;

     case 2:

      printf("two");

      break;

     case 3:

      printf("three");

      break;

     case 4:

      printf("four");

      break;

     default:

      printf("unrecognized number");

   }    /* end of switch */

 

 }

 

[program]

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت سیزدهم:

This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes more than one statement they will have to be enclosed with {} to form a compound statement.


 

 

Structure and Nesting


Objectives

This section brings together the various looping mechanisms available to the C programmer with the program control constructs we met in the last section.

We also demonstrates a neat trick with random numbers.


It is one of the great discoveries of programming that you can write any program using just simple while loops and if statements. You don't need any other control statements at all. Of course it might be nice to include some other types of control statement to make life easy - for example, you don't need the for loop, but it is good to have! So as long as you understand the if and the while loop in one form or another you can write any program you want to.

If you think that a loop and an if statement are not much to build programs then you are missing an important point. It's not just the statements you have, but the way you can put them together. You can include an if statement within a loop, loops within loops are also OK, as are loops in ifs, and ifs in ifs and so on. This putting one control statement inside another is called nesting and it is really what allows you to make a program as complicated as you like.


 

Think of a number

Now let's have a go at writing the following program: 'It thinks of a number in the range 0 to 99 and then asks the user to guess it'. This sounds complicated, especially the 'thinks of a number' part, but all you need to know is that the statement:

r = rand()

will store a random number in the integer variable r. The standard library function rand() randomly picks a number within the range 0 to 32767, but this might vary from machine to machine. Look upon rand() as being a large dice.

Our problem is to select a number between 0 and 99 and not between 0 and 32767. How can we get our random number to within our range? The rand() function will produce numbers such as:

2567

134

20678

15789

32001

15987

etc...

 

If you look at the last two digits of all of these numbers they would form our random set! To select just these numbers we can use an arithmetic calculation of the following form:

r = rand() % 100

That is, to get the number into the right range you simply take the remainder on dividing by 100, ie a value in the range 0 to 99. You should remember this neat programming trick, you'll be surprised how often it is required.

Our solution to the problem is as follows:

 

#include

 

main()

 {

   int target;

   int guess;

   int again;

 

   printf("\n Do you want to guess a number 1 =Yes, 0=No ");

   scanf("%d",&again);

 

   while (again)

    {

      target = rand() % 100;

      guess  = target + l;

 

      while(target!=guess)

       {

         printf('\n What is your guess ? ");

         scanf("%d",&guess);

 

         if (target>guess) printf("Too low");

         else printf("Too high");

       }

 

      printf("\n Well done you got it! \n");

      printf("\nDo you want to guess a number 1=Yes, 0=No");

      scanf("%d".&again);

    }

 }

[program]

This looks like a very long and complicated program, but it isn't. Essentially it used two loops and an if/else which in English could be summarised as:

 

 

while(again) {

  think of a number

  while (user hasn't guessed it)

   {

     get users guess.

     if (target < guess) tell the user the guess is low

     else                tell the user the guess is high

   }

}

The integer variable again is used to indicate that the user wants to carry on playing. If it is 0 then the loop stops so 0 = No, and 1, or any other non-zero value, = Yes.

If you try this program out you will discover that it has a slight flaw - not so much a bug, more a feature. If the user guesses the correct value the program still tells the user that the guess is too high and then congratulates them that they have the correct value. Such problems with how loops end are common and you have to pay attention to details such as this. There are a number of possible solutions, but the most straight forward is to change the inner loop so that the first guess is asked for before the loop begins. This shifts the test for the loop to stop to before the test for a high or low guess:

 

 

#include

 

main()

 

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت چهاردهم:

{

   int target;

   int guess;

   int again;

 

   printf("\n Do you want to guess a number 1 =Yes, 0=No ");

   scanf("%d",&again);

 

   while (again)

    {

      target = rand() % 100;

 

      printf('\n What is your guess ? ");

      scanf("%d",&guess);

 

      while(target!=guess)

       {

         if (target>guess) printf("Too low");

         else printf("Too high");

         printf('\n What is your guess ? ");

         scanf("%d",&guess);

       }

 

      printf("\n Well done you got it! \n");

      printf("\n Do you want to guess a number 1=Yes, 0=No");

      scanf("%d".&again);

    }

 }

[program]

If you want to be sure that you understand what is going on here, ask yourself why the line:

guess = target + 1;

was necessary in the first version of the program and not in the second?


 

 

Functions and Prototypes


Objectives

Having read this section you should be able to:

  1. program using correctly defined C functions
  2. pass the value of local variables into your C functions

Functions - C's Building Blocks

Some programmers might consider it a bit early to introduce the C function - but we think you can't get to it soon enough. It isn't a difficult idea and it is incredibly useful. You could say that you only really start to find out what C programming is all about when you start using functions.

C functions are the equivalent of what in other languages would be called subroutines or procedures. If you are familiar with another language you also need to know that C only has functions, so don't spend time looking for the definition of subroutines or procedures - in C the function does everything!

A function is simply a chunk of C code (statements) that you have grouped together and given a name. The value of doing this is that you can use that "chunk" of code repeatedly simply by writing its name. For example, if you want to create a function that prints the word "Hello" on the screen and adds one to variable called total then the chunk of C code that you want to turn into a function is just:

 

printf("Hello");

total = total + l;

 

To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single compound statement and write the name that you want to give it in front of the brackets:

 

demo()

 {

  printf("Hello");

  total = total + 1;

 }

 

Don't worry for now about the curved brackets after the function's name. Once you have defined your function you can use it within a program:

 

main()

 {

  demo();

 }

 

In this program the instruction demo (); is entirely equivalent to writing out all of the statements in the function. What we have done is to create an new C function and this, of course, is the power of functions. When you are first introduced to the idea of functions, or their equivalent in other languages, it is easy to fall into the trap of thinking that they are only useful when you want to use a block of code more than once.

Functions are useful here but they have a more important purpose. If you are creating a long program then functions allow you to split it into "bite-sized" chunks which you can work on in isolation. As every C programmer knows, "functions are the building blocks of programs."


Functions and Local Variables

Now that the philosophy session is over we have to return to the details - because as it stands the demo function will not work. The problem is that the variable total isn't declared anywhere. A function is a complete program sub-unit in its own right and you can declare variables within it just as you can within the main program. If you look at the main program we have been using you will notice it is in fact a function that just happens to be called "main"! So to make demo work we have to add the declaration of the variable total:

 

demo()

 {

  int total;

  printf("Hello");

  total=total+1;

 }

 

Now this raises the question of where exactly total is a valid variable. You can certainly use total within the function that declares it - this much seems reasonable - but what about other functions and, in particular, what about the main program? The simple answer is that total is a variable that belongs to the demo function. It cannot be used in other functions, it doesn't even exist in other functions and it certainly has nothing to do with any variable of the same name that you declare within other functions.

This is what we hinted at when we said that functions were isolated chunks of code. Their isolation is such that variables declared within the function can only be used within that function. These variables are known as local variables and as their name suggests are local to the function they have been declared in. If you are used to a language where every variable is usable all the time this might seem silly and restrictive - but it isn't. It's what makes it possible to break a large program down into smaller and more manageable chunks.

The fact that total is only usable within the demo function is one thing - but notice we said that it only existed within this function, which is a more subtle point. The variables that a function declares are created when the function is started and destroyed when the function is finished. So if the intention is to use total to count the number of times the >demo function is used - forget it! Each time demo is used the variable total is created afresh, and at the end of the function the variable goes up in a puff of smoke along with its value. So no matter how many times you run demo total will only ever reach a value of 1, assuming that it's initialised to 0.


Making The Connections

Functions are isolated, and whats more nothing survives after they have finished. Put like this a function doesn't seem to be that useful because you can't get data values in, you can't get data values out, and they don't remember anything that happens to them!

To be useful there has to be a way of getting data into and out of a function, and this is the role of the curved brackets. You can define special variables called parameters which are used to carry data values into a function. Parameters are listed and declared in between the () brackets in the function's definition. For example:

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت 15:

sum( int a, int b)

 {

  int result;

  result=a + b;

 }

 

defines a function called sum with two parameters a and b, both integers. Notice that the result variable is declared in the usual way within the body of the function. Also, notice that the parameters a and b are used within the function in the same way as normal variables - which indeed they are. What is more, they are still local variables and have nothing at all to do with any variables called a and b defined in any other function.

The only way in which parameters are any different is that you can give them initial values when the function starts by writing the values between the round brackets. So

sum(l,2);

is a call to the sum function with a set to 1 and b set to 2 and so result is set to 3. You can also initialise parameters to the result of expressions such as:

sum(x+2,z*10);

which will set a equal to whatever x+2 works out to be and b equal to whatever z*10 works out to be.

As a simpler case you can also set a parameter to the value in a single variable - for example:

sum(x,y);

will set a to the value stored in x and b to the value stored in y.

Parameters are the main way of getting values into a function, but how do we get values out? There is no point in expecting the >result variable to somehow magically get its value out of the sum function - after all, it is a local variable and is destroyed when sum is finished. You might try something like:

 

sum(int a, int b, int result)

 {

  int result;

  result = a + b;

 }

 

but it doesn't work. Parameters are just ordinary variables that are set to an initial value when the function starts running - they don't pass values back to the program that used the function. That is:

sum(l,2,r);

doesn't store 1+2 in r because the value in r is used to initialise the value in result and not vice versa. You can even try

sum(l,2,result);

and it still will not work - the variable result within the function has nothing to do with the variable result used in any other program.

The simplest way to get a value out of a function is to use the return instruction. A function can return a value via its name - it's as if the name was a variable and had a value. The value that is returned is specified by the instruction:

return value;

which can occur anywhere within the function, not just as the last instruction - however, a return always terminates the function and returns control back to the calling function. The only complication is that as the function's name is used to return the value it has to be given a data type. This is achieved by writing the data type in front of the function's name. For example:

int sum(a,b);

So now we can at last write the correct version of the sum function:

 

int sum(int a, int b)

  {

   int result;

   result = a + b;

   return result;

  }

 

and to use it you would write something like:

r=sum(1,2);

which would add 1 to 2 and store the result in r. You can use a function anywhere that you can use a variable. For example,

r=sum(1,2)*3

is perfectly OK, as is

r=3+sum(1,2)/n-10

Obviously, the situation with respect to the number of inputs and outputs of a function isn't equal. That is you can create as many parameters as you like but a function can return only a single value. (Later on we will have to find ways of allowing functions to return more than one value.)

So to summarise: a function has the general form:

 

type FunctionName(type declared parameter list)

  {

   statements that make up the function

  }

 

and of course a function can contain any number of return statements to specify its return value and bring the function to an end.

There are some special cases and defaults we need to look at before moving on. You don't have to specify a parameter list if you don't want to use any parameters - but you still need the empty brackets! You don't have to assign the function a type in which case it defaults to int. A function doesn't have to return a value and the program that makes use of a function doesn't have to save any value it does return. For example, it is perfectly OK to use:

sum(1,2);

which simply throws away the result of adding 1 to 2. As this sort of thing offends some programmers you can use the data type void to indicate that a function doesn't return a value. For example:

void demo();

is a function with no parameters and no return value.

void is an ANSI C standard data type.

The break statement covered in a previous section can be used to exit a function. The break statement is usually linked with an if statement checking for a particular value. For example:

if (x==1) break;

If x contained 1 then the fuction would exit and return to the calling program.


Functions and Prototypes

Where should a function's definition go in relation to the entire program - before or after main()? The only requirement is that the function's type has to be known before it is actually used. One way is to place the function definition earlier in the program than it is used - for example, before main(). The only problem is that most C programmers would rather put the main program at the top of the program listing. The solution is to declare the function separately at the start of the program. For example:

 

int sum();

 main()

  {

   etc...

declares the name sum to be a function that returns an integer. As long as you declare functions before they are used you can put the actual definition anywhere you like.

By default if you don't declare a function before you use it then it is assumed to be an int function - which is usually, but not always, correct. It is worth getting into the habit of putting function declarations at the start of your programs because this makes them easier to convert to full ANSI C.


What is ANSI C?

When C was first written the standard was set by its authors Kernighan and Ritche - hence "K&R C". In 1990, an international ANSI standard for C was established which differs from K&R C in a number of ways.

The only really important difference is the use of function prototypes. To allow the compiler to check that you are using functions correctly ANSI C allows you to include a function prototype which gives the type of the function and the type of

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت شانزدهم:

each parameter before you define the function. For example, a prototype for the sum function would be:

int sum(int,int);

meaning sum is an int function which takes two int parameters. Obviously, if you are in the habit of declaring functions then this is a small modification. The only other major change is that you can declare parameter types along with the function as in:

 

int sum(int a, int b);

{

rather than:

 

int sum(a,b)

int a,b;

{

was used in the original K&R C. Again, you can see that this is just a small change. Notice that even if you are using an ANSI compiler you don't have to use prototypes and the K&R version of the code will work perfectly well.


The Standard Library Functions

Some of the "commands" in C are not really "commands" at all but are functions. For example, we have been using printf and scanf to do input and output, and we have used rand to generate random numbers - all three are functions.

There are a great many standard functions that are included with C compilers and while these are not really part of the language, in the sense that you can re-write them if you really want to, most C programmers think of them as fixtures and fittings. Later in the course we will look into the mysteries of how C gains access to these standard functions and how we can extend the range of the standard library. But for now a list of the most common libraries and a brief description of the most useful functions they contain follows:

  • stdio.h: I/O functions:
    • getchar() returns the next character typed on the keyboard.
    • putchar() outputs a single character to the screen.
    • printf() as previously described
    • scanf() as previously described
  • string.h: String functions
    • strcat() concatenates a copy of str2 to str1
    • strcmp() compares two strings
    • strcpy() copys contents of str2 to str1
  • ctype.h: Character functions
    • isdigit() returns non-0 if arg is digit 0 to 9
    • isalpha() returns non-0 if arg is a letter of the alphabet
    • isalnum() returns non-0 if arg is a letter or digit
    • islower() returns non-0 if arg is lowercase letter
    • isupper() returns non-0 if arg is uppercase letter
  • math.h: Mathematics functions
    • acos() returns arc cosine of arg
    • asin() returns arc sine of arg
    • atan() returns arc tangent of arg
    • cos() returns cosine of arg
    • exp() returns natural logarithim e
    • fabs() returns absolute value of num
    • sqrt() returns square root of num
  • time.h: Time and Date functions
    • time() returns current calender time of system
    • difftime() returns difference in secs between two times
    • clock() returns number of system clock cycles since program execution
  • stdlib.h:Miscellaneous functions
    • malloc() provides dynamic memory allocation, covered in future sections
    • rand() as already described previously
    • srand() used to set the starting point for rand()

Throwing The Dice

As an example of how to use functions, we conclude this section with a program that, while it isn't state of the art, does show that there are things you can already do with C. It also has to be said that some parts of the program can be written more neatly with just a little more C - but that's for later. All the program does is to generate a random number in the range 1 to 6 and displays a dice face with the appropriate pattern.

The main program isn't difficult to write because we are going to adopt the traditional programmer's trick of assuming that any function needed already exists. This approach is called stepwise refinement, and although its value as a programming method isn't clear cut, it still isn't a bad way of organising things:

 

main()

 {

   int r;

   char ans;

 

   ans = getans();

 

   while(ans== 'y')

    {

      r = randn(6);

      blines(25);

      if (r==1) showone();

      if (r==2) showtwo();

      if (r==3) showthree();

      if (r==4) showfour();

      if (r==5) showfive();

      if (r==6) showsix();

      blines(21);

      ans = getans();

    }

 

   blines(2);

 }

 

If you look at main() you might be a bit mystified at first. It is clear that the list of if statements pick out one of the functions showone, showtwo etc. and so these must do the actual printing of the dot patterns - but what is blines, what is getans and why are we using randn()? The last time we used a random number generator it was called rand()!

The simple answers are that blines(n) will print n blank lines, getans() asks the user a question and waits for the single letter answer, and randn(n) is a new random number generator function that produces a random integer in the range 1 to n - but to know this you would have written the main program. We decided what functions would make our task easier and named them. The next step is to write the code to fill in the details of each of the functions. There is nothing to stop me assuming that other functions that would make my job easier already exist. This is the main principle of stepwise refinement - never write any code if you can possibly invent another function! Let's start with randn().

This is obviously an int function and it can make use of the existing rand() function in the standard library

 

int randn(int n)

 {

   return rand()%n + 1;

 }

 

The single line of the body of the function just returns the remainder of the random number after dividing by n - % is the remainder operator - plus 1. An alternative would be to use a temporary variable to store the result and then return this value. You can also use functions within the body of other functions.

Next getans()

 

char getans()

 {

   int ans;

 

   printf("Throw y/n ?");

   ans = -1;

   while (ans == -1)

    {

      ans=getchar();

    }

   return ans;

}

 

This uses the standard int function getchar() which reads the next character from the keyboard and returns its ASCII code or -1 if there isn't a key pressed. This function tends to vary in its behaviour according to the implementation you are using. Often it needs a carriage return pressed before it will return anything - so if you are using a different compiler and the program just hangs, try pressing "y" followed the by Enter or Return key.

The blines(n) function simply has to use a for loop to print the specified number of lines:

 

void blines(int n)

  {

    int i;

 

    for(i=1 ; i<=n ; i++) printf("\n");

  }

 

Last but not least are the functions to print the dot patterns. These are just boring uses of printf to show different patterns. Each function prints exactly three lines

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت هفدهم:

of dots and uses blank lines if necessary. The reason for this is that printing 25 blank lines should clear a standard text screen and after printing three lines printing 21 blank lines will scroll the pattern to the top of the screen. If this doesn't happen on your machine make sure you are using a 29 line text mode display.

 

void showone()

  {

    printf("\n * \n");

  }

 

 void showtwo()

  {

    printf(" * \n\n");

    printf(" * \n");

  }

 

 void showthree()

  {

    printf(" *  \n");

    printf("  * \n");

    printf("   *\n");

  }

 

 void showfour()

  {

    printf(" * * \n\n");

    printf(" * * \n");

  }

 

 void showfive()

  {

    printf(" * * \n");

    printf("  *  \n");

    printf(" * * \n");

  }

 

 void showsix()

  {

    int i;

 

    for(i=1 ; i>=3 ; i++) printf(" * * \n");

  }

 

The only excitement in all of this is the use of a for loop in showsix! Type this all in and add:

 

void showone();

 void showtwo();

 void showthree();

 void showfour();

 void showfive();

 void showsix();

 int randn();

 char getans();

 void blines();

before the main function if you type the other functions in after.

[program]

Once you have the program working try modifying it. For example, see if you can improve the look of the patterns. You might also see if you can reduce the number of showx functions in use - the key is that the patterns are built up of combinations of two horizontal dots and one centred dot. Best of luck.


 

 

Data Types Part II


Objectives

So far we have looked at local variable now we switch our attention to other types of variables supported by the C programming language:

  1. Global Variables
  2. Constant Data Types

Global variables

Variables can be declared as either local variables which can be used inside the function it has been declared in (more on this in further sections) and global variables which are known throughout the entire program. Global variables are created by declaring them outside any function. For example:

 

int max;

 

 main()

  {

    .....

  }

 f1()

  {

    .....

  }

 

The int max can be used in both main and function f1 and any changes made to it will remain consistent for both functions. The understanding of this will become clearer when you have studied the section on functions but I felt I couldn't complete a section on data types without mentioning global and local variables.


Constant Data Types

Constants refer to fixed values that may not be altered by the program. All the data types we have previously covered can be defined as constant data types if we so wish to do so. The constant data types must be defined before the main function. The format is as follows:

#define CONSTANTNAME value

for example:

#define SALESTAX 0.05

The constant name is normally written in capitals and does not have a semi-colon at the end. The use of constants is mainly for making your programs easier to be understood and modified by others and yourself in the future. An example program now follows:

 

#define SALESTAX 0.05

#include

main()

 {

   float amount, taxes, total;

   printf("Enter the amount purchased : ");

   scanf("%f",&amount);

   taxes = SALESTAX*amount;

   printf("The sales tax is £%4.2f",taxes);

   printf("\n The total bill is £%5.2f",total);

 }

 

The float constant SALESTAX is defined with value 0.05. Three float variables are declared amount, taxes and total. Display message to the screen is achieved using printf and user input handled by scanf. Calculation is then performed and results sent to the screen. If the value of SALESTAX alters in the future it is very easy to change the value where it is defined rather than go through the whole program changing the individual values separately, which would be very time consuming in a large program with several references. The program is also improved when using constants rather than values as it improves the clarity.


 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت هجدهم:

Arrays


Objectives

Having read this section you should have a good understanding of the use of arrays in C.


 

Advanced Data Types

Programming in any language takes a quite significant leap forwards as soon as you learn about more advanced data types - arrays and strings of characters. In C there is also a third more general and even more powerful advanced data type - the pointer but more about that later. In this section we introduce the array, but the first question is, why bother?

There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:

 

main()

{

 int al,a2,a3,a4,a5;

 scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);

 printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);

}

 

Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.

In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. For example,

int a[5];

declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. C programmer's always start counting at zero! Languages vary according to where they start numbering arrays. Less technical, i.e. simpler, languages start counting from 1 and more technical ones usually start counting from 0. Anyway, in the case of C you have to remember that

type array[size]

declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].

Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple:

 

             

 main()

  {

   int a[5];

   int i;

   for(i =0;i < 5; ++i) scanf("%d",&a[i]);

   for(i =4;i> =0;--i) printf("%d",a[i]);

  }

 

[program]

Well we said simple but I have to admit that the pair of for loops looks a bit intimidating. The for loop and the array data type were more or less made for each other. The for loop can be used to generate a sequence of values to pick out and process each element in an array in turn. Once you start using arrays, for loops like:

for (i=0 ; i<5 ; ++i)

to generate values in the order 0,1,2 and so forth, and

for(i=4;i>=0;--i)

to generate values in the order 4,3,2... become very familiar.


In Dis-array

An array of character variables is in no way different from an array of numeric variables, but programmers often like to think about them in a different way. For example, if you want to read in and reverse five characters you could use:

 

main()

  {

   char a[5];

   int i;

   for(i=0; i<5; ++i) scanf("%c",&a[i]);

   for(i=4;i>=0;--i) printf("%c",a[i]);

  }

 

Notice that the only difference, is the declared type of the array and the %c used to specify that the data is to be interpreted as a character in scanf and printf. The trouble with character arrays is that to use them as if they were text strings you have to remember how many characters they hold. In other words, if you declare a character array 40 elements long and store H E L L O in it you need to remember that after element 4 the array is empty. This is such a nuisance that C uses the simple convention that the end of a string of characters is marked by a null character. A null character is, as you might expect, the character with ASCII code 0. If you want to store the null character in a character variable you can use the notation \0 - but most of the time you don't have to actually use the null character. The reason is that C will automatically add a null character and store each character in a separate element when you use a string constant. A string constant is indicated by double quotes as opposed to a character constant which is indicated by a single quote. For example:

"A"

is a string constant, but

'A'

is a character constant. The difference between these two superficially similar types of text is confusing at first and the source of many errors. All you have to remember is that "A" consists of two characters, the letter A followed by \0 whereas 'A' is just the single character A. If you are familiar with other languages you might think that you could assign string constants to character arrays and work as if a string was a built-in data type. In C however the fundamental data type is the array and strings are very much grafted on. For example, if you try something like:

 

char name[40];

name="Hello"

 

it will not work. However, you can print strings using printf and read them into character arrays using scanf. For example,

 

main()

  {

 

    static char name[40] ="hello";

 

    printf("%s",name);

    scanf("%s",name);

    printf("%s",name);

   }

 

[program]

This program reads in the text that you type, terminating it with a null and stores it in the character array name. It then prints the character array treating it as a string, i.e. stopping when it hits the first null string. Notice the use of the "%s" format descriptor in scanf and printf to specify that what is being printed is a string.


 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت نوزدهم:

At this point the way that strings work and how they can be made a bit more useful and natural depends on understanding pointers which is covered in the next section. Pointers


Objectives

Having read this section you should be able to:

  1. program using pointers
  2. understand how C uses pointers with arrays

Point to Point

Pointers are a very powerful, but primitive facility contained in the C language. Pointers are a throwback to the days of low-level assembly language programming and as a result they are sometimes difficult to understand and subject to subtle and difficult-to-find errors. Still it has to be admitted that pointers are one of the great attractions of the C language and there will be many an experienced C programmer spluttering and fuming at the idea that we would dare to refer to pointers as 'primitive'!

In an ideal world we would avoid telling you about pointers until the very last minute, but without them many of the simpler aspects of C just don't make any sense at all. So, with apologies, let's get on with pointers.

A variable is an area of memory that has been given a name. For example:

int x;

is an area of memory that has been given the name x. The advantage of this scheme is that you can use the name to specify where to store data. For example:

x=lO;

is an instruction to store the data value 10 in the area of memory named x. The variable is such a fundamental idea that using it quickly becomes second nature, but there is another way of working with memory.

The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that memory location.

A pointer is a variable that stores this location of memory. In more fundamental terms, a pointer stores the address of a variable . In more picturesque terms, a pointer points to a variable.

A pointer has to be declared just like any other variable - remember a pointer is just a variable that stores an address. For example,

int *p;

is a pointer to an integer. Adding an asterisk in front of a variable's name declares it to be a pointer to the declared type. Notice that the asterisk applies only to the single variable name that it is in front of, so:

int *p , q;

declares a pointer to an int and an int variable, not two pointers.

Once you have declared a pointer variable you can begin using it like any other variable, but in practice you also need to know the meaning of two new operators: & and *. The & operator returns the address of a variable. You can remember this easily because & is the 'A'mpersand character and it gets you the 'A'ddress. For example:

int *p , q;

declares p, a pointer to int, and q an int and the instruction:

p=&q;

stores the address of q in p. After this instruction you can think of p as pointing at q. Compare this to:

p=q;

which attempts to store the value in q in the pointer p - something which has to be considered an error.

The second operator * is a little more difficult to understand. If you place * in front of a pointer variable then the result is the value stored in the variable pointed at. That is, p stores the address, or pointer, to another variable and *p is the value stored in the variable that p points at.

The * operator is called the de-referencing operator and it helps not to confuse it with multiplication or with its use in declaring a pointer.

This multiple use of an operator is called operator overload.

Confused? Well most C programmers are confused when they first meet pointers. There seems to be just too much to take in on first acquaintance. However there are only three basic ideas:

  1. To declare a pointer add an * in front of its name.
  2. To obtain the address of a variable us & in front of its name.
  3. To obtain the value of a variable use * in front of a pointer's name.

Now see if you can work out what the following means:

 

int *a , b , c;

b = 10;

a = &b;

c = *a;

 

Firstly three variables are declared - a (a pointer to int), and b and c (both standard integers). The instruction stores the value l0 in the variable b in the usual way. The first 'difficult' instruction is a=&b which stores the address of b in a. After this a points to b.

Finally c = *a stores the value in the varable pointed to by a in c. As a points to b, its value i.e. 1O is stored in c. In other words, this is a long winded way of writing

c = b;

Notice that if a is an int and p is a pointer to an int then

a = p;

is nonsense because it tries to store the address of an int, i.e. a pointer value, in an int. Similarly:

a = &p;

tries to store the address of a pointer variable in a and is equally wrong! The only assignment between an int and a pointer to int that makes sense is:

a = *p;


Swap Shop

At the moment it looks as if pointers are just a complicated way of doing something we can already do by a simpler method. However, consider the following simple problem - write a function which swaps the contents of two variables. That is, write swap(a,b) which will swaps over the contents of a and b. In principle this should be easy:

 

function swap(int a , int b);

 {

  int temp;

  temp = a;

  a    = b;

  b    = temp;

 }

 

the only complication being the need to use a third variable temp to hold the value of a while the value of b overwrites it. However, if you try this function you will find that it doesn't work. You can use it - swap(a,b); - until you are blue in the face, but it just will not change the values stored in a and b back in the calling program. The reason is that all parameters in C are passed by value. That is, when you use swap(a,b) function the values in a and b are passed into the function swap via the parameters and any changes that are made to the parameters do not alter a and b back in the main program. The function swap does swap over the values in a and b within the function, but doesn't do so in the main program.

The solution to this very common problem is to pass not the values stored in the variables, but the addresses of the variables. The function can then use pointers

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیستم:

to get at the values in the variables in the main program and modify them. That is, the function should be:

 

function swap(int *a , int *b);

 {

  int temp;

  temp = *a;

  *a   = *b;

  *b   = temp;

 }

 

 

Notice that now the two parameters a and b are pointers and the assignments that effect the swap have to use the de-reference operator to make sure that it is the values of the variables pointed at that are swapped. You should have no difficulty with:

temp = *a;

this just stores the value pointed at by a into temp. However,

*a = *b;

is a little more unusual in that it stores that value pointed at by b in place of the value pointed at by a. There is one final complication. When you use swap you have to remember to pass the addresses of the variables that you want to swap. That is not:

swap(a,b)

but

swap(&a,&b)

The rule is that whenever you want to pass a variable so that the function can modify its contents you have to pass it as an address. Equally the function has to be ready to accept an address and work with it. You can't take any old function and suddenly decide to pass it the address of a variable instead of its value. If you pass an address to a function that isn't expecting it the result is usually disaster and the same is true if you fail to pass an address to a function that is expecting one.

For example, calling swap as swap(a,b) instead of swap(&a,&b) will result in two arbitrary areas of memory being swapped over, usually with the result that the entire system, not just your program, crashes.

The need to pass an address to a function also explains the difference between the two I/O functions that we have been using since the beginning of this course. printf doesn't change the values of its parameters so it is called as printf("%d",a) but scanf does, because it is an input function, and so it is called as scanf("%d",&a).


Pointers And Arrays

In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as:

int a[10];

you are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i . In the same way *(a+ 1) is the same as a[1] and so on.

Being able to add one to a pointer to get the next element of an array is a nice idea, but it does raise the question of what it means to add 'one' to a pointer. For example, in most implementations an int takes two memory locations and a float takes four. So if you declare an int array and add one to a pointer to it, then in fact the pointer will move on by two memory locations. However, if you declare a float array and add one to a pointer to it then the pointer has to move on by four memory locations. In other words, adding one to a pointer moves it on by an amount of storage depending on the type it is a pointer to.

This is, of course, precisely why you have to declare the type that the pointer is to point at! Only by knowing that a is a pointer to int and b is a pointer to float can the compiler figure out that

a + 1

means move the pointer on by two memory locations i.e. add 2, and

b + 1

means move the pointer on by four memory locations i.e. add 4. In practice you don't have to worry about how much storage a pointer's base type takes up. All you do need to remember is that pointer arithmetic works in units of the data type that the pointer points at. Notice that you can even use ++ and -- with a pointer, but not with an array name because this is a constant pointer and cannot be changed. So to summarise:

  1. An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0].
  2. Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i].

It is up to you whether you want to think about an array as an array or an area of storage associated with a constant pointer. The view of it as an array is the more sophisticated and the further away from the underlying way that the machine works. The view as a pointer and pointer arithmetic is more primitive and closer to the hardware. In most cases the distinction is irrelevant and purely a matter of taste.

One final point connected with both arrays and functions is that when you pass an entire array to a function then by default you pass a pointer. This allows you to write functions that process entire arrays without having to pass every single value stored in the array - just a pointer to the first element. However, it also temps you to write some very strange code unless you keep a clear head. Try the following - write a function that will fill an array with random values randdat(a,n) where a is the array and n is its size. Your first attempt might be something like:

 

void randdat(int *pa , int n)

  {

   for (pa = 0 ; pa < n ; pa++ ) *pa = rand()%n + 1;

  }

 

Well I hope your first attempt wouldn't be like this because it is wrong on a number of counts! The problem is that the idea of a pointer and the idea of an index have been confused. The pointer pa is supposed to point to the first element of the array, but the for loop sets it to zero and then increments it though a series of memory locations nowhere near the array. A lesser error is to suppose that n-1 is the correct final value of the array pointer! As before, you will be lucky if this program doesn't crash the system, let alone itself! The correct way of doing the job is to use a for loop to step from 0 to n-1, but to use pointer arithmetic to access the correct array element:

 

int randdat(int *pa , int n)

{

  int i;

  for ( i=0 ; i< n ; ++i)

   {

     *pa = rand()%n + 1;

     ++pa;

   }

}

 

Notice the way that the for loop looks just like the standard way of stepping through an array. If you want to make it look even more like indexing an array using a for loop you could write:

for(i=0 ; i

or even:

for(i=0 ; i

In other words, as long as you define pa as a pointer you can use array indexing notation with it and it looks as if you have actually passed an array. You can even declare a pointer variable using the notation:

int pa[];

that is, as an array with no size information. In this way the illusion of passing an array to a function is complete.


 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و یکم:

 

Strings


Objectives

This section brings together the use of two of C's fundamental data types, ponters and arrays, in the use of handling strings.

Having read this section you should be able to:

  1. handle any string constant by storing it in an array.

Stringing Along

Now that we have mastered pointers and the relationship between arrays and pointers we can take a second look at strings. A string is just a character array with the convention that the end of the valid data is marked by a null '\0'. Now you should be able to see why you can read in a character string using scanf("%s", name) rather than scanf("%s",&name) - name is already a pointer variable. Manipulating strings is very much a matter of pointers and special string functions. For example, the strlen(str) function returns the number of characters in the string str. It does this simply by counting the number of characters up to the first null in the character array - so it is important that you are using a valid null-terminated string. Indeed this is important with all of the C string functions.

You might not think that you need a function to copy strings, but simple assignment between string variables doesn't work. For example:

 

char a[l0],b[10];

b = a;

 

does not appear to make a copy of the characters in a, but this is an illusion. What actually happens is that the pointer b is set to point to the same set of characters that a points to, i.e. a second copy of the string isn't created.

To do this you need strcopy(a,b) which really does make a copy of every character in a in the array b up to the first null character. In a similar fashion strcat(a,b) adds the characters in b to the end of the string stored in a. Finally there is the all-important strcmp(a,b) which compares the two strings character by character and returns true - that is 0 - if the results are equal.

Again notice that you can't compare strings using a==b because this just tests to see if the two pointers a and b are pointing to the same memory location. Of course if they are then the two strings are the same, but it is still possible for two strings to be the same even if they are stored at different locations.

You can see that you need to understand pointers to avoid making simple mistakes using strings. One last problem is how to initialise a character array to a string. You can't use:

a = "hello";

because a is a pointer and "hello" is a string constant. However, you can use:

strcopy(a,"hello")

because a string constant is passed in exactly the same way as a string variable, i.e. as a pointer. If you are worried where the string constant is stored, the answer is in a special area of memory along with all of the constants that the program uses. The main disadvantage of this method is that many compilers use an optimisation trick that results in only a single version of identical constants being stored. For example:

strcopy(b,"hello");

usually ends up with b pointing to the same string as a. In other words, this method isn't particularly safe!

A much better method is to use array initialisation. You can specify constants to be used to initialise any variable when it is declared. For example:

int a=10;

declares a to be an integer and initialises it to 10. You can initialise an array using a similar notation. For example:

int a[5] = {1,2,3,4,5};

declares an integer array and initialises it so that a[0]= 1, a[1] = 2 and so on. A character array can be initialised in the same way. For example:

char a[5]={'h','e','l','l','o'};

but a much better way is to write:

char a[6]="hello";

which also automatically stores a null character at the end of the string - hence a[6] and not a[5]. If you really want to be lazy you can use:

char a[] = "hello";

and let the compiler work out how many array elements are needed. Some compilers cannot cope with the idea of initialising a variable that doesn't exist for the entire life of the program. For those compilers to make initialisation work you need to add the keyword static to the front of the string declaration, therefore:

static char a[] = "hello";


As easy as... B or C?

A few words of warning. If you are familiar with BASIC then you will have to treat C strings, and even C arrays, with some caution. They are not as easy or as obvious to use and writing a program that manipulates text is harder in C than in BASIC. If you try to use C strings as if it were BASIC strings you are sure to create some very weird and wonderful bugs!


A Sort Of Bubble Program

This sections program implements a simple bubble sort - which is notorious for being one of the worst sorting methods known to programmer-kind, but it does have the advantage of being easy and instructive. Some of the routines have already been described in the main text and a range of different methods of passing data in functions have also been used.

The main routine is sort which repeats the scan function on the array until the variable done is set to 0. The scan function simply scans down the array comparing elements that are next door to each other. If they are in the wrong order then function swap is called to swap them over.

Study this program carefully with particular attention to the way arrays, array elements and variables are passed. It is worth saying that in some cases there are better ways of achieving the same results. In particular, it would have been easier not to use the variable done, but to have returned the state as the result of the scan function.

 

#include

 

 

void randdat(int a[] , int n);

void sort(int a[] , int n);

void scan(int a[] , int n , int *done);

void swap(int *a ,int *b);

 

main()

 {

   int i;

   int a[20];

 

   randdat(a , 20);

   sort(a , 20);

 

   for(i=0;i<20;++i) printf("%d\n" ,a[i]);

 }

 

void randdat(int a[1] , int n)

 {

  int i;

  for (i=0 ; i

   a[i] = rand()%n+1;

 }

 

void sort(int a[1] , int n)

 {

  int done;

  done = 1;

  while(done == 1) scan(a , n , &done);

 }

 

void scan(int a[1] , int n , int *done)

 {

  int i;

  *done=0;

  for(i=0 ; i

   {

     if(a[i]

      {

       swap(&a[i],&a[i+1]);

       *done=1;

      }

   }

 }

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و دوم:

 

void swap(int *a ,int *b)

 {     

  int temp;

  temp = *a;

  *a   = *b;

  *b   = temp;

 }


 

 

Structures


Objectives

This section contains some very advanced but important features of the C programming language.

Having read this section you should be able to:

  1. program using a structure rather than several arrays.
  2. how pointer can be used in combination with structures to form linked list.

Structures

The array is an example of a data structure. It takes simple data types like int, char or double and organises them into a linear array of elements. The array serves most but not all of the needs of the typical C program. The restriction is that an array is composed of elements all of the same type. At first this seems perfectly reasonable. After all why would you want an array to be composed of twenty chars and two ints? Well this sort of mixture of data types working together is one of the most familiar of data structures. Consider for a moment a record card which records name, age and salary. The name would have to be stored as a string, i.e. an array of chars terminated with an ASCII null character, and the age and salary could be ints.

At the moment the only way we can work with this collection of data is as separate variables. This isn't as convenient as a single data structure using a single name and so the C language provides struct. At first it is easier to think of this as a record - although it's a little more versatile than this suggests.


Defining A New Type

Declaring a struct is a two-stage process. The first stage defines a new data type that has the required structure which can then be used to declare as many variables with the same structure as required. This two-stage process is often confusing at first - especially as it results in the need to think up multiple names with the same general meaning - but it really is quite simple. For example, suppose we need to store a name, age and salary as a single structure. You would first define the new data type using:

 

struct emprec

 {

   char name[25];

   int age;

   int pay;

 };

 

and then you would declare a new variable:

struct emprec employee

Notice that the new variable is called employee and it is of type emprec which has been defined earlier. You see what we mean about duplicating names - emprec is the name of the general employee record structure and employee is a particular example of this general type. It might help to compare the situation with that of a general int type and a particular int variable such as count - emprec is a type like int and employee is a variable like count. You can see that in general you can define a structure using:

 

struct name

 {

  list of component variables

 };

 

and you can have as long a list of component variables as you need. Once defined you can declare as many examples of the new type as you like using:

struct name list of variables;

For example:

struct emprec employee, oldemploy, newemploy;

and so on. If you want to you can also declare a structure variable within the type definition by writing its name before the final semi-colon. For example:

 

struct emprec

 {

   char name[25];

   int age;

   int pay;

 } employee;

 

defines the structure and declares a structure variable called employee. The only trouble with this form is that not many C programmers use it and many will even think that it is an error! So how do we use a struct?

When you first start working with arrays it seems obvious that you access the individual elements of the array using an index as in a[i] for the ith element of the array, but how to get at the individual components of a structure? The answer is that you have to use qualified names. You first give the name of the structure variable and then the name of the component separated by a dot. For example, given:

struct emprec employee

then:

employee.age

is an int and:

employee.name

is a char array. Once you have used a qualified name to get down to the level of a component then it behaves like a normal variable of the type. For example:

employee.age=32;

is a valid assignment to an int and:

employee.name[2] = 'X';

is a valid assignment to an element of the char array. Notice that the qualified name uses the structure variable name and not the structure type name. You can also define a structure that includes another structure as a component and of course that structure can contain another structure and so on. In this case you simply use the name of each structure in turn, separated by dots, until you reach a final component that isn't a structure. For example, if you declare a struct firm which includes a component employee which is an emprec then:

firm.employee.age

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و سوم:

is an int. You may be feeling a little disappointed at the way in which structures are used. When you first meet arrays it is obvious how useful they are because the array index is an integer which can be used within a loop to process vast amounts of data in a few lines of code. When you first meet the struct it just doesn't have the same obvious advantages. Because you have to write out a full qualified name to get at each of the components of the struct you can't automate the processing in the same way. However this is reasonable enough when you remember that each component of a struct can be a different data type! The point is that the value of a struct is different to that of an array. A struct can be used to wrap up a group of variables which form a coherent entity.

For example, C has no facilities for manipulating complex numbers but this is easy enough to put right using a struct and a few functions. A complex number is composed of two parts - a real and imaginary part - which can be implemented as single or double precision values. This suggests defining a new struct type:

 

struct comp

 {

   float real;

   float imag;

 };

 

After this you can declare new complex variables using something like:

struct comp a,b;

The new complex variables cannot be used as if they were simple variables - because they are not. Most versions, of the C language do allow you to assign structures so you could write:

a=b;

as shorthand for

 

a.real=b.real;

 a.imag=b.imag;

 

Being able to assign structures is even more useful when they are bigger. However you can't expect C to sort out what you mean by c = a + b - for this you have to write out the rule for addition as:

 

c.real=a.real+b.real;

 c.imag=a.imag+b.imag;


 

 


Structures and Functions

Of course a sensible alternative to writing out the addition each time is to define a function to do the same job - but this raises the question of passing structures as parameters. Fortunately this isn't a big problem. Most C compilers, will allow you to pass entire structures as parameters and return entire structures. As with all C parameters structures are passed by value and so if you want to allow a function to alter a parameter you have to remember to pass a pointer to a struct. Given that you can pass and return structs the function is fairly easy:

 

struct comp add(struct comp a , struct comp b)

{

 struct comp c;

 c.real=a.real+b.real;

 c.imag=a.imag+ b.imag;

 return c;

}

 

After you have defined the add function you can write a complex addition as:

x=add(y,z)

which isn't too far from the x=y+z that you would really like to use. Finally notice that passing a struct by value might use up rather a lot of memory as a complete copy of the structure is made for the function.


Pointers to Structures

You can define a pointer to a structure in the same way as any pointer to any type. For example:

struct emprec *ptr

defines a pointer to an emprec. You can use a pointer to a struct in more or less the same way as any pointer but the use of qualified names makes it look slightly different For example:

(*ptr).age

is the age component of the emprec structure that ptr points at - i.e. an int. You need the brackets because '.' has a higher priority than '*'. The use of a pointer to a struct is so common, and the pointer notation so ugly, that there is an equivalent and more elegant way of writing the same thing. You can use:

prt->age

to mean the same thing as (*ptr).age. The notation gives a clearer idea of what is going on - prt points (i.e. ->) to the structure and .age picks out which component of the structure we want. Interestingly until C++ became popular the -> notation was relatively rare and given that many C text books hardly mentioned it this confused many experienced C programmers!

There are many reasons for using a pointer to a struct but one is to make two way communication possible within functions. For example, an alternative way of writing the complex number addition function is:

 

void comp add(struct comp *a , struct comp *b , struct comp *c)

 {

  c->real=a->real+b->real;

  c->imag=a->imag+b->imag;

 }

 

In this case c is now a pointer to a comp struct and the function would be used as:

add(&x,&y,&z);

Notice that in this case the address of each of the structures is passed rather than a complete copy of the structure - hence the saving in space. Also notice that the function can now change the values of x, y and z if it wants to. It's up to you to decide if this is a good thing or not!


Malloc

Now we come to a topic that is perhaps potentially the most confusing. So far we have allowed the C compiler to work out how to allocate storage. For example when you declare a variable:

int a;

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و چهارم:

the compiler sorts out how to set aside some memory to store the integer. More impressive is the way that

int a[50]

sets aside enough storage for 50 ints and sets the name a to point to the first element. Clever though this may be it is just static storage. That is the storage is allocated by the compiler before the program is run - but what can you do if you need or want to create new variables as your program is running? The answer is to use pointers and the malloc function. The statement:

ptr=malloc(size);

reserves size bytes of storage and sets the pointer ptr to point to the start of it. This sounds excessively primitive - who wants a few bytes of storage and a pointer to it? You can make malloc look a little more appealing with a few cosmetic changes. The first is that you can use the sizeof function to allocate storage in multiples of a given type. For example:

sizeof(int)

returns a number that specifies the number of bytes needed to store an int. Using sizeof you can allocate storage using malloc as:

ptr= malloc(sizeof(int)*N)

where N is the number of ints you want to create. The only problem is what does ptr point at? The compiler needs to know what the pointer points at so that it can do pointer arithmetic correctly. In other words, the compiler can only interpret ptr++ or ptr=ptr+1 as an instruction to move on to the next int if it knows that the ptr is a pointer to an int. This works as long as you define the ptr to be a pointer to the type of variable that you want to work with. Unfortunately this raises the question of how malloc knows what the type of the pointer variable is - unfortunately it doesn't.

To solve this problem you can use a TYPE cast. This C play on words is a mechanism to force a value to a specific type. All you have to do is write the TYPE specifier in brackets before the value. So:

ptr = (*int) malloc(sizeof(int)*N)

forces the value returned by malloc to be a pointer to int. Now you can see how a simple idea ends up looking complicated. OK, so now we can acquire some memory while the program is running, but how can we use it? There are some simple ways of using it and some very subtle mistakes that you can make in trying to use it! For example, suppose during a program you suddenly decide that you need an int array with 50 elements. You didn't know this before the program started, perhaps because the information has just been typed in by the user. The easiest solution is to use:

int *ptr;

and then later on:

ptr = (*int) malloc(sizeof(int)*N)

where N is the number of elements that you need. After this definition you can use ptr as if it was a conventional array. For example:

ptr[i]

is the ith element of the array. The trap waiting for you to make a mistake is when you need a few more elements of the array. You can't simply use malloc again to get the extra elements because the block of memory that the next malloc allocates isn't necessarily next to the last lot. In other words, it might not simply tag on to the end of the first array and any assumption that it does might end in the program simply overwriting areas of memory that it doesn't own.

Another fun error that you are not protected against is losing an area of memory. If you use malloc to reserve memory it is vital that you don't lose the pointer to it. If you do then that particular chunk of memory isn't available for your program to use until it is restarted.


 

 


Structures and Linked Lists

You may be wondering why malloc has been introduced right after the structure. The answer is that the dynamic allocation of memory and the struct go together a bit like the array and the for loop. The best way to explain how this all fits together is via a simple example. You can use malloc to create as many variables as you want as the program runs, but how do you keep track of them? For every new variable you create you also need an extra pointer to keep track of it. The solution to this otherwise tricky problem is to define a struct which has a pointer as one of its components. For example:

 

struct list

 {

  int data;

  struct list *ptr;

 };

 

This defines a structure which contains a single int and - something that looks almost paradoxical - a pointer to the structure that is being defined. All you really need to know is that this is reasonable and it works. Now if you use malloc to create a new struct you also automatically get a new pointer to the struct. The final part of the solution is how to make use of the pointers. If you start off with a single 'starter' pointer to the struct you can create the first new struct using malloc as:

 

struct list *star;

start = (*struct list) malloc(sizeof(list))

 

After this start points to the first and only example of the struct. You can store data in the struct using statements like:

start->data=value;

The next step is to create a second example of the struct:

start = (*struct list) malloc(sizeof(list));

This does indeed give us a new struct but we have now lost the original because the pointer to it has been overwritten by the pointer to the new struct. To avoid losing the original the simplest solution is to use:

 

struct list *start,newitem;

newitem = (*struct list) malloc(sizeof(list));

start->prt=start;

start=newitem;

 

This stores the location of the new struct in newitem. Then it stores the pointer to the existing struct into the newitem's pointer and sets the start of the list to be the newitem. Finally the start of the list is set to point at the new struct. This procedure is repeated each time a new structure is created with the result that a linked list of structures is created. The pointer start always points to the first struct in the list and the prt component of this struct points to the next and so on. You should be able to see how to write a program that examines or prints the data in each of the structures. For example:

 

thisptr=start;

while (1==1)

 {

  printf("%d",thisprt-> data);

  thisprt=thisprt->prt;

 }

 

This first sets thisptr to the start of the list, prints the data in the first element and then gets the pointer to the next struct in the list and so on. How does the program know it has reached the end of the list? At the moment it just keeps going into the deep and uncharted regions of your machine's memory! To stop it we have to mark the end of the list using a null pointer. Usually a pointer value of 0 is special in that it never occurs in a pointer pointing at a valid area of memory. You can use 0 to initialise a pointer so that you know it isn't pointing at anything real. So all we have to do is set the last pointer in the list to 0 and then test for it That is:

 

thisptr=start;

while (thisptr!=0)

 {

  printf("%d",thisprt->data);

  thisprt=thisprt-> prt;

 }

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و پنجم:

 

To be completely correct you should TYPE cast 0 to be a pointer to the struct in question. That is:

while (thisptr!=(struct list*)0)

By generally mucking about with pointers stored in the list you can rearrange it, access it, sort it, delete items and do anything you want to. Notice that the structures in the list can be as complicated as you like and, subject to there being enough memory, you can create as many structures as you like.

You can use the same sort of technique to create even more complicated list structures. For example you can introduce another pointer into each structure and a pointer to the end of the list so that you can work your way along it in the other direction - a doubly linked list. You can create stacks, queues, trees and so on. The rest of the story is a matter of either inventing these data structures for yourself or looking them up in a suitable book.


Structures and C++

The reason why structures are even more important for today's budding C programmer is that they turn into classes in C++. A class is a structure where you can define components that are functions. In this case the same distinction between a data TYPE and an example of the TYPE, i.e. a variable, is maintained only now the instances of the class include functions as well as data. The same qualified naming system applies to the class and the use of pointers and the -> operator. As this is the basis of C++'s object-oriented features it is important to understand.


Header Files

The final mystery of C that needs to be discussed is the header file. This started off as a simple idea, a convenience to make programming easier. If you have a standard set of instructions that you want to insert in a lot of programs that you are writing then you can do it using the #include statement.

The # symbol at the start indicates that this isn't a C statement but one for the C pre-processor which looks at the text file before the compiler gets it. The #include tells the pre-processor to read in a text file and treat it as if it was part of the program's text. For example:

#include "copy.txt"

could be used to include a copyright notice stored in the file copy.txt. However the most common use of the #include is to define constants and macros. The C pre-processor is almost a language in its own right For example, if you define the identifier NULL as:

#define NULL 0

then whenever you use NULL in your program the pre-processor substitutes 0. In most cases you want these definitions to be included in all your programs and so the obvious thing to do is to create a separate file that you can #include.

This idea of using standard include files has spiralled out of all proportions. Now such include files are called header files and they are distinguished by ending in the extension .h. A header file is generally used to define all of the functions, variables and constants contained in any function library that you might want to use. The header file stdio.h should be used if you want to use the two standard I/O functions printf and scanf. The standard libraries have been covered in a previous section.

This sort of use of header files is simple enough but over time more and more standard elements of the C environment have been moved into header files. The result is that header files become increasingly mysterious to the beginner. Perhaps they reach their ultimate in complexity as part of the Windows development environment So many constants and macros are defined in the Windows header files that they amount to hundreds of lines! As another example of how you could use a header file consider the complex structure defined earlier. At the moment it looks messy to declare a new complex variable as:

struct comp a,b;

If you want to make the complex TYPE look like other data types all you need is a single #define

#define COMPLEX struct comp

After this you can write:

COMPLEX a,b;

and the pre-processor will automatically replace COMPLEX by struct comp for you when you compile the program. Put this #define and any others needed to make the complex number type work and you have the makings of a complex.h header file of your very own.


 

 

 

File Handling


Objectives

So far we have entered information into our programs via the computer's keyboard. This is somewhat laborious if we have a lot of data to process. The solution is to combine all the input data into a file and let our C program read the information when it is required.

Having read this section you should be able to:

  1. open a file for reading or writing
  2. read/write the contents of a file
  3. close the file

The Stream File

Although C does not have any built-in method of performing file I/O, the C standard library contains a very rich set of I/O functions providing an efficient, powerful and flexible approach. We will cover the ANSI file system but it must be mentioned that a second file system based upon the original UNIX system is also used but not covered on this course.

A very important concept in C is the stream. In C, the stream is a common, logical interface to the various devices that comprise the computer. In its most common form, a stream is a logical interface to a file. As C defines the term "file", it can refer to a disk file, the screen, the keyboard, a port, a file on tape, and so on. Although files differ in form and capabilities, all streams are the same. The stream provides a consistent interface and to the programmer one hardware device will look much like another.

A stream is linked to a file using an open operation. A stream is disassociated from a file using a close operation. The current location, also referred to as the current position, is the location in a file where the next file access will occur.

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و ششم:

There are two types of streams: text (used with ASCII characters some character translation takes place, may not be one-to-one correspondence between stream and what's in the file) and binary (used with any type of data, no character translation, one-to-one between stream and file).

To open a file and associate it with a stream, use fopen(). Its prototype is shown here:

FILE *fopen(char *fname,char *mode);

The fopen() function, like all the file-system functions, uses the header stdio.h . The name of the file to open is pointed to by fname (must be a valid name). The string pointed at for mode determines how the file may be accesed as shown:

Mode

Meaning

r

Open a text file for reading

w

Create a text file for writing

a

Append to a text file

rb

Open a binary file for reading

wb

Open a binary file for writing

ab

Append to a binary file

r+

Open a text file for read/write

w+

Create a text file for read/write

a+

Append or create a text file for read/write

r+b

Open a binary file for read/write

w+b

Create a binary file for read/write

a+b

Append a binary file for read/write

If the open operation is successful, fopen() returns a valid file pointer. The type FILE is defined in stdio.h. It is a structure that holds various kinds of information about the file, such as size.The file pointer will be used with all other functions that operate on the file and it must never be altered or the object it points to. If fopen() fails it returns a NULL pointer so this must always be checked for when opening a file. For example:

 

FILE *fp;

 

if ((fp = fopen("myfile", "r")) ==NULL){

  printf("Error opening file\n");

  exit(1);

}

To close a file, use fclose(), whose prototype is

int fclose(FILE *fp);

The fclose() function closes the file associated with fp, which must be a valid file pointer previously obtained using fopen(), and disassociates the stream from the file. The fclose() function returns 0 if successful and EOF (end of file) if an error occurs.

Once a file has been opened, depending upon its mode, you may read and/or write bytes to or from it using these two functions.

 

int fgetc(FILE *fp);

int fputc(int ch, FILE *fp);

The getc() function reads the next byte from the file and returns its as an integer and if error occurs returns EOF. The getc() function also returns EOF when the end of file is reached. Your routine can assign fget()'s return value to a char you don't have to assign it to an integer.

The fput() function writes the bytes contained in ch to the file associated with fp as an unsigned char. Although ch is defined as an int, you may call it using simply a char. The fput() function returns the character written if successful or EOF if an error occurs.


Text File Functions

When working with text files, C provides four functions which make file operations easier. The first two are called fputs() and fgets(), which write or read a string from a file, respectively. Their prototypes are:

 

int fputs(char *str,FILE *fp);

char *fgets(char *str, int num, FILE *fp);

 

The fputs() function writes the string pointed to by str to the file associated with fp. It returns EOF if an error occurs and a non-negative value if successful. The null that terminates str is not written and it does not automatically append a carriage return/linefeed sequence.

The fget() function reads characters from the file associated with fp into a string pointed to by str until num-1 characters have been read, a new line character is encountered, or the end of the file is reached. The string is null-terminated and the new line character is retained. The function returns str if successful and a null pointer if an error occurs.

The other two file handling functions to be covered are fprintf() and fscanf(). These functions operate exactly like printf() and scanf() except that they work with files. Their prototypes are:

 

int fprintf(FILE *fp, char *control-string, ...);

int fscanf(FILE *fp, char *control-string ...);

 

Instead of directing their I/O operations to the console, these functions operate on the file specified by fp. Otherwise their operations are the same as their console-based relatives. The advantages to fprintf() and fscanf() is that they make it very easy to write a wide variety of data to a file using a text format.


Binary File Functions

The C file system includes two important functions: fread() and fwrite(). These functions can read and write any type of data, using any kind of representation. Their prototypes are:

 

size_t fread(void *buffer, size_t size, size_t num,FILE *fp);

size_t fwrite(void *buffer, size_t size, size_t num, FILE *fp);

The fread() function reads from the file associated with fp, num number of objects, each object size bytes long, into buffer pointed to by buffer. It returns the number of objects actually read. If this value is 0, no objects have been read, and either end of file has been encountered or an error has occurred. You can use feof() or ferror() to find out which. Their prototypes are:

 

int feof(FILE *fp);

int ferror(FILE *fp);

 

The feof() function returns non-0 if the file associated with fp has reached the end of file, otherwise it returns 0. This function works for both binary files and text files. The ferror() function returns non-0 if the file associated with fp has experienced an error, otherwise it returns 0.

The fwrite() function is the opposite of fread(). It writes to file associated with fp, num number of objects, each object size bytes long, from the buffer pointed to by buffer. It returns the number of objects written. This value will be less than num only if an output error as occurred.

The void pointer is a pointer that can point to any type of data without the use of a TYPE cast (known as a generic pointer). The type size_t is a variable that is able to hold a value equal to the size of the largest object surported by the compiler. As a simple example, this program write an integer value to a file called MYFILE using its internal, binary representation.

 

#include   /* header file  */

#include

void main(void)

{

 

 FILE *fp;   /* file pointer */

 int i;

 

 /* open file for output */

 if ((fp = fopen("myfile", "w"))==NULL){

  printf("Cannot open file \n");

  exit(1);

 }

 i=100;

 

 if (fwrite(&i, 2, 1, fp) !=1){

  printf("Write error occurred");

  exit(1);

 }

 fclose(fp);

 

 /* open file for input */

 if ((fp =fopen("myfile", "r"))==NULL){

  printf("Read error occurred");

  exit(1);

 }

 printf("i is %d",i);

 fclose(fp);

}

[program]


File System Functions

You can erase a file using remove(). Its prototype is

int remove(char *file-name);

You can position a file's current location to the start of the file using rewind(). Its prototype is

void rewind(FILE *fp);

Hopefully I have given you enough information to at least get you started with files. Its really rather easy once you get started.

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت بیست و هفتم:(قسمت آخر)

Command Line Parameters

Many programs allow command-line arguments to be specified when they are run. A command-line argument is the information that follows the program's name on the command line of the operating system. Command-line arguments are used to pass information to the program. For example, when you use a text editor, you probably specify the name of the file you want to edit after the name of the word processing program. For example, if you use a word processor called WP, then this line causes the file TEST to be edited.

WP TEST

Here, TEST is a command-line argument. Your C programs may also utilize command-line arguments. These are passed to a C program through two arguments to the main() function. The parameters are called argc and argv. These parameters are optional and are not used when no command-line arguments are being used.

The argc parameter holds the number of arguments on the command-line and is an integer. It will always be at least 1 because the name of the program qualifies as the first argument. The argv parameter is an array of string pointers. The most common method for declaring argv is shown here.

char *argv[];

The empty brackets indicate that it is an array of undetermined length. All command-line arguments are passed to main() as strings. To access an individual string, index argv. For example, argv[0] points to the program's name and argv[1] points to the first argument. This program displays all the command-line arguments that it is called with.

 

#include

 

void main(int argc, char *argv[])

{

 int i;

 

 for (i=1; i<argc; i++) printf("%s",argv[i]);

}

 

The ANSI C standard does not specify what constitutes a command-line argument, because operatring systems vary considerably on this point. However, the most common convention is as follows:

Each command-line argument must be separated by a space or a tab character. Commas, semicolons, and the like are not considered separators. For example:

This is a test

is made up of four strings, but

this,that,and,another

is one string. If you need to pass a command-line argument that does, in fact contain spaces, you must place it between quotes, as shown in this example:

"this is a test"

A further example of the use of argc and argv now follows:

 

void main(int argc, char *argv[])

{

  if (argc !=2)  {

     printf("Specify a password");

     exit(1);

  }

  if (!strcmp(argv[1], "password"))

     printf("Access Permitted");

  else

    {

       printf("Access denied");

       exit(1);

    }

program code here ......

}

This program only allows access to its code if the correct password is entered as a command-line argument. There are many uses for command-line arguments and they can be a powerful tool.

My final example program takes two command-line arguments. The first is the name of a file, the second is a character. The program searches the specified file, looking for the character. If the file contains at least one of these characters, it reports this fact. This program uses argv to access the file name and the character for which to search.

 

/*Search specified file for specified character. */

 

#include

#include

 

void main(int argc, char *argv[])

{

  FILE *fp;   /* file pointer */

  char ch;

 

  /* see if correct number of command line arguments */

   if(argc !=3)  {

     printf("Usage: find \n");

     exit(1);

   }

 

   /* open file for input */

   if ((fp = fopen(argv[1], "r"))==NULL)  {

     printf("Cannot open file \n");

     exit(1);

   }

 

  /* look for character */

  while ((ch = getc(fp)) !=EOF)  /* where getc() is a */

    if (ch== *argv[2]) {         /*function to get one char*/

      printf("%c found",ch);     /* from the file */

      break;

    }

   fclose(fp);

}

 

[program]

The names of argv and argc are arbitrary - you can use any names you like. However, argc and argv have traditionally been used since C's origin. It is a good idea to use these names so that anyone reading your program can quickly identify them as command-line parameters.

 

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

ngc6543

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

آموزش زبان c قسمت چهارم:

of trouble! Also notice that the semicolon marks the end of an instruction - it isn't a separator as is the custom in other languages.If you're puzzled about why the curly brackets are on separate lines I'd better tell you that it's just a layout convention to help you spot matching brackets. C is very unfussy about the way you lay it out. For example, you could enter the Hello World program as:

main(){printf("Hello World\n");}

But this is unusual.


The printf function does what its name suggest it does: it prints, on the screen, whatever you tell it to. The "\n" is a special symbols that forces a new line on the screen.

OK, that's enough explanation of our first program! Type it in and save it as Hello.c. Then use the compiler to compile it, then the linker to link it and finally run it. The output is as follows:

Hello World


Add Comments to a Program

A comment is a note to yourself (or others) that you put into your source code. All comments are ignored by the compiler. They exist solely for your benefit. Comments are used primarily to document the meaning and purpose of your source code, so that you can remember later how it functions and how to use it. You can also use a comment to temporarily remove a line of code. Simply surround the line(s) with the comment symbols.

In C, the start of a comment is signalled by the /* character pair. A comment is ended by */. For example, this is a syntactically correct C comment:

/* This is a comment. */

Comments can extend over several lines and can go anywhere except in the middle of any C keyword, function name or variable name. In C you can't have one comment within another comment. That is comments may not be nested. Lets now look at our first program one last time but this time with comments:

main() /* main function heading */

{

printf("\n Hello, World! \n");  /* Display message on */

}                                   /* the screen */

This program is not large enough to warrant comment statements but the principle is still the same.


 

Data Types


Objectives

Having read this section you should be able to:

  1. declare (name) a local variable as being one of C's five data types
  2. initialise local variables
  3. perform simple arithmetic using local variables

Now we have to start looking into the details of the C language. How easy you find the rest of this section will depend on whether you have ever programmed before - no matter what the language was. There are a great many ideas common to programming in any language and C is no exception to this rule.

So if you haven't programmed before, you need to take the rest of this section slowly and keep going over it until it makes sense. If, on the other hand, you have programmed before you'll be wondering what all the fuss is about It's a lot like being able to ride a bike!

The first thing you need to know is that you can create variables to store values in. A variable is just a named area of storage that can hold a single value (numeric or character). C is very fussy about how you create variables and what you store in them. It demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it.

In this section we are only going to be discussing local variables. These are variables that are used within the current program unit (or function) in a later section we will looking at global variables - variables that are available to all the program's functions.


There are five basic data types associated with variables:

  • int - integer: a whole number.
  • float - floating point value: ie a number with a fractional part.
  • double - a double-precision floating point value.
  • char - a single character.
  • void - valueless special purpose type which we will examine closely in later sections.

One of the confusing things about the C language is that the range of values and the amount of storage that each of these types takes is not defined. This is because in each case the 'natural' choice is made for each type of machine. You can call variables what you like, although it helps if you give them sensible names that give you a hint of what they're being used for - names like sum, total, average and so on. If you are translating a formula then use variable names that reflect the elements used in the formula. For example, 2pr (that should read as "2 pi r" but that depends upon how your browser has been set-up) would give local variables names of pi and r. Remember, C programmers tend to prefer short names!

Note: all C's variables must begin with a letter or a "_" (underscore) character.


Integer Number Variables

The first type of variable we need to know about is of class type int - short for integer. An int variable can store a value in the range -32768 to +32767. You can think of it as a largish positive or negative whole number: no fractional part is allowed. To declare an int you use the instruction:

int variable name;

For example:

int a;

declares that you want to create an int variable called a.

To assign a value to our integer variable we would use the following C statement:

a=10;

 

+ نوشته شده در  شنبه بیست و ششم مرداد 1387ساعت 10:35 قبل از ظهر  توسط کامران  | 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

آموزش زبان c قسمت اول:


 

Introduction to C Programming



Objectives

This section is designed to give you a general overview of the C programming language. Although much of this section will be expanded in later sections it gives you a taste of what is to come.

 


 

Why use C?

C has been used successfully for every type of programming problem imaginable from operating systems to spreadsheets to expert systems - and efficient compilers are available for machines ranging in power from the Apple Macintosh to the Cray supercomputers. The largest measure of C's success seems to be based on purely practical considerations:

  • the portability of the compiler;
  • the standard library concept;
  • a powerful and varied repertoire of operators;
  • an elegant syntax;
  • ready access to the hardware when needed;
  • and the ease with which applications can be optimised by hand-coding isolated procedures

C is often called a "Middle Level" programming language. This is not a reflection on its lack of programming power but more a reflection on its capability to access the system's low level functions. Most high-level languages (e.g. Fortran) provides everything the programmer might want to do already built into the language. A low level language (e.g. assembler) provides nothing other than access to the machines basic instruction set. A middle level language, such as C, probably doesn't supply all the constructs found in high-languages - but it provides you with all the building blocks that you will need to produce the results you want!


Uses of C

C was initially used for system development work, in particular the programs that make-up the operating system. Why use C? Mainly because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:

  • Operating Systems
  • Language Compilers
  • Assemblers
  • Text Editors
  • Print Spoolers
  • Network Drivers
  • Modern Programs
  • Data Bases
  • Language Interpreters
  • Utilities

In recent years C has been used as a general-purpose language because of its popularity with programmers. It is not the world's easiest language to learn and you will certainly benefit if you are not learning C as your first programming language! C is trendy (I nearly said sexy) - many well established programmers are switching to C for all sorts of reasons, but mainly because of the portability that writing standard C programs can offer.


 


A Brief History of C

C is a general-purpose language which has been closely associated with the UNIX operating system for which it was developed - since the system and most of the programs that run it are written in C.

Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-7. BCPL and B are "type less" languages whereas C provides a variety of data types.

In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming Language by Kernighan & Ritchie caused a revolution in the computing world.

In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late 1988.

A Rough Guide to Programming Languages is available on-line for those of you that are interested.


 


C for Personal Computers

With regards to personal computers Microsoft C for IBM (or clones) PC's. and Borlands C are seen to be the two most commonly used systems. However, the latest version of Microsoft C is now considered to be the most powerful and efficient C compiler for personal computers.

Running C Programs


Objectives

Having read this section you should be able to:

  1. Edit, link and run your C programs

This section is primarily aimed at the beginner who as no or little experience of using compiled languages. We cover the various stages of program development. The basic principles of this section will apply to what ever C compiler you choose to use, the stages are nearly always the same


The Edit-Compile-Link-Execute Process

Developing a program in a compiled language such as C requires at least four steps:

  1. editing (or writing) the program
  2. compiling it
  3. linking it
  4. executing it

We will now cover each step separately.                  

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

آموزش زبان c قسمت دوم:

Editing

You write a computer program with words and symbols that are understandable to human beings. This is the editing part of the development cycle. You type the program directly into a window on the screen and save the resulting text as a separate file. This is often referred to as the source file (you can read it with the TYPE command in DOS or the cat command in unix). The custom is that the text of a C program is stored in a file with the extension .c for C programming language


Compiling

You cannot directly execute the source file. To run on any computer system, the source file must be translated into binary numbers understandable to the computer's Central Processing Unit (for example, the 80*87 microprocessor). This process produces an intermediate object file - with the extension .obj, the .obj stands for Object.


Linking

The first question that comes to most peoples minds is Why is linking necessary? The main reason is that many compiled languages come with library routines which can be added to your program. Theses routines are written by the manufacturer of the compiler to perform a variety of tasks, from input/output to complicated mathematical functions. In the case of C the standard input and output functions are contained in a library (stdio.h) so even the most basic program will require a library function. After linking the file extension is .exe which are executable files.


Executable files

Thus the text editor produces .c source files, which go to the compiler, which produces .obj object files, which go to the linker, which produces .exe executable file. You can then run .exe files as you can other applications, simply by typing their names at the DOS prompt or run using windows menu.


Using Microsoft C

Edit stage:

Type program in using one of the Microsoft Windows editing packages.

Compile and link:

Select Building from Make menu. Building option allows you to both compile and link in the same option.

Execute:

Use the Run menu and select Go option.

Errors:

First error highlighted. Use Next Error from Search menu for further errors if applicable.

If you get an error message, or you find that the program doesn't work when you finally run it (at least not in the way you anticipated) you will have to go back to the source file - the .c file - to make changes and go through the whole development process again!


Unix systems

The University's central irix Service is a Silicon Graphics Inc. Challenge XL system which runs a Unix-like operating sysem called IRIX. The basic information to run a C program on this system is covered in document HT.SI.05 - How To... Run C Programs On The irix Service. Although this document refers to the IRIX operating system many of the command options will be common to all Unix systems.

On all Unix systems further help on the C compiler can be obtained from the on-line manual. Type

man cc

on your local Unix system for more information.

Please note that Unix is a case sensitive operating system and files named firstprog.c and FIRSTPROG.c are treated as two separate files on these system. By default the Unix system compiles and links a program in one step, as follows:

cc firstprog.c

This command creates an executable file called a.out that overwrites any existing file called a.out. Executable files on Unix are run by typing their name. In this case the program is run as follows:

a.out

To change the name of the executable file type:

cc -o firstprog firstprog.c

This produces an executable file called firstprog which is run as follows:

Firstprog


 

 

Structure of C Programs


Objectives

Having completed this section you should know about:

  1. C's character set
  2. C's keywords
  3. the general structure of a C program
  4. that all C statement must end in a ;
  5. that C is a free format language
  6. all C programs us header files that contain standard library functions.

C's Character Set

C does not use, nor requires the use of, every character found on a modern computer keyboard. The only characters required by the C Programming Language are as follows:

  • A - Z
  • a -z
  • 0 - 9
  • space . , : ; ' $ "
  • # % & ! _ {} [] () < > |
  • + - / * =

The use of most of this set of characters will be discussed throughout the course.


The form of a C Program

All C programs will consist of at least one function, but it is usual (when your experience grows) to write a C program that comprises several functions. The only function that has to be present is the function called main. For more advanced programs the main function will act as a controlling function calling other functions in their turn to do the dirty work! The main function is the first function that is called when your program executes.

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

آموزش زبان c قسمت سوم:

C makes use of only 32 keywords which combine with the formal syntax to the form the C programming language. Note that all keywords are written in lower case - C, like UNIX, uses upper and lowercase text to mean different things. If you are not sure what to use then always use lowercase text in writing your C programs. A keyword may not be used for any other purposes. For example, you cannot have a variable called auto.


The layout of C Programs

The general form of a C program is as follows (don't worry about what everything means at the moment - things will be explained later):

pre-processor directives

global declarations

main()

{

   local variables to function main ;

   statements associated with function main ;

}

f1()

{

   local variables to function 1 ;

   statements associated with function 1 ;

}

f2()

{

   local variables to function f2 ;

   statements associated with function 2 ;

}

.

.

.

etc

Note the use of the bracket set () and {}. () are used in conjunction with function names whereas {} are used as to delimit the C statements that are associated with that function. Also note the semicolon - yes it is there, but you might have missed it! a semicolon (;) is used to terminate C statements. C is a free format language and long statements can be continued, without truncation, onto the next line. The semicolon informs the C compiler that the end of the statement has been reached. Free format also means that you can add as many spaces as you like to improve the look of your programs.

A very common mistake made by everyone, who is new to the C programming language, is to miss off the semicolon. The C compiler will concatenate the various lines of the program together and then tries to understand them - which it will not be able to do. The error message produced by the compiler will relate to a line of you program which could be some distance from the initial mistake.


Pre-processor Directives

C is a small language but provides the programmer with all the tools to be able to write powerful programs. Some people don't like C because it is too primitive! Look again at the set of keywords that comprises the C language and see if you can find a command that allows you to print to the computer's screen the result of, say, a simple calculation. Don't look too hard because it doesn't exist.

It would be very tedious, for all of us, if every time we wanted to communicate with the computer we all had to write our own output functions. Fortunately, we do not have to. C uses libraries of standard functions which are included when we build our programs. For the novice C programmer one of the many questions always asked is does a function already exist for what I want to do? Only experience will help here but we do include a function listing as part of this course.

All programs you will write will need to communicate to the outside world - I don't think I can think of a program that doesn't need to tell someone an answer. So all our C programs will need at least one of C's standard libraries which deals with standard inputting and outputting of data. This library is called stdin.h and it is declared in our programs before the main function. The .h extension indicates that this is a header file.

I have already mentioned that C is a free format language and that you can layout your programs how you want to using as much white space as you like. The only exception are statements associated with the pre-processor.

All pre-processor directives begin with a # and the must start in the first column. The commonest directive to all C programs is:

#include

Note the use of the angle brackets (< and >) around the header's name. These indicate that the header file is to be looked for on the system disk which stores the rest of the C program application. Some text books will show the above statement as follows:

#include "stdio.h"

The double quotes indicate that the current working directory should be searched for the required header file. This will be true when you write your own header files but the standard header files should always have the angle brackets around them.

NOTE: just to keep you on your toes - pre-processor statements, such as include, DO NOT use semi-colons as delimiters! But don't forget the # must be in the first column.


 

 

Your First Program


Objectives

Having read this section you should have an understanding of:

  1. a pre-processor directive that must be present in all your C programs.
  2. a simple C function used to write information to your screen.
  3. how to add comments to your programs

Now that you've seen the compiler in action it's time for you to write your very own first C program. You can probably guess what it's going to be - the program that everyone writes just to check they understand the very, very, very basics of what is going on in a new language.

Yes - it's the ubiquitous "Hello World" program. All your first program is going to do is print the message "Hello World" on the screen.


The program is a short one, to say the least. Here it is:

#include

main()

{

    printf("Hello World\n");

}

 

[program]

The first line is the standard start for all C programs - main(). After this comes the program's only instruction enclosed in curly brackets {}. The curly brackets mark the start and end of the list of instructions that make up the program - in this case just one instruction.

Notice the semicolon marking the end of the instruction. You might as well get into the habit of ending every C instruction with a semicolon - it will save you a lot

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 1:45 بعد از ظهر  توسط کامران  | 

اخبار نجومی

 

RELEASE: 08-199 .NASA Spacecraft Analyzing Martian Soil Data

WASHINGTON -- Scientists are analyzing results from soil samples delivered several weeks ago to science instruments on NASA's Phoenix Mars Lander to understand the landing site's soil chemistry and mineralogy.
Within the last month, two samples have been analyzed by the Wet Chemistry Lab of the spacecraft's Microscopy, Electrochemistry, and Conductivity Analyzer, or MECA, suggesting one of the soil constituents may be perchlorate, a highly oxidizing substance. The Phoenix team has been waiting for complementary results from the Thermal and Evolved-Gas Analyzer, or TEGA, which also is capable of detecting perchlorate. TEGA is a series of ovens and analyzers that "sniff" vapors released from substances in a sample.
NASA will hold a media teleconference on Tuesday, Aug. 5, at 2 p.m. EDT, to discuss these recent science activities. Participants will be introduced at the start of the briefing. To participate in the teleconference, reporters should contact Steve Cole on 202-358-0918 for dial-in and passcode information.
Confirmation of the presence of perchlorate and supporting data is important prior to scientific peer review and subsequent public announcements. The results from Sunday's TEGA experiment, which analyzed a sample taken directly above the ice layer, found no evidence of this compound.
"This is surprising since an earlier TEGA measurement of surface materials was consistent with but not conclusive of the presence of perchlorate," said Peter Smith, Phoenix's principal investigator at the University of Arizona, Tucson.
Scientists at the Phoenix Science Operations Center at the University of Arizona, Tucson, are specifically looking at the data from these instruments to provide information on the composition of Martian soil.
"We are committed to following a rigorous scientific process. While we have not completed our process on these soil samples, we have very interesting intermediate results," said Smith, "Initial MECA analyses suggested Earth-like soil. Further analysis has revealed un-Earthlike aspects of the soil chemistry."
The team also is working to totally exonerate any possibility of the perchlorate readings being influenced by terrestrial sources which may have migrated from the spacecraft, either into samples or into the instrumentation.
"When surprising results are found, we want to review and assure our extensive pre-launch contamination control processes covered this potential," said Barry Goldstein, Phoenix project manager at NASA's Jet Propulsion Laboratory in Pasadena, Calif.
Since landing on May 25, Phoenix has been studying Martian soil with MECA's wet chemistry lab, two microscopes and a conductivity probe, TEGA's ovens and two cameras.
MECA's robotic wet chemistry lab studies soluble chemicals in the soil by mixing a soil sample with a water-based solution with several reagents brought from Earth. The inner surface of each cell's beaker has 26 sensors that give information about the acidity or alkalinity and concentrations of elements such as chloride or perchlorate. The beaker also can detect concentrations of magnesium, calcium and potassium, which form salts that are soluble in water.
With continuing results and the spacecraft in good condition, the mission has been extended through Sept. 30. The original prime mission of three months ends in late August. The mission extension adds five weeks to the 90 days of the prime mission.
The Phoenix mission is led by Smith at the University of Arizona with project management at NASA's Jet Propulsion Laboratory in Pasadena, Calif., and development partnership at Lockheed Martin in Denver. International contributions come from the Canadian Space Agency; the University of Neuchatel, Switzerland; the universities of Copenhagen and Aarhus in Denmark; the Max Planck Institute in Germany; and the Finnish Meteorological Institute.

Directors: Dwayne Brown
Headquarters, Washington
202-358-1726
dwayne.c.brown@nasa.gov
Guy Webster
Jet Propulsion Laboratory, Pasadena, Calif.
818-354-6278
guy.webster@jpl.nasa.gov
Sara Hammond
University of Arizona, Tucson
520-626-1974
shammond@lpl.arizona.edu
 

For information about Phoenix, visit:

http://www.nasa.gov/phoenix

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:17 قبل از ظهر  توسط کامران  | 

اخبار نجومی

MEDIA ADVISORY: 08-203 .NASA 'Inspire' Interns Work To Become Future Explorers And Innovators



WASHINGTON -- In the coming weeks, high school and college students across the country will soon be heading back to school. A fortunate few will share some unique experiences. They will tell how they were at NASA for two months conducting cutting-edge research and working to send American astronauts to the moon and beyond.
This summer, more than 150 students from 23 states and Puerto Rico took part in a new NASA education project called "INSPIRE" -- the Interdisciplinary National Science Project Incorporating Research and Education Experience. The internships are located at each of NASA's 10 field centers.
"INSPIRE gives students, parents and teachers a mechanism for interacting with one another," said Steve Chance, INSPIRE project manager. "They ask questions, share knowledge and build 'a community of practice' that NASA hopes will lead them to pursue careers in fields critical to NASA and the nation."
The INSPIRE project is open to students in grades 9-12, including high school graduates preparing for their first year of college who are U.S. citizens and have at least an overall 2.5 grade point average or better on a 4.0 scale.
Interested students should first apply for entry into the INSPIRE online community, NASA's education resource for students, parents and teachers. Once selected for INSPIRE, they may compete for internships and other unique summer opportunities.
To participate in the summer opportunities, students must achieve a minimum 3.0 grade point average, submit an essay about their interest in NASA and the space program, and include two letters of recommendation from teachers or adult mentors with their application. NASA education officials assess all submissions, seeking candidates who demonstrate teamwork, leadership potential and career aspirations in fields related to math, science and engineering.
Through the INSPIRE online community, NASA provides resources and activities that help parents champion their students' goals. NASA also contributes to classrooms, providing teaching modules and resources designed to capture students' imaginations and enhance their technical and problem-solving skills.
Director: Sonja Alexander
Headquarters, Washington
202-358-1761
sonja.r.alexander@nasa.gov


For information about INSPIRE and how to participate in the program, visit:

www.nasa.gov/audience/forstudents/postsecondary/programs/INSPIRE_Project.html


For more information about NASA education programs, visit:

www.nasa.gov/education

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:17 قبل از ظهر  توسط کامران  | 

اخبار نجومی



RELEASE: 08-196 Take an Interactive Journey through NASA's First Fifty Years of Exploration

WASHINGTON -- This week marks the 50th anniversary of the signing of the space act that created NASA. To commemorate NASA's beginning, the agency has released an immersive multimedia experience that takes visitors on an interactive tour of its first five decades of exploration.
Combining current and historic video with state-of-the-art computer animation, the virtual exhibit takes a World's Fair approach to NASA history, featuring pavilions that host each decade of the agency's challenges and achievements. Visitors will get unique insight into NASA's activities over the years, including a wide range of exploration and research initiatives, and a glimpse into the future.
"We're very excited to have people come and take a look at NASA's history," said Brian Dunbar, NASA's Internet services manager at Headquarters in Washington. "We've been able to take a wide range of material and weave it into a virtual tour that allows people to explore at their own pace."
The exhibit's host is an animated robot named Automa, who will guide visitors through their journey. Also assisting everyone throughout their tour are important historic and cultural figures of the past 50 years of aerospace history, including astronauts, presidents, astronomers, and other popular icons associated with NASA's history. For example, in the 1970s pavilion, visitors will see a presentation of NASA's Voyager and Viking missions hosted by an avatar of the late astronomer Carl Sagan, complete with excerpts from his popular television series "Cosmos."
"We're making our first real foray into animation," said David Mould, associate administrator for public affairs, Headquarters, Washington. "It represents a new communications medium for us and we have been fortunate to get the support of a lot of people that has enabled us to include some recognizable historic figures as part of this interactive commemoration.” Visitors to the site can also experience: Interior 3D views of John Glenn's Friendship 7 Mercury spacecraft The original April 1959 press conference introducing the Mercury astronauts A tour of the International Space Station Video presentations about NASA's aeronautics programs An interview with former CBS news journalist Walter Cronkite
On July 29, 1958, the 34th President of the United States, Dwight D. Eisenhower, signed into law the "National Aeronautics and Space Act of 1958" (Public Law 85-568). Less than one month later, President Eisenhower administered the oath of office to NASA's first Administrator, T. Keith Glennan, and the agency's Deputy Administrator, Hugh L. Dryden, who had been serving as the director of NASA's predecessor, the National Advisory Committee for Aeronautics, or NACA.
Director: Bob Jacobs
Headquarters, Washington
202-358-1600
bob.jacobs@nasa.gov


To begin the tour of NASA's first 50 years, visit:

http://www.nasa.gov/50years

and learn more about the agency's 50th anniversary at:

http://www.nasa.gov/50th

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:16 قبل از ظهر  توسط کامران  | 

اخبار نجومی


 

RELEASE: 08-197 .NASA Names Irvine Deputy Associate Administrator for Aeronautics

WASHINGTON -- NASA Associate Administrator for Aeronautics Research Jaiwon Shin on Monday announced that Thomas B. Irvine will be the deputy associate administrator for the agency's Aeronautics Research Mission Directorate, effective immediately.
Since May 2005, Irvine has been the director of the Mission Support Office for the directorate at NASA Headquarters in Washington. In his new position, he will assist Shin with planning, management and development of NASA's aeronautics research activities.
NASA's Aeronautics Research Mission Directorate conducts cutting-edge, fundamental research in traditional aeronautical disciplines and emerging fields to help transform the U.S. air transportation system and support future air and space vehicles.
"Tom has been instrumental in the restructuring and management of NASA's aeronautics research programs since he came to Washington in 2004," said Shin. "He has extensive and well-rounded experience in the areas of aeronautics research, space station program engineering and management, institutional management, and NASA administration. Aeronautics benefits greatly from his presence on my team."
Irvine previously served as deputy director of the Aeronautics Test Program at NASA Headquarters. From 1999 to 2004, Irvine was the chief of the Facility Management and Planning Office at NASA's Glenn Research Center in Cleveland. During 26 years with NASA, he has held a variety of program management and research engineering positions in technical services, space operations and aeronautics.
Irvine holds a Master of Science degree in engineering mechanics and a Bachelor of Science degree in civil engineering from the Ohio State University in Columbus.
Irvine has received several commendations for group achievements, as well as NASA's Exceptional Service Medal for sustained contributions to NASA aeronautics and space flight missions.

Director” Beth Dickey
Headquarters, Washington
202-358-2087
beth.dickey-1@nasa.gov

For information about NASA's aeronautics research activities, visit:

http:///www.aeronautics.nasa.gov

 

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:16 قبل از ظهر  توسط کامران  | 

اخبار نجومی


 

 

RELEASE: 08-199 .NASA Spacecraft Analyzing Martian Soil Data

WASHINGTON -- Scientists are analyzing results from soil samples delivered several weeks ago to science instruments on NASA's Phoenix Mars Lander to understand the landing site's soil chemistry and mineralogy.
Within the last month, two samples have been analyzed by the Wet Chemistry Lab of the spacecraft's Microscopy, Electrochemistry, and Conductivity Analyzer, or MECA, suggesting one of the soil constituents may be perchlorate, a highly oxidizing substance. The Phoenix team has been waiting for complementary results from the Thermal and Evolved-Gas Analyzer, or TEGA, which also is capable of detecting perchlorate. TEGA is a series of ovens and analyzers that "sniff" vapors released from substances in a sample.
NASA will hold a media teleconference on Tuesday, Aug. 5, at 2 p.m. EDT, to discuss these recent science activities. Participants will be introduced at the start of the briefing. To participate in the teleconference, reporters should contact Steve Cole on 202-358-0918 for dial-in and passcode information.
Confirmation of the presence of perchlorate and supporting data is important prior to scientific peer review and subsequent public announcements. The results from Sunday's TEGA experiment, which analyzed a sample taken directly above the ice layer, found no evidence of this compound.
"This is surprising since an earlier TEGA measurement of surface materials was consistent with but not conclusive of the presence of perchlorate," said Peter Smith, Phoenix's principal investigator at the University of Arizona, Tucson.
Scientists at the Phoenix Science Operations Center at the University of Arizona, Tucson, are specifically looking at the data from these instruments to provide information on the composition of Martian soil.
"We are committed to following a rigorous scientific process. While we have not completed our process on these soil samples, we have very interesting intermediate results," said Smith, "Initial MECA analyses suggested Earth-like soil. Further analysis has revealed un-Earthlike aspects of the soil chemistry."
The team also is working to totally exonerate any possibility of the perchlorate readings being influenced by terrestrial sources which may have migrated from the spacecraft, either into samples or into the instrumentation.
"When surprising results are found, we want to review and assure our extensive pre-launch contamination control processes covered this potential," said Barry Goldstein, Phoenix project manager at NASA's Jet Propulsion Laboratory in Pasadena, Calif.
Since landing on May 25, Phoenix has been studying Martian soil with MECA's wet chemistry lab, two microscopes and a conductivity probe, TEGA's ovens and two cameras.
MECA's robotic wet chemistry lab studies soluble chemicals in the soil by mixing a soil sample with a water-based solution with several reagents brought from Earth. The inner surface of each cell's beaker has 26 sensors that give information about the acidity or alkalinity and concentrations of elements such as chloride or perchlorate. The beaker also can detect concentrations of magnesium, calcium and potassium, which form salts that are soluble in water.
With continuing results and the spacecraft in good condition, the mission has been extended through Sept. 30. The original prime mission of three months ends in late August. The mission extension adds five weeks to the 90 days of the prime mission.
The Phoenix mission is led by Smith at the University of Arizona with project management at NASA's Jet Propulsion Laboratory in Pasadena, Calif., and development partnership at Lockheed Martin in Denver. International contributions come from the Canadian Space Agency; the University of Neuchatel, Switzerland; the universities of Copenhagen and Aarhus in Denmark; the Max Planck Institute in Germany; and the Finnish Meteorological Institute.

Directors: Dwayne Brown
Headquarters, Washington
202-358-1726
dwayne.c.brown@nasa.gov
Guy Webster
Jet Propulsion Laboratory, Pasadena, Calif.
818-354-6278
guy.webster@jpl.nasa.gov
Sara Hammond
University of Arizona, Tucson
520-626-1974
shammond@lpl.arizona.edu
 

For information about Phoenix, visit:

http://www.nasa.gov/phoenix

 

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:16 قبل از ظهر  توسط کامران  | 

اخبار نجومی

RELEASE: 08-200 .NASA Awards Space Radiobiology Research Grants

WASHINGTON -- NASA's Human Research Program will fund nine proposals from six states to investigate questions about the affects of space radiation on human explorers. The selected proposals from researchers in California, Colorado, Georgia, Maryland, New York and Utah have a total value of approximately $13 million.
The ground-based studies will address the impact of space radiation on astronaut health. Research areas will include risk predictions for cancer and models for potential damage to the central nervous system.
"The proposals funded this year using advanced biomedical approaches will lead to a much deeper understanding than has been possible in the past on how celestial radiation differs from radiation on Earth," said Francis A. Cucinotta, chief scientist for the Human Research Program at NASA's Johnson Space Center in Houston.
The Human Research Program provides knowledge and technologies to improve human health during space exploration and identifies possible countermeasures for known problems. The program quantifies crew health and performance risks during spaceflight and develops strategies that mission planners and system developers can use to monitor and mitigate health risks.
The nine projects were selected from 60 proposals that were reviewed by scientific and technical experts from academia and government laboratories. A complete

Directors: Grey Hautaluoma
Headquarters, Washington
202-358-0668
grey.hautaluoma-1@nasa.gov
William Jeffs
Johnson Space Center, Houston
281-483-5111
william.p.jeffs@nasa.gov

List of the selected proposals is available at:

http://www.nasa.gov/directorates/esmd/acd/radiobiology_study.html

For information about NASA and agency programs, visit:

http://www.nasa.gov

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:14 قبل از ظهر  توسط کامران  | 

اخبار نجومی

RELEASE: 08-206 .Prizes Awarded At NASA's General Aviation Technology Challenge

WASHINGTON -- NASA awarded a total of $97,000 in prizes at the 2008 General Aviation Technology Challenge. The challenge asked competitors to demonstrate innovations that would lead to aircraft that are safer, more affordable, and easier to fly and also have less of a negative impact on the environment and on the communities that surround airports.
The challenge was managed by the Comparative Aircraft Flight Efficiency, or CAFE, Foundation at the Sonoma County Airport in Santa Rosa, Calif., from Aug. 4 through Aug. 10. All competitors had experimental licenses, as required by the Federal Aviation Administration, since aircraft were modified with new innovations for this competition.
The largest prize awarded was $50,000 for the aircraft with the overall best safety features which went to Vance Turner's team from El Dorado Hills, Calif., flying a modified Pipistrel Virus. The Pipistrel team also won prizes for the shortest takeoff distance and best angle of climb. Turner's team shared the lowest cabin noise prize with a team led by John Dunham of Carson City, Nev.
Dunham's team used a customized Lambada aircraft to win $20,000 for the community noise prize. Pilot Bob Basham, flying a Flight Design-CT, won a prize of $3,750 for best glide ratio at 100 mph.
a $50,000 Green Aviation Prize purse was offered, but no team was able to exceed the minimum requirement of 30 miles per gallon, although all the competitors came The General Aviation Technology Challenge is one of seven NASA technology prize competitions. The prize program began in 2005 and is known as Centennial Challenges, in recognition of the centennial of powered flight. In keeping with the spirit of the Wright Brothers and other American innovators, the Centennial Challenge prizes are offered to independent inventors who work without government support, including small businesses, student groups and individuals.
The prize competitions are targeted at a range of technical challenges that support NASA's missions in aeronautics and space. The goal is to encourage novel solutions from non-traditional sources. For the program, NASA provides the prize money while each of the competitions is managed by an independent allied organization at no cost to NASA. NASA's Innovative Partnerships Program Office manages the Centennial Challenges program.
Director: Sonja Alexander
Headquarters, Washington
202-358-1761
sonja.r.alexander@nasa.gov


For more information on the program, visit:

http://centennialchallenges.nasa.gov

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:14 قبل از ظهر  توسط کامران  | 

اخبار نجومی

MEDIA ADVISORY: 08-203 .NASA 'Inspire' Interns Work To Become Future Explorers And Innovators



WASHINGTON -- In the coming weeks, high school and college students across the country will soon be heading back to school. A fortunate few will share some unique experiences. They will tell how they were at NASA for two months conducting cutting-edge research and working to send American astronauts to the moon and beyond.
This summer, more than 150 students from 23 states and Puerto Rico took part in a new NASA education project called "INSPIRE" -- the Interdisciplinary National Science Project Incorporating Research and Education Experience. The internships are located at each of NASA's 10 field centers.
"INSPIRE gives students, parents and teachers a mechanism for interacting with one another," said Steve Chance, INSPIRE project manager. "They ask questions, share knowledge and build 'a community of practice' that NASA hopes will lead them to pursue careers in fields critical to NASA and the nation."
The INSPIRE project is open to students in grades 9-12, including high school graduates preparing for their first year of college who are U.S. citizens and have at least an overall 2.5 grade point average or better on a 4.0 scale.
Interested students should first apply for entry into the INSPIRE online community, NASA's education resource for students, parents and teachers. Once selected for INSPIRE, they may compete for internships and other unique summer opportunities.
To participate in the summer opportunities, students must achieve a minimum 3.0 grade point average, submit an essay about their interest in NASA and the space program, and include two letters of recommendation from teachers or adult mentors with their application. NASA education officials assess all submissions, seeking candidates who demonstrate teamwork, leadership potential and career aspirations in fields related to math, science and engineering.
Through the INSPIRE online community, NASA provides resources and activities that help parents champion their students' goals. NASA also contributes to classrooms, providing teaching modules and resources designed to capture students' imaginations and enhance their technical and problem-solving skills.
Director: Sonja Alexander
Headquarters, Washington
202-358-1761
sonja.r.alexander@nasa.gov


For information about INSPIRE and how to participate in the program, visit:

www.nasa.gov/audience/forstudents/postsecondary/programs/INSPIRE_Project.html


For more information about NASA education programs, visit:

www.nasa.gov/education

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:14 قبل از ظهر  توسط کامران  | 

اخبار نجومی


MEDIA ADVISORY: M08-148 NASA to Broadcast Historical Highlights in High Definition

WASHINGTON - NASA Television will broadcast a special high definition (HDTV) feed of two hours of highlights from America's human spaceflight history as the agency celebrates its 50th anniversary.
The NASA HD highlights will be broadcast on Friday, Aug. 8, Monday, Aug. 11, and Tuesday, Aug. 12, from 9 to 11 a.m. EDT on a special feed from NASA TV. The highlights also will be broadcast on standard definition on NASA TV's media channel.
The broadcast will include material drawn from more than 150 hours of historical film footage that was converted to HDTV under collaboration between The Discovery Channel and NASA. Much of the converted footage was used in production of The Discovery Channel's acclaimed series, "When We Left Earth: The NASA Missions."
directors: John Yembrick
Headquarters, Washington
202-358-0602
john.yembrick-1@nasa.gov
James Hartsfield
Johnson Space Center, Houston
281-483-5111
james.a.hartsfield@nasa.gov


For technical information on how to receive the special broadcast in high definition, and for NASA TV streaming video, downlink and scheduling information, visit:

http://www.nasa.gov/ntv

For more information about NASA and its programs, visit:

http://www.nasa.gov

 

+ نوشته شده در  پنجشنبه بیست و چهارم مرداد 1387ساعت 11:13 قبل از ظهر  توسط کامران  |