0% found this document useful (0 votes)
60 views16 pages

Cprintf

' C'books student software Tutorial 2. Outputting text Tutorial 3. Variables Tutorial 5. Controlling program flow in plain English Tutorial 6 Branching and Looping Tutorial 99. Quick reference ASCII Codes Download files how to code your first 'c' program. Updated 15 March 2003.

Uploaded by

Saurabh Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views16 pages

Cprintf

' C'books student software Tutorial 2. Outputting text Tutorial 3. Variables Tutorial 5. Controlling program flow in plain English Tutorial 6 Branching and Looping Tutorial 99. Quick reference ASCII Codes Download files how to code your first 'c' program. Updated 15 March 2003.

Uploaded by

Saurabh Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

T223 C Tutorial 2.

The required code for any of C,s source code and how to Output text to the screen using
C's built in functions.



Up to 80% off
for Students
from Adobe.
PIus FREE
Shipping
Offer
Offer ends 30/9/2009

% 'C' %utoriaI - Outputting text to the
screen
C Home page | ' C ' Books | Student Software | Tutorial 2. Outputting
text | Tutorial 3. Variables | Tutorial 5. Controlling program flow in
plain English |Tutorial 6 Branching & Looping | Tutorial 90.' C ' Error
Messages | Tutorial 99. Quick reference | ASCII Codes | Download
files |

How to code your first C program. Updated 15 March 2003.



Contents
O #equired Code
o main( ) function
o }
O cprintf( )
O Differences between cprintf()and
printf()
O clrscr ( )
O
O hite space
O Times Table Project
O Students on OU course T223 - Warning
re #eference Manual
O irst Program
o Premature closing of Dos indow.
o Backslash format control
codes / Escape sequence
o n
o r
O Error Exercises
O Display of line numbers
O Solutions to Exercises
O Comments

Required Code
Exercise 1.

All ' C ' programs must contain the following code
main()
{

}
E
x
e
r
c
i
s
e

1
.

C
o
d
e

e
x
p
l
a
n
a
t
i
o
n

m
a
i
n
(
)

f
u
n
c
t
i
o
n
%his code does not do anything that the user can see, but it is required in all 'C' programs.

main()
O s a special function in C.
O t is the first function that will be executed.
%he braces }
O ndicate the start and end of the code for the proceeding function.
O %hey are used as a matching pair.
O %hey are normally indented to the function.
o t is easier to check that pairs match if they are vertically aligned.
Enter this code, save as t02ex01 compile, link, and run.
Remember because most free compilers etc. are DOS based when entering file names
O ou are restricted to 8 characters for the name.
O A single . period
O characters for the extension after the period.
o c is the extension used for 'C' files
o cpp is the extension for 'C++' files
%he notation for the names used in this course is tXXex.
O tXX is the %utorial number.
O ex is the exercise number.
O is a spare character that is usually a letter a-z and usually used for alternative program files, temporary
files etc.
Exercise 1.

%ype or Copy and paste this code into the 'C' Editor. f you are a % student that will be the PFE
main()
{

}
Save as t02ex01 compile, link, and run.

%he following style in this course, represents what should be displayed in the resulting output window, which may be a
separate window or the full screen, depending on the setup of DOS files on your computer.
A window should appear that states that the Source file has been successfully
compiled, along with other information
t is possible that the window may close itself automatically, on modern computers this can be so fast that you may
see a quick flicker or nothing at all. f this is the case you will be told how to correct this after the next exercise.
| Top of Page |

Students on OU course %
Students on the open University course may like to use their #eference Manual, in conjunction with this course.
arning. Do not make any notes in this #eference Manual because you are allowed to take it into the
exam.
| Top of Page |

First Program
Exercise 2. cprintf(), formatting
T223 Students will find that the course team use cprintf( ), rather than printf( ). Differences between
cprintf()and printf()
Most programs place text onto the screen to inform the user about something. %he next exercise will show you how
to do this.
printf( ) writes formatted output to the stdout, standard output device such as a screen, a printer a stream, or a
string. %he screen is the default output.
cprintf( ) writes formatted output to the screen.
n this lesson, will use cprintf(), in later lessons will use printf().
main()
{
cprintf("HeIIo WorId.\n%his is my\nfirst ' C ' program");
}
%his code should produce the following result.
ello World.
This is my
first'C' program
ote: the layout of the lines, this is produced by the backslash formatting code n
P
r
e
m
a
t
u
r
e

c
l
o
s
i
n
g

o
f

D
o
s

i
n
d
o
w
.
Important ote: t is possible that the DOS window that displays the above result, may close after the program
finishes. %his depends on the setup of your computer. %his can be cured by entering the additional line as follows.
ain()
{
cprintf("HeIIo WorId.\n%his is my\nfirst ' C ' program");
cprintf("\n\r\n\r\n\rPress the Space bar to Exit.");
getch();
}
Enter this code, save as t02ex02 compile, link, and run.
After several lines of information produced by the compiler, you will see the output of the above code starting
at Hello orld as follows ...
#esult of running Exercise 1 code.

Note that depending on your computers set up this DOS window may be displayed full screen, i.e Just the area with
the black background.
Code explanation
cprintf()
O s a function that displays a formatted string on to the screen.
O Our your code is calling the function cprintf() and passing all of the contents within the parenthesis ( ) as
a parameter.
O s a pre written function that is held in a library of functions.
O %he string in the code is
"Hello World.\nThis is my\nfirst'C' program"
O %he pair of double quotes enclose the entire string, but are not outputted onto the output screen.
O %he string contains ...
o %he actual text that will be displayed
o %he backslash formatting control code n
%his code, n is used twice.
More backslash control codes are shown below in the table.
(a semicolon)
O s used to mark the end of a line of code
O Most lines end in a
O %here are a few exceptions to this which will be pointed out.
o Note there is no on the end of the
main()
line

%he line
cprintf("nrnrnrPress the Space bar to Exit.")
nrnrnr
Places blank lines onto the screen.
Further information on nr is below.
Press the Space bar to Exit. s the text that will be displayed. t is an informative message to the user, to inform
the user what to do. %his is a very important step to include when coding. Please not that the pressing of almost any
key will end the program
Note the position of the cursor.
%he getch() code is expecting a key to be pressed before continuing. Almost any key, but not them all, will work.
Hence the prompt to use the space bar.
Further information on getch() is given in tutorial 7.
hite space
%he above code could be written as ...
main(){cprintf("HeIIo WorId.\n%his is my\nfirst'C' program");cprintf("\n\r\n\r\n\rPress the Space bar to
Exit.");getch();}
O think that you will agree that the original is far easier to read.
O %his is more noticeable as the code becomes more complicated.
O White space is ignored by the compiler.
O As you read different peoples code you will notice how the use of white space varies.
O f you are studying at a college or university they may have a "white space style" that they require you to
follow.
B
a
c
k
s
l
a
s
h

o
r
m
a
t

C
o
n
t
r
o
l

C
o
d
e

/

E
s
c
a
p
e

s
e
q
u
e
n
c
e
s
.
%hese are used in 'C' strings and character variables
| Top of Page |

Table of Backslash ormat Control Code
Code Meaning Code Meaning
b backspace f form feed
n newline r carriage return
t horizontal tab " double quote
' single quote 0 null (string terminator)
backslash v vertical tab
a alert a question mark
%he characters " ' \ ? can sometimes create problems if used by themselves, hence the use of the preceding \
backslash.
ote: have scattered a few ' in the code examples and solutions to test you
f you require the combined codes nr then use them in the order shown

%here are many more code that start with the % percent character. %hese are later in the course.
First Program - Improved
Exercise 3. clrscr()
Read all of this exercise before starting it.
n this exercise you are required to improve and change the code you used in exercise , as follows
O Add an additional word, improved, into the string, after my
O Experiment with the backslash codes so that the output looks like
O ello World.
O This is my improved
first'C' program
O an additional line of code that will clear all the proceeding additional information that you have seen in the
output screen. %he function that does this follows and will require a at the end of the line as follows ...
cIrscr() ;
o Some programmers like to leave a space before the this helps it to be seen more easily, and to
distinguish it from the accidental use of : rather than
Enter into your code from exercise ,
%ip. f the code is not on the screen, load the file t02ex02 into the editor, and immediately save it as t02ex03, this
will save a lot of typing time. ou only have to add code to it then.
ain()
{
cprintf("HeIIo WorId.\n%his is my\nfirst'C' program");
}
%he above code is your starting point.

%ip. ou are asked to do things in this exercise.
O %herefore do the things as separate steps
O Do each step separately and make sure the program is working after each step, and before carrying on with
the next one.
O %his makes error finding much easier.

Enter the code, save as t02ex03 compile, link, and run.

f the program is not working see if you can work it out before looking at the solution
o to solution exercise 3.
| Top of Page |

Error Exercises
ou will experience many error messages when you attempt to compile 'C' programs. Beginners are puzzled by these
messages, because they can not see the error in there code that caused the message. n the next few exercises you
are going to introduce very common errors, which sometimes the compiler will tell you exactly what is wrong.
At other times the message is not very helpful.

Many 'C' editors allow the display of line numbers, if you are using the OU (Open University) PFE (Programmer's File
Editor) click the button marked.
1AB
CL
to display line numbers.
n other editors read the documentation to see if line numbers can be displayed.
TIP: %he line number shown is where the compiler discovered there is an error. %he error may be on that line, often it
is on the line before, or may be several lines before. Experience helps with finding errors. As a beginner and therefore
lacking experience note the next tip.
TIP: Make a list of errors messages, what actually caused the error, and where that error took place in relation to
the line number quoted in the error message. ou will experience the same error messages time and time again. ou
could copy and paste the following list as your starter for your own List of Compiler Error Messages


Exercise 4. Statement missing

Use the code in the alternative solution to exercise .
main()
{
cIrscr();
cprintf("HeIIo WorId.\r\n");
cprintf("%his is my improved");
cprintf("\r\nfirst 'C' program");
}
Copy and paste this code into the editor.
Delete the from the line that clears the screen.
Save as t02ex04 compile, link, and run.
ou will receive an error message similar to the following
rror \path\filename.c linenumber Statement missing
in function main
%he path is the path to where the file is stored.
%he filename is the name of the file that is being used.
%he linenumber that C displays is the line in which the compiler discovers the error. %his number may not be
the line number where the actual error is. t is often in a line after the actual error.

Statement missing is a very explicit message and the error is usually on the end of the previous line.
ote. Other error messages can be returned, depending where the line is with the missing ; %he error is then harder
to find.

Replace the

Exercise 5a. Statement missing }
Now delete the final }
Save, compile, link, and run.
rror \path\filename.c linenumber Statement missing < Compound statement missing
,in function main
Again the message is clear, and again the line number is after the error line.
Replace the } check the program is working correctly.


Exercise 5b. Declaration syntax error
Now delete the }
Save, compile, link, and run.
ou know that you only made 1 error, but there is a list of errors, one for every line after the actual error.
Declaration syntax error.
%his error is not as obvious as the others.
Tip. Printout the list of error messages, provided in Tut. 90. C Error Messages . Add to this list
additional information as you correct your errors. ou can guarantee that an error that causes many hours of
frustration, will do so again in a week, month or whatever.
ou require information such as
O What caused the error.
O How to rectify the error.
O Reference to exercises, chapters, pages etc.
Continue with the following exercises in a similar manner. After you see the error message add to
my/your list of messages.
Correct the error then continue with the next one.

Exercise 6a. Undefined symbol
Delete a start " in one of the strings such as Hello
Multiple error messages returned for a simple single error, look at the first one.
Undefined symbol Hello
%he compiler thinks that Hello is a symbol, you know it is a string, and you can put guess the cause.
Another example see Exercise 7 below
Correct the error then continue with the next one.

Exercise 6a. Unterminated string or character constant.
Delete an end " in one of the strings
Unterminated string or character constant
Easy once you know the meaning.
Correct the error then continue with the next one.

Exercise 7. Undefined symbol
Delete the ( after line that clears the screen.
Undefined symbol 'clrscr'
Correct the error then continue with the next one.

Exercise 8. Linker errors
Misspell some function names to say clrscrn, cprint, mane etc.
There has been Linker errors
Correct the error then continue with the next one.

Exercise 9.
Misspell main

ou can obtain some very unusual results.
| Top of Page |

%imes %abIe Project
ou are required to display a times table similar to those you did at school as a child.
%he project will be improved as you learn new skills.

ou do not have the skill to do this in a few lines of code. ou would need to write code for every line of the table.
%herefore at this stage you are only required to enter a few lines of the table. our output screen should look like this.
times table
1 x =
2 x = 14
10 x = 0

%he table
O should have the columns of numbers right aligned as shown in the proposed output window.
o At this stage this will be achieved by inserting additional spaces where required.
O %he right column that displays the answer is calculated within the program.


Learn to build up your project in simple stages / steps
O Each stage being saved compiled, linked, and run.
O Correct any mistakes and , save compile, link, and run again. Repeat this step if required.
O When you save you can slightly amend the name of the file, using the 8
th
spare character, so that you can
return to an earlier version if required.
o %he earlier versions can be deleted when the project is complete.
| Top of Page |
Exercise 10.

Stage 1
Note that after any of the following steps you may test the code by undertaking steps 5 and 6.
1. Start the project from scratch. If possible attempt to write the code without looking up the
code shown earlier on this page. Only if required look the code up. ou will soon remember this code. %
students may like to use their reference manual if required.
. Write the code that all programs require, if possible no cheating.
. Write the code that will clear the output screen, if possible no cheating.
4. Write the code that will produce the first line of the output, if possible no cheating.
times table
5. Save as t02ex10a.c compile, link, and run.
6. Correct any errors. Save, compile, link, and run. Repeat as required.
7. Go to solution 10a.
Stage 2
1. Starting with the answer given in solution 10a.
i. Add the following line of code. Note you will insert the formatting in the next step
cprintf("1 x 7= %i" ,1*7) ;
ii. Save as t02ex10b.c compile, link, and run.
iii. Correct any errors. Save, compile, link, and run. Repeat as required.
Code explanation
"1 x 7= %i" f you look at the "1 x 7=" leaving out the %i, this is a string and because of the printf it will be
displayed on the screen. t still requires escape sequence formatting.

%i
O s a place holder
o t shows the place within the string where the result of the calculation will be placed.
o Compare the position of %i in the code, with the position of the final 7 in the output.
O s also another type of formatting code, the i stating the format is for an integer (whole number, i.e. no
decimal point.)
O Much more on % codes later.
,1*7
O After the end of the string is a comma which is used as a separator.
O %his is followed by the actual calculation 1*7
O %he result of this calculation is placed within the string of the output at the location of the place holder.
O More than 1 place holder can be used in a string, you will be using additional place holders in the next
lesson.
Go to solution 10a.
our result should be ...
times table 1 x =


Stage 3
1. Starting with the answer given in solution 10b.
. Sort out the formatting. Alter the code to ...
i. Place the output on separate line
ii. times table
1 x =
iii. nsert a blank line between these lines.
iv. nsert a few spaces as required.
v. Save as t02ex10c.c compile, link, and run.
vi. Correct any errors. Save, compile, link, and run. Repeat as required.
Go to solution 10c.
Note how a comment has been entered into this solution. Comments are discussed below in the next section.

Stage 4
1. Copy the line containing the code that outputs the following to the screen
1 x =
. Paste this line twice into the source code.
1. ou should now have identical lines of code, following each other.
. Amend the second of these lines to correctly output the times line of the table.
. Aimed the third of these lines to correctly output the 10 times line of the table.
4. Save as t02ex10d.c compile, link, and run.
5. Correct any errors. Save, compile, link, and run. Repeat as required.
6. Check that the output is vertically aligned with the numbers aligned right.
1. %his right alignment is achieved by inserting/ deleting spaces.
. Later in the course you will see how this can be achieved by using % formatting.
| Top of Page |

Comments
Comments are entered between the opening and closing symbols /* */
* %his is an exampIe of a comment *
* Large comments
can be spread
over severaI Iines *

***********************
* %his is a comment *
* embeIIished to *
* make it stand out *
*****************************

With some compilers, but not all you can use a quicker to enter comment.
%his comment does not need an end marker.
It goes as far as the end of the Iine
Compilers that do not allow this form will create errors if used. %he PFE is one of them.
| Top of Page |
ifferences between printf( ) and cprintf( )
Most courses on C use the function printf(), the Open University course % uses the function cprintf( ), basically the
functions produce the same results but there are subtle differences listed in the table below. %able: Differences
between cprintf() and printf() put device.
cprintf() printf()
include <conio.h> <stdio.h>
Writes formatted
output to
the screen
the screen, a stream, stdout, or a string Standard
output device such as a printer.
linefeed characters
(\n)
Does not translate linefeed
characters (\n) into carriage-
return/linefeed character pairs
(\r\n)
%ranslates linefeed characters (\n) into carriage-
return/linefeed character pairs (\r\n)
%ab characters
(specified by \t)
Are not expanded into spaces. Are expanded into spaces.
Return value %he number of characters output.
On success, returns the number of bytes output.
On error, returns EOF.
Portability DOS, Win, OS/ DOS, Win, OS/, UNX, ANS C, ANS C++
Note:
Do not use this function for Wins
or Win GU applications.

| Top of Page |
SoIutions to Exercises
Solutions to Exercise 3.
main()
{
cIrscr();
cprintf("HeIIo WorId.\r\n%his is my improved\r\nfirst C program");
}


%he following is an alternative way of achieving the same output.
O %his way is useful if the cprintf() line becomes rather long, and as you will shortly find out more complicated.
O Note how the rn is placed at the end of one of the lines, and at the start of another.
O When splitting lines up it is usual place the rn at either the start or end of a line, but not required.
O t is usual for the rn to be placed at the end of most cprintf() lines.
O ote. t is the rn that places the output onto lines, it is not
main()
{
cIrscr();
cprintf("HeIIo WorId.\r\n");
cprintf("%his is my improved");
cprintf("\r\nfirst C program");
}

#eturn to exercise 3.


Solutions to Exercise 10a.
ain()
{
cIrscr();
cprintf("7 times tabIe") ;
}

#eturn to exercise 10.

Solutions to Exercise 10b.
ain()
{
cIrscr();
cprintf("7 times tabIe") ;
cprintf("1 x 7=%i",1*7) ;
}

#eturn to exercise 10.

Solutions to Exercise 10c.
ain()
{
cIrscr();
cprintf("7 times tabIe\r\n\r\n");
cprintf("1 x 7 = %i\r\n", 1 * 7) ; * the spacing between , 1 * 7 is white space *
}

#eturn to exercise 10.

Solutions to Exercise 10d.
ain()
{
cIrscr();
cprintf(" 7 times tabIe\r\n\r\n");
cprintf(" 1 x 7 = %i\r\n", 1 * 7) ;
cprintf(" x 7 = %i\r\n", * 7) ;
cprintf("10 x 7 = %i\r\n", 10 * 7) ;
}

#eturn to exercise 10.
| Top of Page |
More courses for Open University students by John McGuinn.
HTML and eb Design tutorial suitable for Beginers and students of Open University Courses for T171, TT
Smalltalk suitable for Beginers and students of Open University Courses an Object-Oriented
Approach M885
and discontinued Object-oriented courses M878 and M206
Other Sites to Visit
Leeds guide my home town City of Leeds information

#elax in the sun
Benidorm and Costa Blanca ran Canaria Malta and ozo #esorts in Spain Tenerife




Leeds eb Design eb Designers Hosting Domain names eb site Promotion
Leeds my home town
Relax in the sun.
Benidorm Tenerife San Marino apartments to rent
Copyright John G McGuinn 001-0

You might also like