Programming in C – a shortish tutorial by Toto

Programming in C – a shortish tutorial by Toto

Contents

  1. Introduction
  2. Keywords
  3. A Simple C Program – Printing a Line of Text
  4. Formatting output using printf
  5. Getting Input from the Keyboard
  6. Variables
  7. The if Control Structure
  8. Header files
  9. Simple Arithmetic
  10. Data Types
  11. Strings
  12. Repetition using while, do-while & for
  13. Good Programming Practices
  14. Common Errors
  15. Exercises
  16. Acknowledgements

Introduction

Welcome to this shortish tutorial on learning the Windows based C programming language. This document is available on the web in HTML & Word 97 formats. The latest version can be found at http://www.xploiter.com/c.shtml

We will be covering the basics of this extremely powerful language here so I assume that you are either new to programming or just want to refresh your memory [be it RAM or ROM ;o)]. Dont worry if you don’t know anything about programming as a willing mind is all that is required in order to use this tutorial.

I am assuming that you have a C compiler, i.e. a program that will convert the source code that you write into your actual program & that you know how to start it up & enter code.

If you do not have a compiler, you really need to get hold of one before you go any further. One’s to look out for are listed below: –

    • Borland Turbo C/C++ Ver 3.1 – good dos based compiler complete with Integrated Design Environment (IDE)
    • Borland C/C++ Ver 4.52 or even if you are flush Ver 5.0 ( http://www.inprise.com )
    • DJGPP – A freeware C/C++ compiler available from http://brennan.home.ml.org/djgpp/

Check out the links on the website for further compilers & locations where they can be obtained.

For the examples in this tutorial, I will be using Borland C/C++ Ver 4.52. All the C code will be shown in blue text.

Keywords

Keywords are words that have a special meaning in the C language. They may not be used for any other purpose with the result that if you do, your compiler will throw up errors. The following table shows words that are reserved: –

auto break case char const Continue default do
double else enum extern float For goto if
int long register return short Signed sizeof static
struct switch typedef union unsigned Void volatile while

Notes

    1. These keywords are always in lower case (i. e. small letters).
    2. Some compilers may use additional keywords – check the manual for details of these.

A Simple C Program – Printing a Line of Text

OK now down to some serious coding – well maybe not serious but just to get you going, type in the following code to your compiler: –

/* Our 1st program in C */

{

printf(“Welcome to my 1st C program”);

return 0;

}

Now compile the code (ctrl + F9 in Borland) and see what happens.

Nothing! Well not quite. You should see that an error has been generated by the compiler saying something similar to : –

Compiling NONAME00.CPP:

Error NONAME00.CPP 3: Declaration terminated incorrectly

Now without going into the deep & meaningful reasons why this is, the simple answer is that there are two vital things missing. You need to ‘include’ your library files, in this case the standard input/output and also you must have a function called ‘main‘. Add the following lines to the top of the code as shown below & recompile.

#include <stdio.h>

main()

You should now have: –

/* Our 1st program in C */

#include <stdio.h> //include header files

main () //main function

{

printf(“Welcome to my 1st C program”); //print output to screen

return 0; //terminate program properly

}

Congratulations! You should now have a DOS window appear displaying the output of your program.

Welcome to C.

Now we can break this program down to see what is happening. We will take it one line at a time.

Line 1 – /* Our 1st program in C */

This is called a comment line and is basically there to inform you what the code does. The line begins with /* & ends with */ indicating that the line is a comment. This can be spread over many lines when you have a lot of comments to make. Another comment identifier is // and this one is used to comment out one line. In this example I have gone a bit over the top simply to demonstrate their usage.

Line 2 – #include <stdio.h>

This is a directive to the C preprocessor. Lines that begin with # are processed by the preprocessor before the program is compiled. This particular line tells the preprocessor to include the contents of the Standard Input/Output Header File stdio.h in the program.

This file contains information & declarations used by the compiler when compiling standard input/output library functions such as printf. Header files will be explained more later in the tutorial.

Line 3 – main ()

This line must be present in every C program in order for it to compile successfully. The parentheses after main indicate that main is a program building block called a function. Every C program begins executing at the function main.

Line 4 – {

This left brace { , must begin the body of every function. A corresponding right brace } , must end each function. This pair of braces & the code contained inside them is called a block.

Line 5 – printf(“Welcome to my 1st C program”);

This line tells the computer to perform an action i.e. in this case to print a line of text to the screen. This is known as a statement. Notice that the entire line is ended by a semi-colon ; which is known as a statement terminator. Every statement must terminate with a ;.

Line 6 – return 0;

This line just returns a value of zero to the operating system to say the program has ended successfully. Although this line is not necessary for the program to compile, a compiler warning error would crop up saying something like: –

Warning NONAME00.CPP 9: Function should return a value in function main()

Line 7 – }

This closes the function body as described earlier.

That’s it for your 1st C program. Now you can experiment with your own text.

Formatting Output Using printf

The printf command can include detailed instructions regarding how a particular data item should be displayed.

These layout indicators are included within the formatting string – between the % sign and the conversion character (i.e. c, d, f, etc.) for the relevant item.

Size of Field for Display

A minimum field width can be specified as shown in the following examples.

e.g.1 printf ( “%10d”, number) ; //will display the contents of number within a field ten spaces wide. This is useful for setting data out in columns. Note that if the field specified is not large enough for the value displayed – then a larger field will be used automatically.

A variable field width may be specified by including an asterisk (* ) instead of a numeric value. The variable name holding the actual width should be included in the argument list immediately after the data item to which it relates.

e.g.2 printf ( “%*d”, number, field_width_for_number); //will display the contents of number within a field whose width is governed by the value stored in field_width_for_number.

Precision for Floating Point Numbers

The precision required for display can be specified as a decimal point followed by a number.

e.g. 3 printf ( ” %.2f “, wage ); //displays wage showing two figures after the decimal point.

Again an asterisk * may be used in the formatting string to tell the command to refer to a variable named in the argument list for the precision.

Precision may also be applied to a string – in which case it is used to limit the number of characters displayed from the string.

e.g.4 printf( ” %.5 “, name ) ; //will display the first 5 characters of the string name.

Left Alignment

A hyphen (-) included in the formatting string will ensure that the corresponding data item will be aligned on the left of its display field. This is important where a minimum field width has been specified which is larger than the data item; if left alignment is not specified the item will be right justified.

e.g. 5 printf ( “%-10d”, number) ; //will display the contents of the variable number aligned to the left of its ten space field.

Any combination of these formatting indicators may be used – but must be in the order: left alignment field-size precision.

e.g.6 printf ( “%-10.2f”, wage); //will display the contents of wage, left aligned within a 1 (l space field, showing two digits after the decimal point.

The following table assumes & describes the techniques discussed above in a practical format:

int num1 = 200;

char name[9] = “Anderson”

float num2 = 2.345678;

Instruction Output on Screen
Printf(“%dn”, num1); 200.00
Printf(“%10dn”, num1); 200
Printf(“%-10dn”, num1); 200.00
Printf(“%fn”, num2); 2.35
Printf(“%10fn”, num2); 2.35
Printf(“%-10fn”, num2); 2.35
Printf(“%.4fn”, num2); 2.35
Printf(“%10.4fn”, num2); 2.35
Printf(“%-10.4fn”, num2); 2.35
printf(“%sn”, name); Anderson
printf(“%10sn”, name); Anderson
printf(“%-10sn”, name); Anderson
printf(“%.2sn”, name); An
printf(“%10.2sn”, name); An

Using appropriate formatting instructions is particularly important when there are several data items to be arranged in columns.

e.g.7 printf(“%-10s %10f %10fn”, name,salary,bonus); //will display the data neatly set out in columns:

Getting Input from the Keyboard

When we write a C program, normally we wish to get some sort of input from the user e.g. Name, Age, Sex etc. In C, the scanf function is used for this purpose.

/* a program to get input from a user and display it on screen*/

#include <stdio.h>

#include <conio.h>

int age;

main()

{

printf(“Please enter your age: “);

scanf(“%d”, &age);

printf(“Hello, you are %d years old.”, age);

getch();

return 0;

}

OK, you should be able to follow this program quite easily. Basically all it does is to print a message on the screen asking for your age, this is stored in a variable called age & then the result is printed back to the screen.

There are only two new terms used in this program & are explained below: –

int age; In order to store the value that the user types into the program, a variable must be allocated for it. Variables will be covered in more detail in the next chapter but basically age is the variables name & int is its type identifier i.e. int = integer or a number. We can also have char name to store characters & so on.

scanf(“%d”, &age); scanf is a function that constantly scans the keyboard for user input 7 then stores it in the variable age. The %d works alongside int in that it gets the input as a decimal figure. The & (ampersand) character is called the address operator and must be included with the variable name as shown in order for the program to work. The ampersand, when combined with the variable name tells scanf the location in memory in which the variable age is stored.

printf(“Hello, you are %d years old.”, age); To print the value stored in the variable age, again we use %d inside the printf statement. We then need to tell the statement which variable to pull the data from, in this case age.

That’s all there is to it. Now you should be able to understand how to print simple lines of text to the screen & how to get the users input & then display that on the screen.

Variables

A computer has to store any data it is about to use in spaces in its memory. Because the data placed in these memory locations will vary each time the program is used – they are known as variables.

e.g. a program written to add two numbers together and display a total would need to use three memory spaces for the data – one for each of the numbers used (including the answer).

When you are writing a program – you have to tell the machine in advance what the variables will be. This is so that the program can reserve a set number of spaces in memory along with the type of data that a memory space will need to hold e.g. integer data, character data, floating point data etc.

You also have to give each space a name. This is done by listing the names near the beginning of the program. This was demonstrated in the previous programming example.

e.g. 1 int number, number2, answer ; // sets aside three spaces in memory to hold integer (i.e. whole number) data – and gives each space a label.

e.g. 2 char mathsgrade, englishgrade, itgrade; // sets aside three spaces – each one capable of holding a single character – such as a letter of the alphabet.

e.g. 3 float roomlength, roomwidth, roomheight; //sets aside three spaces capable of storing floating-point numbers (i.e. numbers containing fractions – e.g. 5.25).

Example:

Lets assume that we have two variables, integer1 & integer 2 & we wish to work out the sum of the two. Using the statement scanf(“%d”, &integer1); we can get the number that the user types into the program. This would of course be stored in the variable integer1.

We can then do the same again for the second variable, integer2. Now we have two figures, both stored in memory in their relevant variables that we can now manipulate to work out the total. This can be done as follows: –

printf(“%d + %d = %d”), interger1, integer2, integer1 + integer2);

The final program would look like this: –

/* a program to add tow numbers together*/

#include <stdio.h>

#include <conio.h>

int integer1, integer2;

main()

{

printf(“Please a number: “);

scanf(“%d”, &integer1);

printf(“Please another number: “);

scanf(“%d”, &integer2);

printf(“%d + %d = %d”, integer1, integer2, integer1 + integer2);

getch();

return 0;

}

The if Control Structure

Using if .. else

Sometimes you might wish to program the computer to take one course of action in a certain case – and a different course of action in another case. To do this the if .. else statement is used.

For example, you may wish the computer to display “PASS” if a student gets 50 or more in an exam, and “FAIL” if the mark is less than 50 – this could be written as follows:

e.g.1 if ( studentMark >= 50 )

printf(“PASS”);

else

printf(“FAIL”);

Note

  1. Brackets are placed around the condition.
  2. A semi-colon finishes each statement.

Sometimes the else is not required:

e.g. 2 i f (studentMark >= 80 )

printf(“You have won a prize”); //(i.e. anyone who gets less than 80 or less will not get a prize – so no action is needed.)The following Relational Operators may be used with the if .. else statement:

> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== equal to
!= is not equal to

Do not confuse the relational operator == (which compares two items to check whether they are equal) with the assignment operator = (which makes a variable equal some value).

Other ways of using the if .. else statement are described below.

A compound if .. else may be used where there are several possible options.

e.g.1 if (mark >= 85)

printf(“Distinctionn”);

else if (mark >= 65)

printf(“Meritn”);

else if (mark >= 50)

printf(“Passn”);

else

printf(“Failn”);

printf(“Your mark is %d n”, mark);

Each condition will be tested in turn until one is found to be true – whereupon the relevant command will be carried out, and then control will drop to the statement after the group of if .. else statements (in this case the instruction to display the actual mark).

e.g.2 if (age >= 30)

if (length_of_service >= 10)

bonus = 5000 ;

else

bonus = 3000;

else

if (length_of_service >= 10

bonus = 4000;

else

bonus = 1000;

In this case, employees are divided first into two groups according to age Once this has been, done, then their bonus depends on length of service. So for example, someone of 35 with 5 years service with the firm gets a bonus of 3000.

Groups of statements enclosed in braces { } (including further if.. else statements) may be carried out following if or else commands.

e.g.1 if (mark >= 80 )

{

printf(“DISTINCTION n”);

printf(“NAME PRIZE-BOOK REQUIRED”);

scanf(” %s”, prize);

}

else

{

if (mark >= 40)

printf(“PASSn”);

else

printf(“FAILn”);

}

printf(“%dn”, mark);

For any mark of 80 or over, the computer will display “Distinction” and ask what prize the student would like; marks lower than this are divided into passes and fails. The statement printf(“%d”, mark) is outside the if . else groups of statements and so applies to all students and every mark is printed.

e.g.2 if (mark >= 40 )

{

printf(“PASS “);

if (mark >= 70)

printf(“GRADE A”);

else

printf(“GRADE B”);

}

else

printf(“FAIL”);

Header files

What is a header file you may ask? Well header files, also called include files, provide function prototype declarations for library functions that are used in your programs.

Data types and symbolic constants used with the library functions are also defined in them, along with global variables defined by Borland C++ and by the library functions. The Borland C++ library follows the ANSI C standard on names of header files and their contents.

The following table was taken from the Borland C/C++ help file for Ver 4.52.

Note: The middle column indicates C++ header files and header files defined by ANSI C.

Standard Library Header File Defined by ANSI C? Explanation
alloc.h Declares memory-management functions (allocation, deallocation, and so on).
assert.h ANSI C Defines the assert debugging macro.
bcd.h C++ Declares the C++ class bcd and the overloaded operators for bcd and bcd math functions.
bios.h Declares various functions used in calling IBM-PC ROM BIOS routines.
bwcc.h Defines the Borland Windows Custom Control interface.
checks.h C++ Defines the class diagnostic macros.
complex.h C++ Declares the C++ complex math functions.
conio.h Declares various functions used in calling the operating system console I/O routines.
constrea.h C++ Defines the conbuf and constream classes.
cstring.h C++ Defines the string classes.
ctype.h ANSI C Contains information used by the character classification and character conversion macros (such as isalpha and toascii).
date.h C++ Defines the date class.
_defs.h Defines the calling conventions for different application types and memory models.
dir.h Contains structures, macros, and functions for working with directories and path names.
direct.h Defines structures, macros, and functions for dealing with directories and path names.
dirent.h Declares functions and structures for POSIX directory operations.
dos.h Defines various constants and gives declarations needed for DOS and 8086-specific calls.
errno.h ANSI C Defines constant mnemonics for the error codes.
except.h C++ Declares the exception-handling classes and functions.
excpt.h Declares C structured exception support.
fcntl.h Defines symbolic constants used in connection with the library routine open.
file.h C++ Defines the file class.
float.h ANSI C Contains parameters for floating-point routines.
fstream.h C++ Declares the C++ stream classes that support file input and output.
generic.h C++ Contains macros for generic class declarations.
io.h Contains structures and declarations for low-level input/output routines.
iomanip.h C++ Declares the C++ streams I/O manipulators and contains templates for creating parameterized manipulators.
Iostream.h C++ Declares the basic C++ streams (I/O) routines.
limits.h ANSI C Contains environmental parameters, information about compile-time limitations, and ranges of integral quantities.
locale.h ANSI C Declares functions that provide country- and language-specific information.
Malloc.h Declares memory-management functions and variables.
math.h ANSI C Declares prototypes for the math functions and math error handlers.
mem.h Declares the memory-manipulation functions. (Many of these are also defined in string.h.)
memory.h Contains memory-manipulation functions.
new.h C++ Access to _new_handler, and set_new_handler.
_nfile.h Defines the maximum number of open files.
_null.h Defines the value of NULL.
process.h Contains structures and declarations for the spawn… and exec… functions.
search.h Declares functions for searching and sorting.
setjmp.h ANSI C Declares the functions longjmp and setjmp and defines a type jmp_buf that these functions use.
share.h Defines parameters used in functions that make use of file-sharing.
signal.h ANSI C Defines constants and declarations for use by the signal and raise functions.
stdarg.h ANSI C Defines macros used for reading the argument list in functions declared to accept a variable number of arguments (such as vprintf, vscanf, and so on).
stddef.h ANSI C Defines several common data types and macros.
stdio.h ANSI C Defines types and macros needed for the standard I/O package defined in Kernighan and Ritchie and extended under UNIX System V. Defines the standard I/O predefined streams stdin, stdout, stdprn, and stderr and declares stream-level I/O routines.
stdiostr.h C++ Declares the C++ (version 2.0) stream classes for use with stdio FILE structures. You should use iostream.h for new code.
stdlib.h ANSI C Declares several commonly used routines such as conversion routines and search/sort routines.
string.h ANSI C Declares several string-manipulation and memory-manipulation routines.
strstrea.h C++ Declares the C++ stream classes for use with byte arrays in memory.
syslocking.h Contains definitions for mode parameter of locking function.
sysstat.h Defines symbolic constants used for opening and creating files.
systimeb.h Declares the function ftime and the structure timeb that ftime returns.
systypes.h Declares the type time_t used with time functions.
Thread.h C++ Defines the thread classes.
time.h ANSI C Defines a structure filled in by the time-conversion routines asctime, localtime, and gmtime, and a type used by the routines ctime, difftime, gmtime, localtime, and stime. It also provides prototypes for these routines.
typeinfo.h C++ Declares the run-time type information classes.
utime.h Declares the utime function and the utimbuf struct that it returns.
values.h Defines important constants, including machine dependencies; provided for UNIX System V compatibility.
varargs.h Definitions for accessing parameters in functions that accept a variable number of arguments. Provided for UNIX compatibility; you should use stdarg.h for new code.

Simple Arithmetic

Since we have been at school, we have learnt how to add, multiply, subtract & divide. Now some of us hated mathematics & were & still are useless at it (like me), and there are others that go to bed dreaming of figures (come to think of it that is like me but they are nothing to do with maths ;o)).

Unfortunately, to be a programmer, you have to understand maths, after all you may need to work out the powers of a number input by a user one day! There is just no getting around it.

Thankfully, the maths we will learn to do here is simple & to a degree, C simlifies things for us. The C arithmetic operators are summarised in the following table: –

C Operation Arithmetic Operator Algebraic Expression C Expression
Addition + f + 7 f + 7
Subtraction p – c p – c
Multiplication * bm b * m
Division / x / y x / y
Modulus % r mod s r % s

You may have noticed that there are several types of symbols not used in algebra. The asterisk (*) indicates multiplication, & the percent sign (%) indicates modulus.

Multiplication

Now as you will (or should) know, to multiply a times b in algebra, we would place these single letter variables side by side as in ab. If we were to do this in C, ab would be interpreted as a single two-letter name (or identifier). To get around this problem, in C we would write this simple equation as a * b by using the * operator.

Division

Surprisingly integer division yeilds an integer result! To explain this further, the expression 7 / 4 evaluates to 1. Still puzzled? Basically an integer can only conprise a whole number so rather than the result being 1.75, because this is a floating point value & we can only return an integer value in the expression, everything after the floating point is ignored. The same appies to 17 / 5 which equals 3. Comprendez?

C provides the modulus (%) operator which yields the remainder after integer division. The following program demonstrates this.

/* program to work out the division & modulus of two numbers*/

#include <stdio.h>

int num1, num2, num3, num4; //declare variables

main()

{

num1 = 7; //initialise variables

num2 = 4;

num3 = num1 / num2; //calculate division

printf(“The division 1st -> %d / %d = %dnn”,num1, num2, num3 );

num4 = num1 % num2; //calculate modulus

printf(“Now the modulus -> %d %% %d = %d”,num1, num2, num4 );

return 0;

}

The modulus operator is an integer operator and can only be used with integer operands. The expression x % y yields the remainder after x is divided by y. Thus 7 % 4 yields 3 & 17 % 5 yields 2.

Addition + Subtraction

This is really easy peasy. The form is simply a + b for addition and a – b for subtraction as shown in the table above.

Use straight-line form

When writing arithmetic operators in C, you must use straight-line form i.e. the expression a divided by b would be written in C as a / b but the algebraic notation would express this as :

This is not normally acceptable to compilers although there are some maths packages (Mathcad) that can accept this form.

Parentheses

Parentheses are regularly used in C expressions in a similar way to algebra i.e.

The expression a times the quantity of b + c is written as a * (b + c).

Rules of operator precedence

In C, the arithemtic operators are evaluated in a specific sequence which you can see more clearly in the table below.

Operator(s) Operation(s) Order of Evaluating (Precedence)
( ) Parentheses Evaluated first. If they are nested, the expression in the innermost pair is evaluated first. If they are not nested & there are several of them, they are evaluated left to right.
*, /, or % Multiplication, Division, Modulus Evaluated second. If there are several, they are evaluated left to right.
+ or – Addition or Subtraction Evaluated last. If there are several, they are evaluated left to right.

To explain this table a bit clearer, take the following examples into consideration.

This example calculates the arithmetic mean (average) of five terms, first in algebra & then in C:  –


The parentheses are required because division has a higher precedence than addition.

Data Types

The following tables list the types and summarises the minimum requirements of the ANSI C standard in relation to the data each type will hold for both 16 & 32 bit.

Some systems will improve upon these minima, and the actual ranges, etc., allowed by a particular system – are defined as symbolic constants in the header files limits.h and float.h.

Data Types (32-bit)
Type Length Range
unsigned char 8 bits 0 to 255
Char 8 bits -128 to 127
short int 16 bits -32,768 to 32,767
unsigned int 32 bits 0 to 4,294,967,295
Int 32 bits -2,147,483,648 to 2,147,483,647
unsigned long 32 bits 0 to 4,294,967,295
Enum 16 bits -2,147,483,648 to 2,147,483,647
Long 32 bits -2,147,483,648 to 2,147,483,647
Float 32 bits 3.4 x 10-38 to 3.4 x 10+38
Double 64 bits 1.7 x 10-308 to 1.7 x 10+308
long double 80 bits 3.4 x 10-4932 to 1.1 x 10+4932
near (pointer) 32 bits not applicable
far (pointer) 32 bits not applicable
Data Types (16-bit)
Type Length Range
unsigned char 8 bits 0 to 255
Char 8 bits -128 to 127
Enum 16 bits -32,768 to 32,767
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
Int 16 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
Long 32 bits -2,147,483,648 to 2,147,483,647
Float 32 bits 3.4 x 10-38 to 3.4 x 10+38
Double 64 bits 1.7 x 10-308 to 1.7 x 10+308
long double 80 bits 3.4 x 10-4932 to 1.1 x 10+4932
near (pointer) 16 bits not applicable
far (pointer) 32 bits not applicable

Strings

Many items of data – e.g. names, addresses, etc. – consist of several characters grouped together to form a piece of text. These are known as strings. To allocate space in memory to store a string, it is necessary to specify char as the data type and state how much space is required. In fact, one extra character must be allowed for a special end-of-string marker which is added by the computer.

e.g. 1 char student name [11] ; //allocates enough space to store a ten character student name – together with an end-of-string marker.

To ask the computer to accept a string keyed in by a user, scanf is used with %s to specify that a string will be input.

e.g. 2 scanf ( “%s” , studentname); //instructs the machine to accept a string and then store it as studentname.

Note that NO ampersand (&) is used when scanf is used with %s (unlike %c, %d, %f – as seen previously).

The scanf command assumes that a space, tab or newline character marks the end of the string being keyed in. This means that scanf cannot be used to accept a string of characters which might include spaces (e.g. an address). Where a string may contain a space, the gets (get string) command can be used instead. The gets command takes a newline character as the end of the input string.

e.g. 3 gets (studentname); //will accept any string (including one containing a space) and store it in studentname.

WARNING: In either case, the user should take care to key in no more than the number of characters set aside for the variable – any more may be accepted and stored in memory spaces not allocated, perhaps overwriting important information and even ‘crashing’ the system.

Note, however, that there may be problems’ if gets is carried out at any point in a program after scanf has been used.

To tell the computer to display a string, printf can be used – again with %s to indicate the type of output.

e.g. 4 printf ( “%s” , studentname); //will display the contents of student name.

Repetition using while, do-while & for

Repetition using whileIt is possible to tell the computer to repeat an instruction or a group of instructions as long as a certain condition is true.

e.g. 1. count = 0 ;

while (count < 10)

{

printf(“Hellon”);

count++;

}

This will display “Hello” ten times down the screen. Note that the group of statements which have to be repeated are enclosed in braces { }.

e.g. 2. reply = ‘Y’ ;while (reply != ‘N’)

{printf(“What is your mark out of ten ?n”);
scanf(” %d”, &markOutOfTen);
percentageMark = markOutOfTen * 10;
printf(“Percentage is %dn”, percentageMark);
printf(“Any more marks to be calculated ?n”);
scanf(” %c”, &reply);

}

This will repeatedly allow students to key in their marks-out-of-ten and turn them into percentages – until ‘N’ is typed in reply to “Any more …”.

Note: With a while loop (‘loop’ means ‘repetition’) – the condition for continuing is checked before starting each repetition. It is important to ensure that the variable being checked has a suitable value before starting the loop first of all. Setting the variable to some suitable starting value is called ‘initialising’ it.

Repetition using do .. while

It is sometimes useful to test at the end of a group of instructions, rather than at the beginning, whether or not they should be carried out again. The do .. while command can be used in this case.

e.g.1. do

{printf(“Key in your maths markn”);

scanf(” %d”, &mathsMark);

printf(“Key in your English markn”);

scanf(” %d”, &englishMark);

averageMark = (englishMark + mathsMark)/2;

printf(“Your average is %dn”, averageMark);

printf(“Any more to calculate ?n”);

scanf(” %c”,&carryOn);

}while (carryOn != ‘N’);

The instructions will be carried out once and then repeatedly until the user keys in N. Note that as the test does not come until the end (by which time the user will have keyed in a response), there is no need to initialise the variable carryOn.

e.g.2. count = 1;

do

{printf(“%dn”,count);

count++;

}while (count <= 100);

The computer will display numbers from 1 to 100 down the screen.Repetition using for

If you want a certain part of your program to be repeated a given number of times the for statement is particularly useful as, unlike the while and do .. while commands, it can increment a count automatically.

e.g.1

The computer will repeatedly display “Hello” on the screen – adding 1 to the variable count after each repetition and continuing as long as the condition (count <=10) is true. So the message will be displayed 10 times.

e.g.2 for (number = 0; number <= 100; number +=10)

printf(“%dn”, number);

The variable being used to keep count is incremented by 10 each time – with the result that the numbers 0,10, 20, 30, etc. will be displayed.

To repeat a group of instructions

If you want to make the computer repeat a number of statements – rather than just a single command as in the example above – it is necessary to surround the program lines that are to be repeated with braces { and } – thus creating a block of statements. (This has already been used with while and do .. while in the previous examples.)

e.g.3 for(x = l; x <= 5; x++)

{

printf(“hellon”);

printf(“how are you ?n”);

printf(“Message has appeared %d timesn”,x);

}

Good Programming Practices

  1. Identing your code to make it more readable.
  2. Commenting your code liberally .
  3. Place a space after each comma (,) to make the programs more readable.
  4. Choose meaningfull variable names.
  5. Use underscores in long variable names to make them more readable i.e. this_is_your_age.
  6. Ident the statements in the body of an if structure.
  7. There should be no more than one statement per line.
  8. Use identifiers of 31 or fewer characters. This helps ensure portability and can avoid some subtle programming errors.

Common Errors

  1. Forgetting to terminate a comment line with */ or starting a comment with */.
  2. Typing the name of the output function printf as print in a program.
  3. Using a capital letter where a lower case should be used.
  4. Forgetting one or both of the doble quotes surrounding the format control string of a printf or scanf.
  5. Forgetiing the % in a conversion specification in the format control string of a printf or scanf.
  6. Placing an escape sequence such as n outside the format control string of a printf or scanf.
  7. Confusing the equality operator = with the assignment operator.
  8. Forgetting to terminate a statement with a semi-colon;
  9. An attempt to divide by zero is normally undefined on computer systems & generally results in a fatal error i.e. a crash.

Exercises

The following programs will put into practice some of what you have learnt in this tutorial. To make your program more user friendly display a welcome message only allowing the user to continue once they press any key & esure the program is terminated cleanly.

  1. Write a program that will perform the following tasks:
  1. prompt the user to enter their full name.
  2. prompt the user to enter their age.
  3. display the results on screen.
  1. Display the results of the following sums:
  1. 100 + 100
  2. 200 / 100
  3. 50 X 4
  4. 5.5 / 2.2
  1. Identify what is wrong with the following statements & program listings. There may be more than one error:
  1. printf(hello world);
  2. scanF(“%d), &num);
  3. int num2
  4. #include <stdio.h>
  5. int num;

    main();

    {

    printf(“Please enter a number”);

    scanf(“%d”, &num);

    printf(“your answer is %s”, num);

    return 0;

    }

  6. scanf(“%d”, value);
  7. firstnumber + secondnumber = sumofnumbers
  8. print(“The sum is %dn”, x+y);

Acknowledgements

The information supplied here has been collected from many sources including from my own head!

The repetition & if…else sections were from documents found on the network drives at my local College (Tut Tut) with modest modifications by me to make everything more readable & understandable by all & sundry.

Thanks for reading this tutorial & I hope that it has helped you to understand some of the underlying principles of programming in C.

I would also suggest that you join some of the various newsgroups & mailing lists dedicated to this subject. You will find many thousands of C programmers, many of them full time professionals, willing to help you out. Keep an eye on the website for details.

Regards

Toto

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.