Skip to Main Content or Page Contents

C Programming - Outputting text to the screen

C Programming

Results per page:

Match: any search words all search words

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

Page Contents

Required Code

Exercise 1.

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

Exercise 1. Code explanation main() function

This code does not do anything that the user can see, but it is required in all 'C' programs.

main()
  • Is a special function in C.
  • It is the first function that will be executed.
The braces { }
  • Indicate the start and end of the code for the proceeding function.
  • They are used as a matching pair.
  • They are normally indented to the function.
    • It 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
  • You are restricted to 8 characters for the name.
  • A single . period
  • 3 characters for the extension after the period.
    • c is the extension used for 'C' files
    • cpp is the extension for 'C++' files
The notation for the names used in this course is tXXexYYZ.
  • tXX is the Tutorial number.
  • exYY is the exercise number.
  • Z is a spare character that is usually a letter a-z and usually used for alternative program files, temporary files etc.
Exercise 1.

Type or Copy and paste this code into the 'C' Editor. If you are a T223 student that will be the PFE
main()
      {
	      
      }
Save as t02ex01 compile, link, and run.

The 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

It 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. If this is the case you will be told how to correct this after the next exercise.

| 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. The 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. The screen is the default output.
cprintf( ) writes formatted output to the screen.

In this lesson, I will use cprintf(), in later lessons I will use printf().

main()
      {
	      cprintf("Hello World.\nThis is my\nfirst ' C ' program");
       }
This code should produce the following result.
Hello World.
            This is my
                       first'C' program

Note: the layout of the lines, this is produced by the backslash formatting code for new line \n

Premature closing of Dos Window.

Important Note: It is possible that the DOS window that displays the above result, may close after the program finishes. This depends on the setup of your computer. This can be cured by entering the 2 additional line as follows.

Main()
      {
	      cprintf("Hello World.\nThis 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 World as follows ...

Result 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()
  • Is a function that displays a formatted string on to the screen.
  • Our your code is calling the function and passing all of the contents within the parenthesis ( ) as a parameter.
  • Is a pre written function that is held in a library of functions.
  • The string in the code is
    "Hello World.\nThis is my\nfirst'C' program" 
  • The pair of double quotes enclose the entire string, but are not outputted onto the output screen.
  • The string contains ...
    • The actual text that will be displayed
    • The backslash formatting control code \n
      • This code, \n is used twice.
      • More backslash control codes are shown below in the table.
;(a semicolon)
  • Is used to mark the end of a line of code;
  • Most lines end in a ;
  • There are a few exceptions to this which will be pointed out.
    • Note there is no ; on the end of the
      main()
      line

The line

cprintf("\n\r\n\r\n\rPress the Space bar to Exit.");

\n\r\n\r\n\r
Places 3 blank lines onto the screen.
Further information on \n\r is below.

Press the Space bar to Exit. Is the text that will be displayed. It is an informative message to the user, to inform the user what to do. This 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.

The 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.

White space
The above code could be written as ...

main(){cprintf("Hello World.\nThis is my\nfirst'C' program");cprintf("\n\r\n\r\n\rPress the Space bar to Exit.");getch();}
  • I think that you will agree that the original is far easier to read.
  • This is more noticeable as the code becomes more complicated.
  • White space is ignored by the compiler.
  • As you read different peoples code you will notice how the use of white space varies.
  • If you are studying at a college or university they may have a "white space style" that they require you to follow.

Backslash Format Control Code / Escape sequences.

These are used in 'C' strings and character variables

| Top of Page |

The characters " ' \ ? can sometimes create problems if used by themselves, hence the use of the preceding \ backslash.
Note: I have scattered a few ' in the code examples and solutions to test you

If you require the combined codes \n\r then use them in the order shown


There are many more code that start with the % percent character. These are later in the course.

First Program - Improved

Exercise 3. clrscr() ;
Read all of this exercise before starting it.
In this exercise you are required to improve and change the code you used in exercise 2, as follows
  • Add an additional word, improved, into the string, after my
  • Experiment with the backslash codes so that the output looks like
    Hello World.
    This is my improved
    first'C' program
  • an additional line of code that will clear all the proceeding additional information that you have seen in the output screen. The function that does this follows and will require a ; at the end of the line as follows ...
          clrscr() ;
    • 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 2,
Tip. If 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. You only have to add code to it then.
Main()
      {
	     cprintf("Hello World.\nThis is my\nfirst'C' program");
      }
The above code is your starting point.

Tip. You are asked to do 3 things in this exercise.
  • Therefore do the 3 things as 3 separate steps
  • Do each step separately and make sure the program is working after each step, and before carrying on with the next one.
  • This makes error finding much easier.

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

If the program is not working see if you can work it out before looking at the solution
Go to solution exercise 3.

| Top of Page |

Error Exercises

You 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. In 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.
1
AB
2CL

to display line numbers.
In other editors read the documentation to see if line numbers can be displayed.

TIP: The line number shown is where the compiler discovered there is an error. The 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. You will experience the same error messages time and time again. You 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 3.

main()
      {
      clrscr();
      cprintf("Hello World.\r\n");
      cprintf("This 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.
You will receive an error message similar to the following
Error \path\filename.c linenumber: Statement missing ; in function main
The path is the path to where the file is stored.
The filename is the name of the file that is being used.
The linenumber that C displays is the line in which the compiler discovers the error. This number may not be the line number where the actual error is. It 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.
Note. Other error messages can be returned, depending where the line is with the missing ; The error is then harder to find.

Replace the ;

Exercise 5a. Statement missing }
Now delete the final }
Save, compile, link, and run.
Error \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.
You 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.

This 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. You can guarantee that an error that causes many hours of frustration, will do so again in a week, month or whatever.
You require information such as

  • What caused the error.
  • How to rectify the error.
  • 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

The 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

You can obtain some very unusual results.

| Top of Page |

Times Table Project

You are required to display a times table similar to those you did at school as a child.
The project will be improved as you learn new skills.

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

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


Learn to build up your project in simple stages / steps
  • Each stage being saved compiled, linked, and run.
  • Correct any mistakes and , save compile, link, and run again. Repeat this step if required.
  • When you save you can slightly amend the name of the file, using the 8th spare character, so that you can return to an earlier version if required.
    • The 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. You will soon remember this code. T223 students may like to use their reference manual if required.
  2. Write the code that all programs require, if possible no cheating.
  3. 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.
    7 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.
    1. Add the following line of code. Note you will insert the formatting in the next step
          cprintf("1 x 7= %i" ,1*7) ;
    2. Save as t02ex10b.c compile, link, and run.
    3. Correct any errors. Save, compile, link, and run. Repeat as required.

Code explanation

"1 x 7= %i" If 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. It still requires escape sequence formatting.

%i
  • Is a place holder
    • It shows the place within the string where the result of the calculation will be placed.
    • Compare the position of %i in the code, with the position of the final 7 in the output.
  • Is also another type of formatting code, the i stating the format is for an integer (whole number, i.e. no decimal point.)
  • Much more on % codes later.
,1*7
  • After the end of the string is a comma which is used as a separator.
  • This is followed by the actual calculation 1*7
  • The result of this calculation is placed within the string of the output at the location of the place holder.
  • 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.
Your result should be ...
7 times table 1 x 7=7


Stage 3
  1. Starting with the answer given in solution 10b.
  2. Sort out the formatting. Alter the code to ...
    1. Place the output on separate line
      7 times table
      1 x 7=7
    2. Insert a blank line between these 2 lines.
    3. Insert a few spaces as required.
    4. Save as t02ex10c.c compile, link, and run.
    5. 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 7 =  7
  2. Paste this line twice into the source code.
    1. You should now have 3 identical lines of code, following each other.
    2. Amend the second of these lines to correctly output the 2 times line of the table.
    3. 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. This right alignment is achieved by inserting/ deleting spaces.
      2. 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 /* */
/*  This is an example of a comment */
/* Large comments
   can be spread
  over several lines */

/***********************
  *  This is a comment    *
  *     embellished to        *
  *   make it stand out     *
 *****************************/

With some compilers, but not all you can use a quicker to enter comment.
//  This comment does not need an end marker.
//  It goes as far as the end of the line

Compilers that do not allow this form will create errors if used. The PFE is one of them.

| Top of Page |

Differences between printf( ) and cprintf( )

Most courses on C use the function printf(), the Open University course T223 uses the function cprintf( ), basically the 2 functions produce the same results but there are subtle differences listed in the table below. Table: 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) Translates linefeed characters (\n) into carriage-return/linefeed character pairs (\r\n)
Tab characters (specified by \t) Are not expanded into spaces. Are expanded into spaces.
Return value The number of characters output. On success, returns the number of bytes output.
On error, returns EOF.
Portability DOS, Win32, OS/2 DOS, Win32, OS/2, UNIX, ANSI C, ANSI C++
Note: Do not use this function for Win32s or Win32 GUI applications.  

| Top of Page |

Solutions to Exercises

Solutions to Exercise 3.
main()
      {
      clrscr();
      cprintf("Hello World.\r\nThis is my improved\r\nfirst C program");
      }


The following is an alternative way of achieving the same output.
  • This way is useful if the cprintf() line becomes rather long, and as you will shortly find out more complicated.
  • Note how the \r\n is placed at the end of one of the lines, and at the start of another.
  • When splitting lines up it is usual place the \r\n at either the start or end of a line, but not required.
  • It is usual for the \r\n to be placed at the end of most cprintf() lines.
  • Note. It is the \r\n that places the output onto 3 lines, it is not
main()
      {
      clrscr();
      cprintf("Hello World.\r\n");
      cprintf("This is my improved");
      cprintf("\r\nfirst C program");
      }

Return to exercise 3.



Solutions to Exercise 10a.
Main()
      {
      clrscr();
      cprintf("7 times table") ;
       }

Return to exercise 10.

Solutions to Exercise 10b.
Main()
      {
      clrscr();
      cprintf("7 times table") ;
      cprintf("1 x 7=%i",1*7) ; 
       }

Return to exercise 10.

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

Return to exercise 10.

Solutions to Exercise 10d.
Main()
      {
      clrscr();
 	    cprintf(" 7 times table\r\n\r\n");
	     cprintf(" 1 x 7 =  %i\r\n", 1 * 7) ; 
	     cprintf(" 2 x 7 = %i\r\n", 2 * 7) ; 
	     cprintf("10 x 7 = %i\r\n", 10 * 7) ; 
      }

Return to exercise 10.

 



© tutorials4u.com
HTML Tutorial by John McGuinn.