C Programming
A SIMPLE C PROGRAM
The
following program is written in the C programming language.
#include
<stdio.h>
main()
{
printf("Programming
in C is easy.\n");
}
Sample
Program Output
Programming
in C is easy.
_
A NOTE ABOUT C PROGRAMS
In C, lowercase and uppercase characters are very important! All commands in C
must be lowercase. The C programs starting point is identified by the word
main()
This informs the computer as to where the program actually
starts. The brackets that follow the keyword main indicate that there
are no arguments supplied to this program (this will be examined
later on).
The two braces, { and }, signify the begin and end segments
of the program. The purpose of the statement
#include
<stdio.h>
is to allow the use of the printf statement to
provide program output. Text to be displayed by printf() must be
enclosed in double quotes. The program has only one statement
printf("Programming
in C is easy.\n");
printf() is actually a function
(procedure) in C that is used for printing variables and text. Where text
appears in double quotes "", it is printed without
modification. There are some exceptions however. This has to do with the \ and
% characters. These characters are modifier's, and
for the present the \ followed by the n character represents a newline
character. Thus the program prints
Programming
in C is easy.
and the cursor is set to the beginning of the next line. As
we shall see later on, what follows the \ character will determine what is
printed, ie, a tab, clear screen, clear line etc. Another important thing to
remember is that all C statements are terminated by a semi-colon ;
Click here for a
pascal comparison.
Summary of major points so far
program execution begins at main()
keywords are written in lower-case
statements are terminated with a semi-colon
text strings are enclosed in double quotes
C is case sensitive, use lower-case and try not to
capitalise variable names
\n means position the cursor on the beginning of the next
line
printf() can be used to display text to the screen
the curly braces {} define the beginning and end of a
program block
DATA TYPES AND CONSTANTS
The four basic data types are
INTEGER
These are whole numbers, both positive and negative. Unsigned integers
(positive values only) are supported. In addition, there are short and long
integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of
declaring an integer variable called sum is,
int
sum;
sum =
20;
FLOATING POINT
These are numbers which contain fractional parts, both positive and negative.
The keyword used to define float variables is,
float
An example of a float value is 34.12. An example of
declaring a float variable called money is,
float
money;
money =
0.12;
DOUBLE
These are exponetional numbers, both positive and negative. The keyword used to
define double variables is,
double
An example of a double value is 3.0E2. An example of
declaring a double variable called big is,
double
big;
big =
312E+7;
CHARACTER
These are single characters. The keyword used to define character variables is,
char
An example of a character value is the letter A. An
example of declaring a character variable called letter is,
char
letter;
letter =
'A';
Note the assignment of the character A to the
variable letter is done by enclosing the value in single quotes.
Remember the golden rule: Single character - Use single quotes.
Sample program illustrating each data type
#include
< stdio.h >
main()
{
int sum;
float
money;
char letter;
double
pi;
sum
= 10; /* assign integer value
*/
money
= 2.21; /* assign float value */
letter
= 'A'; /* assign character value */
pi
= 2.01E6; /* assign a double value
*/
printf("value
of sum = %d\n", sum );
printf("value
of money = %f\n", money );
printf("value
of letter = %c\n", letter );
printf("value
of pi = %e\n", pi );
}
Sample
program output
value of
sum = 10
value of
money = 2.210000
value of
letter = A
value of
pi = 2.010000e+06
PREPROCESSOR STATEMENTS
The define statement is used to make programs more readable. Consider
the following examples,
#define
TRUE 1 /* Don't use a semi-colon , # must be first character on line
*/
#define
FALSE 0
#define
NULL 0
#define
AND &
#define
OR |
#define
EQUALS ==
game_over
= TRUE;
while(
list_pointer != NULL )
................
Note that preprocessor statements begin with a # symbol,
and are NOT terminated by a semi-colon. Traditionally, preprocessor statements
are listed at the beginning of the source file.
Preprocessor statements are handled by the compiler (or
preprocessor) before the program is actually compiled. All # statements are
processed first, and the symbols (like TRUE) which occur in the C program are
replaced by their value (like 1). Once this substitution has taken place by the
preprocessor, the program is then compiled.
In general, preprocessor constants are written in UPPERCASE.
Click
here for more information of preprocessor statements, including macros.
Class Exercise C4
Use pre-processor statements to replace the following constants
0.312
W
37
LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define
Lets now examine a few examples of using these symbolic constants in our
programs. Consider the following program which defines a constant called
TAX_RATE.
#include
<stdio.h>
#define
TAX_RATE 0.10
main()
{
float
balance;
float
tax;
balance
= 72.10;
tax
= balance * TAX_RATE;
printf("The
tax on %.2f is %.2f\n", balance, tax );
}
The pre-processor first replaces all symbolic constants
before the program is compiled, so after preprocessing the file (and before its
compiled), it now looks like,
#include
<stdio.h>
#define
TAX_RATE 0.10
main()
{
float
balance;
float
tax;
balance
= 72.10;
tax
= balance * 0.10;
printf("The
tax on %.2f is %.2f\n", balance, tax );
}
YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTS
Considering the above program as an example, look at the changes we have made
below. We have added a statement which tries to change the TAX_RATE to a new
value.
#include
<stdio.h>
#define
TAX_RATE 0.10
main()
{
float
balance;
float
tax;
balance
= 72.10;
TAX_RATE
= 0.15;
tax
= balance * TAX_RATE;
printf("The
tax on %.2f is %.2f\n", balance, tax );
}
This is illegal. You cannot re-assign a new value to
a symbolic constant.
ITS LITERAL SUBSTITUTION, SO BEWARE OF ERRORS
As shown above, the preprocessor performs literal substitution of symbolic
constants. Lets modify the previous program slightly, and introduce an error to
highlight a problem.
#include
<stdio.h>
#define
TAX_RATE 0.10;
main()
{
float
balance;
float
tax;
balance
= 72.10;
tax
= (balance * TAX_RATE )+ 10.02;
printf("The
tax on %.2f is %.2f\n", balance, tax );
}
In this case, the error that has been introduced is that
the #define is terminated with a semi-colon. The preprocessor performs
the substitution and the offending line (which is flagged as an error by the
compiler) looks like
tax
= (balance * 0.10; )+ 10.02;
However, you do not see the output of the preprocessor. If
you are using TURBO C, you will only see
tax
= (balance * TAX_RATE )+ 10.02;
flagged as an error, and this actually looks okay (but its
not! after substitution takes place).
MAKING PROGRAMS EASY TO MAINTAIN BY USING #define
The whole point of using #define in your programs is to make them
easier to read and modify. Considering the above programs as examples, what
changes would you need to make if the TAX_RATE was
changed to 20%.
Obviously, the answer is once, where the #define statement
which declares the symbolic constant and its value occurs. You would change it
to read
#define
TAX_RATE = 0.20
Without the use of symbolic constants, you would hard code
the value 0.20 in your program, and this might occur several times (or tens of
times).
This would make changes difficult, because you would need
to search and replace every occurrence in the program. However, as the programs
get larger, what would happen if you actually used the value 0.20 in a
calculation that had nothing to do with the TAX_RATE!
SUMMARY OF #define
allow the use of symbolic constants in programs
in general, symbols are written in uppercase
are not terminated with a semi-colon
generally occur at the beginning of the file
each occurrence of the symbol is replaced by its value
makes programs readable and easy to maintain
ARITHMETIC OPERATORS
The symbols of the arithmetic operators are:-
|
Operation |
Operator |
Comment |
Value of Sum before |
Value of sum after |
|
Multiply |
* |
sum = sum * 2; |
4 |
8 |
|
Divide |
/ |
sum = sum / 2; |
4 |
2 |
|
Addition |
+ |
sum = sum + 2; |
4 |
6 |
|
Subtraction |
- |
sum = sum -2; |
4 |
2 |
|
Increment |
++ |
++sum; |
4 |
5 |
|
Decrement |
-- |
--sum; |
4 |
3 |
|
Modulus |
% |
sum = sum % 3; |
4 |
1 |
The following code fragment adds the variables loop
and count together, leaving the result in the variable sum
sum = loop + count;
Note: If the modulus % sign is needed to be
displayed as part of a text string, use two, ie %%
#include
<stdio.h>
main()
{
int
sum = 50;
float
modulus;
modulus = sum % 10;
printf("The
%% of %d by 10 is %f\n", sum, modulus);
}
Sample
Program Output
The %
of 50 by 10 is 0.000000
CLASS EXERCISE C5
What does the following change do to the printed output of the previous
program?
printf("The
%% of %d by 10 is %.2f\n", sum, modulus);
GOOD FORM
Perhaps we should say programming style or readability. The most
common complaints we would have about beginning C programmers can be summarized
as,
they have poor layout
their programs are hard to read
Your programs will be quicker to write and easier to debug
if you get into the habit of actually formatting the layout correctly as you
write it.
For instance, look at the program below
#include<stdio.h>
main()
{
int sum,loop,kettle,job;
char Whoknows;
sum=9;
loop=7;
whoKnows='A';
printf("Whoknows=%c,kettle=%d\n",whoknows,kettle);
}
It is our contention that the program is hard to read, and
because of this, will be difficult to debug for errors by an inexperienced
programmer. It also contains a few deliberate mistakes!
Okay then, lets rewrite the program using good form.
#include
<stdio.h>
main()
{
int
sum, loop, kettle = 0, job;
char
whoknows;
sum
= 9;
loop
= 7;
whoknows
= 'A';
printf(
"Whoknows = %c, kettle = %d\n", whoknows, kettle );
}
We have also corrected the mistakes. The major differences
are
the { and } braces directly line up underneath each other
This allows us to check ident levels and ensure that statements belong to the
correct block of code. This becomes vital as programs become more complex
spaces are inserted for readability
We as humans write sentences using spaces between words. This helps our
comprehension of what we read (if you dont believe me, try reading the
following sentence. wishihadadollarforeverytimeimadeamistake. The insertion of
spaces will also help us identify mistakes quicker.
good indentation
Indent levels (tab stops) are clearly used to block statements, here we clearly
see and identify functions, and the statements which belong to each { } program
body.
initialization of variables
The first example prints out the value of kettle, a variable that has
no initial value. This is corrected in the second example.
KEYBOARD INPUT
There is a function in C which allows the programmer to accept input from a
keyboard. The following program illustrates the use of this function,
#include
<stdio.h>
main() /* program which introduces keyboard
input */
{
int number;
printf("Type
in a number \n");
scanf("%d",
&number);
printf("The
number you typed was %d\n", number);
}
Sample
Program Output
Type
in a number
23
The
number you typed was 23
An integer called number is defined. A prompt to
enter in a number is then printed using the statement
printf("Type
in a number \n:");
The scanf routine, which accepts the response, has
two arguments. The first ("%d") specifies what type of data type is
expected (ie char, int, or float). List of formatters
for scanf() found here.
The second argument (&number) specifies the variable
into which the typed response will be placed. In this case the response will be
placed into the memory location associated with the variable number.
This explains the special significance of the & character
(which means the address of).
Sample program illustrating use of scanf() to read
integers, characters and floats
#include
< stdio.h >
main()
{
int
sum;
char
letter;
float
money;
printf("Please
enter an integer value ");
scanf("%d",
&sum );
printf("Please
enter a character ");
/*
the leading space before the %c ignores space characters in the input */
scanf(" %c", &letter );
printf("Please
enter a float variable ");
scanf("%f",
&money );
printf("\nThe
variables you entered were\n");
printf("value
of sum = %d\n", sum );
printf("value
of letter = %c\n", letter );
printf("value
of money = %f\n", money );
}
Sample
Program Output
Please
enter an integer value
34
Please
enter a character
W
Please
enter a float variable
32.3
The
variables you entered were
value of
sum = 34
value of
letter = W
value of
money = 32.300000
This program illustrates several important points.
the c language provides no error checking for user input.
The user is expected to enter the correct data type. For instance, if a user
entered a character when an integer value was expected, the program may enter
an infinite loop or abort abnormally.
its up to the programmer to validate data for
correct type and range of values.
THE RELATIONAL OPERATORS
These allow the comparision of two or more variables.
|
Operator |
Meaning |
|
== |
equal to |
|
!= |
not equal |
|
< |
less than |
|
<= |
less than or equal to |
|
> |
greater than |
|
>= |
greater than or equal to |
In the next few screens, these will be used in for loops and if
statements.
The operator
<>
may be legal in Pascal, but is illegal in C.
ITERATION, FOR LOOPS
The basic format of the for statement is,
for(
start condition; continue condition; re-evaulation )
program
statement;
/*
sample program using a for statement */
#include
<stdio.h>
main() /* Program introduces the for statement,
counts to ten */
{
int count;
for(
count = 1; count <= 10; count = count + 1 )
printf("%d
", count );
printf("\n");
}
Sample
Program Output
1 2 3
4 5 6 7 8 9 10
The program declares an integer variable count. The
first part of the for statement
for(
count = 1;
initialises the value of count to 1. The for
loop continues whilst the condition
count
<= 10;
evaluates as TRUE. As the variable count has just
been initialised to 1, this condition is TRUE and so the program statement
printf("%d
", count );
is executed, which prints the value of count to the
screen, followed by a space character.
Next, the remaining statement of the for is executed
count =
count + 1 );
which adds one to the current value of count.
Control now passes back to the conditional test,
count
<= 10;
which evaluates as true, so the program statement
printf("%d
", count );
is executed. Count is incremented again, the
condition re-evaluated etc, until count reaches a value of 11.
When this occurs, the conditional test
count
<= 10;
evaluates as FALSE, and the for loop terminates, and
program control passes to the statement
printf("\n");
which prints a newline, and then the program terminates, as
there are no more statements left to execute.
/*
sample program using a for statement */
#include
<stdio.h>
main()
{
int n, t_number;
t_number
= 0;
for(
n = 1; n <= 200; n = n + 1 )
t_number
= t_number + n;
printf("The
200th triangular_number is %d\n", t_number);
}
Sample
Program Output
The
200th triangular_number is 20100
The above program uses a for loop to calculate the
sum of the numbers from 1 to 200 inclusive (said to be the triangular number).
The following diagram shows the order of processing each
part of a for



An example of using a for loop to print out characters
#include
<stdio.h>
main()
{
char
letter;
for(
letter = 'A'; letter <= 'E'; letter = letter + 1 ) {
printf("%c
", letter);
}
}
A B C
D E
An example of using a for loop to count numbers, using two
initialisations
#include
<stdio.h>
main()
{
int
total, loop;
for(
total = 0, loop = 1; loop <= 10; loop = loop + 1 ){
total
= total + loop;
}
printf("Total
= %d\n", total );
}
Total
= 55
In the above example, the variable total is
initialised to 0 as the first part of the for loop. The two statements,
for(
total = 0, loop = 1;
are part of the initialisation. This illustrates that more
than one statement is allowed, as long as they are separated by commas.
MAKING DECISIONS
SELECTION (IF STATEMENTS)
The if statements allows branching (decision making) depending upon the
value or state of variables. This allows statements to be executed or skipped,
depending upon decisions. The basic format is,
if( expression )
program statement;
Example;
if( students < 65 )
++student_count;
In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65.
The following program uses an if statement to validate the users input to be in the range 1-10.
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 ) {
printf("Enter a number
between 1 and 10 -->");
scanf("%d",
&number);
/* assume number is valid
*/
valid = 1;
if( number < 1 ) {
printf("Number
is below 1. Please re-enter\n");
valid = 0;
}
if( number > 10 ) {
printf("Number
is above 10. Please re-enter\n");
valid = 0;
}
}
printf("The number is
%d\n", number );
}
Sample Program Output
Enter a number between 1 and 10 --> -78
Number is below 1. Please re-enter
Enter a number between 1 and 10 --> 4
The number is 4
EXERCISE C10
Write a C program that allows the user to enter in 5 grades, ie, marks between
0 - 100. The program must calculate the average mark, and state the number of
marks less than 65.
Consider the following program which determines whether a character entered from the keyboard is within the range A to Z.
#include <stdio.h>
main()
{
char letter;
printf("Enter a character
-->");
scanf(" %c", &letter
);
if( letter >= 'A' ) {
if( letter <= 'Z' )
printf("The
character is within A to Z\n");
}
}
Sample Program Output
Enter a character --> C
The character is within A to Z
The program does not print any output if the character entered is not within the range A to Z. This can be addressed on the following pages with the if else construct.
Please note use of the leading space in the statement (before %c)
scanf("
%c", &letter );
This enables the skipping of leading TABS, Spaces, (collectively called whitespaces) and the ENTER KEY. If the leading space was not used, then the first entered character would be used, and scanf would not ignore the whitespace characters.
COMPARING float types FOR EQUALITY
Because of the way in which float types are stored, it makes it very difficult
to compare float types for equality. Avoid trying to compare float variables
for equality, or you may encounter unpredictable results.
switch() case:
The switch case statement is a better way of writing a program when a
series of if elses occurs. The general format for this is,
switch ( expression ) {
case value1:
program statement;
program statement;
......
break;
case valuen:
program statement;
.......
break;
default:
.......
.......
break;
}
The keyword break must be included at the end of each case statement. The default clause is optional, and is executed if the cases are not met. The right brace at the end signifies the end of the case selections.
Rules for switch statements
values for 'case' must be integer or character constants
the order of the 'case' statements is unimportant
the default clause may occur first (convention places it last)
you cannot use expressions or ranges
#include <stdio.h>
main()
{
int menu, numb1, numb2, total;
printf("enter in two numbers
-->");
scanf("%d %d",
&numb1, &numb2 );
printf("enter in
choice\n");
printf("1=addition\n");
printf("2=subtraction\n");
scanf("%d", &menu );
switch( menu ) {
case 1: total = numb1 +
numb2; break;
case 2: total = numb1 -
numb2; break;
default:
printf("Invalid option selected\n");
}
if( menu == 1 )
printf("%d plus %d is
%d\n", numb1, numb2, total );
else if( menu == 2 )
printf("%d minus %d is
%d\n", numb1, numb2, total );
}
Sample Program Output
enter in two numbers --> 37 23
enter in choice
1=addition
2=subtraction
2
37 minus 23 is 14
The above program uses a switch statement to validate and select upon the users input choice, simulating a simple menu of choices.
EXERCISE C11
Rewrite the previous
program, which accepted two numbers and an operator, using the switch
case statement.
ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD
getchar
The following program illustrates this,
#include <stdio.h>
main()
{
int i;
int ch;
for( i = 1; i<= 5; ++i ) {
ch = getchar();
putchar(ch);
}
}
Sample Program Output
AACCddEEtt
The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch) to the console screen.
The file ctype.h provides routines for manipulating characters.