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. 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: 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! 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. 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. We hope we have now managed to convince you to continue with this online C course and hopefully in time become a confident C programmer.Introduction to C Programming
Objectives
Why use C?
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:
A Brief History of C
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.
Tuesday, March 25, 2008
Introduction to C Programming
Posted by
techgeek
at
12:12 PM
4
comments
Running C Programs
Running C Programs
Introduction to C.
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.
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
Posted by
techgeek
at
12:00 PM
0
comments
Structure of C Programs
Having completed this section you should know about: The use of most of this set of characters will be discussed C makes use of only 32 keywords Note the use of the bracket set () and {}. () are used in A very common mistake made by everyone, who is new to the C It would be very tedious, for all of us, if every time we All programs you will write will need to communicate to the I have already mentioned that C is a free format language and All pre-processor directives begin with a # and the must start #include <stdio.h> Note the use of the angle brackets (< and >) around the #include "stdio.h" The double quotes indicate that the current working directory NOTE: just to keep you on your toes - pre-processor Structure of C Programs
Objectives
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:
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.
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
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.
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 href="cccckey.html">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.
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.
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.
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.
in the first column. The commonest directive to all C programs
is:
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:
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.
statements, such as include, DO NOT use
semi-colons as delimiters! But don't forget the # must be in the 1st coloumn
Posted by
techgeek
at
12:11 AM
0
comments
Your First Program
Having read this section you should have an understanding Now that you've seen the compiler in action it's time for you Yes - it's the ubiquitous "Hello World" program. All The program is a short one, to say the least. Here it is: The first line is the standard start for all C programs - Notice the semicolon marking the end of the instruction. You If you're puzzled about why the curly brackets are on separate main(){printf("Hello World\n");} but this is unusual. The printf function does what its name suggest OK, that's enough explanation of our first program! Type it in Hello World In C, the start of a comment is signalled by the /* This is a comment. */ Comments can extend over several lines and can go anywhere Your First Program
Objectives
of:
screen.
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.
your first program is going to do is print the message "Hello
World" on the screen.#include <stdio.h>
main()
{
printf("Hello World\n");
}
[program]
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.
might as well get into the habit of ending every C
instruction with a semicolon - it will save you a lot 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.
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:
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.
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: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.
/* character pair. A comment is ended by
*/. For example, this is a syntactically correct C comment:
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.
Posted by
techgeek
at
12:10 AM
0
comments
Data Types
Having read this section you should be able to: Now we have to start looking into the details of the C So if you haven't programmed before, you need to take the rest The first thing you need to know is that you can create In this section we are only going to be discussing There are five basic data types associated with variables: One of the confusing things about the C language is Note: all C's variables must begin with a int variable name; For example: int a; declares that you want to create an int To assign a value to our integer variable we would use the a=10; The C programming language uses the "=" character for a=a+10; will get mathematicians blowing fuses! This statement should For example: float total; double sum; To assign a numerical value to our floating point and double total=0.0; sum=12.50; To declare a variable of type character we use the keyword For example: char c; To assign, or store, a character value in a c='A' Notice that you can only store a single character in a name = value; For example: a=10; stores the value 10 in the int Consider four very simple mathematical operations: add, a=10/3 The answer depends upon how a was declared. If Two points to note from the above 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 Note: To avoid confusion use brackets. The a=10.0 + (2.0 * 5.0) - (6.0 / 2.0) You can freely mix int, float This is very reasonable but more surprising is the fact that int a, b, c; declares three integers: a, b Here is an example program that includes some of the concepts int i=1; sets the int variable to one as soon as it's Data Types
Objectives
types
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.
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!
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.
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.
fractional part.
examine closely in later sections.
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!
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:
variable called a.
following C statement:
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:
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.
precision and a range of about 1.E-36 to 1.E+36. A float takes
four bytes to store.
precision and a range of about 1.E-303 to 1.E+303. A double takes
eight bytes to store.
precision variables we would use the following C
statement: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.
char. - A single character stored in one
byte.
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:
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:
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.
subtract, multiply and divide. Let us see how C would use
these operations on two float variables a and
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?
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.
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:
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.
following are two different calculations:
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
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.
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 an
integer variable. You can declare any number of variables of the
same type with a single statement. For example:
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.
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 <stdio.h>
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:
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:
significant
Posted by
techgeek
at
12:09 AM
0
comments
Input and Output Functions
Having read this section you should have a clearer idea of a=100; stores 100 in the variable a each time you run scanf("%d",&a); For the moment don't worry about what the %d a=100; When the program reaches the scanf statement The final missing piece in the jigsaw is using the printf("The value stored in a is %d",a); The %d, both in the case of Note: the scanf function does not The only problem with this is that C programmers have a One attempt to make C a more uniform language is the It is now time to look at exactly how scanf The original C specification did not include commands where the ... means you can carry on writing a list of printf("Hello World"); only has a control string and, as this contains no printf("Total = %d",total); will print Total = and then the value passed If you are familiar other programming languages then you may printf("Total = %d",total); looks like the sort of output command you might have used PRINT "Total = ",total but the C view of output is at a lower level than you The reason for this is twofold. This is all a bit technical, but that's in the nature of C. You can ignore these details as long as you remember You can also add an 'l' in front of a Each specifier can be preceded by a modifier flag width.precision The flag can be any of: For example, %10.3f will display the The specifier %-1Od will display an The only complexity is the use of the # Strings will be discussed later but for now remember: if you For example: printf("%s,Hello") will print Hello, printf("%25s ,Hello") will print 25 characters with Hello right printf("%25.3s,Hello") will print Hello right justified in a group of Also notice that it is fine to pass a constant value to Finally there are the control codes: scanf(control In this case the control string The most obvious is that scanf has to change To understand this fully you will have to wait until we have The second difference is that the control The rule is that scanf processes the control 3 4 5 or and it doesn't matter how many spaces are included between scanf("%d %d",&i,&j); will read in two integer values into i and The only exception to this rule is the %c For example: scanf("%lOd",&i) would use at most the first ten digits typed as the new value There is one main problem with scanf function The point is that as far as standard C goes simple I/O Well you don't have to worry too much because although C may not define them as standard, all Let's write a program that adds two numbers together and The program is a bit more complicated than you might expect, [program] The first instruction declares three integer variables: Type the program in, compile it and link it and the result Input and Output
FunctionsObjectives
one of C's: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:
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:
or the &a means - concentrate on the difference
between this and:
it pauses to give the user time to type something on the keyboard
and continues only when users press <Enter>, or
<Return>, 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!
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:
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.
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.
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?"
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 frequently really are
standard on all implementations. In particular the I/O functions
vary very little.
and printf work and what they can do - you might
be surprised at just how complex they really are!
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...)
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:
% 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:
by >total as a decimal integer.
feel happy about the printf function because
something like:
before. For example, in BASIC you would write:
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.
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.
difference ints, floats and
doubles use a different binary representation and
%d expects the bit pattern to be a simple signed
binary integer.
two important facts:
of variable to be displayed as well as the format in which that
the value should be displayed;
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.
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 valueFormatting 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.
which determines how the value will be printed. The most general
modifier is of the form: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.
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!)
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.
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
%#f or
%#e ensures decimal point is printed
%#g displays trailing zeros
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.
justified and
25 spaces.
printf as in
printf("%s,Hello").
\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:
string,variable,variable,...)
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 values stored in the parts of computers memory that is
associated with parameters (variables).
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.)
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.
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
items. For example:
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.
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 i.
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.
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?
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?
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.
but only because of the need to let the user know what is
happening:
#include <stdio.h>
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);
}
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.
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.
Posted by
techgeek
at
12:08 AM
0
comments
Conditional Execution
Conditional
Execution
Objectives
Having read this section you should be able to:
- Program control with if ,
if-else and switch
structures - 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 <stdio.h>
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a<b) printf("\n\nFirst number is less than second\n\n");
if (b<a) printf("Second number is less than first\n\n");
} while (a < 999);
}
[program]
Here's another program using an if keyword and
a compound statement or a block:
#include <stdio.h>
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a<b) {
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 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 <stdio.h>
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 <stdio.h>
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 <stdio.h>
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 <stdio.h>
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]
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.
Read more!
Posted by
techgeek
at
12:07 AM
0
comments
Control Loops
Input and Output
Functions
Objectives
Having read this section you should have a clearer idea of
one of C's:
- input functions, called scanf
- 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 <Enter>, or
<Return>, 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 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.
- 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. - 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:
- The specifier following % indicates the type
of variable to be displayed as well as the format in which that
the value should be displayed; - 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
%#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 <stdio.h>
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.
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.
Posted by
techgeek
at
12:07 AM
0
comments