You are on page 1of 18

An Introduction to C programming

This is an informal introduction to C programming and some programming related


topics.

An Introduction to C programming
General format of a C program:

void main()
{

statement;
statement;

}
Program execution begins by executing the statements inside the main() function.
Functions and the use of the keyword void will be explained later.

Variable Declarations
Integers:

int i, j, k ;

Reals
float salary, average ;

Text
char name[80];

Output
The printf statement is the most commonly used output statement in C.

printf is a very powerful output statement, capable of formatting output in a


number of ways.

/* prog1.c: First C program */


#include <stdio.h>

void main()
{

C Programming Notes: J. Carthy UCD Computer Science 1


printf(“hello world \n”) ;
}

This is a classic first C program for many people. It simply displays the message

hello world

on your screen. The line

#include <stdio.h>

is used to when we wish to use standard C function for input and output. It
“includes” declarations required to allow us use various I/O functions. Text inside
/* */is treated as a comment and ignored by C.

Note the \n in the string. This causes the printf to start a new line when it has
output the message. This prevents the next message beginning directly after the last
one e.g.

printf(“hello world”);
printf(‘hello tom”);

would display the follow output

hello worldhello tom

whereas

printf(“hello world\n”);
printf(‘hello tom\n”);

displays

hello world
hello tom

\n is called the newline character. You can have several newlines in a single
message e.g.

printf(“\n\n hello world \n\nhello tom”);

What will it display ?


Displaying variables
Assume that a variable sum has the value 124. Then

printf( “Sum = %d “, sum ) ;

will display the following


Sum = 124

In displaying a variable you must tell printf how to display it (format it). The
%d above tells printf to display the variable sum as a decimal number (integer).
The position of %d tells printf where in the output to display the number.

printf simply replaces the %d in the message with the value of the variable to be
displayed. You must have the %d in the message for printf to work properly for
integers.

You may display several variables in one printf :

printf(“ sum = %d average = %f \n”, sum, average) ;

will display

sum = 124 average = 12.4000

%f is used to display real numbers

Note: The following 2 printfs produce the same output as the previous one.
WHY ?

printf(“ sum = %d “, sum );

printf(“average = %f \n”, average);

We assume that the variables sum and average have been declared and have been
assigned the appropriate values earlier in the program.

There are other formatting options in addition to %d and %f e.g. for displaying
hexadecimal and octal numbers.
Exercises on printf.
1) Write printf statements to display the following:

a) HELLO WORLD

b) 67.34

c) THE ANSWER IS

d) The Answer is.

e) Given ft = 4 and ins = 48.


Display using the variables the message,
4 feet = 48 inches

2) Enter the following C programs and try to make sense of any errors that may be
reported:

a) void main(
{
printf ( “this is program number 1” );
}

b) void main()
{
printf ( “this is program two );
}

c) void main()
printf ( “this is the third one” );

Assignment Statement
Variables are assigned values as follows:
i = 0 ;

count = 10;

sum = sum + i ;
General format:

variable = value ;

Input in C
There are numerous input statements provided by the C language. For the moment
we will consider one method - the scanf statement. Unfortunately, input in C is
not as easy as assignment. To input into our variable feet we use:

scanf ( “%d”, &feet );

This is pretty horrible! But it is the way you must write it.

Be careful to include both quotes, and the ampersand (&) before feet. Do not
leave out the comma. This statement says “read a decimal number from the
keyboard into the variable called feet”.

By replacing the %d with %f we can use scanf to read in real numbers as well:

scanf(“%f”, &hours) ;

This will read a real number from the keyboard into the variable hours.

Note: When you enter the number using the keyboard, you must press the
Return (Enter) key before scanf will read it.

Common C Programming Errors.


1) Spelling.
int feet;
ins = ft * 12;

The statement int feet declares a variable called feet.

feet and ft are not the same. You must spell a variable the way you declared it.
Note the following spelling ERRORS

flaot average ;
print(“hello world”) ;
scan(“%d”, &feet) ;
2) Missing Quotes, Commas, Variables

scanf(“%f , hours);
printf(“average = %f “) ;
scanf (“%d” answer) ;

3) Assignment.
ft * 12 = ins; ERROR the wrong way around.

Conditional Statements
Conditions (Boolean expressions) in C must ALWAYS be enclosed in parentheses
(round brackets) e.g.

( hours <= 40 )

( hours >= 100 )

( count != 0 )

( answer == 1 )

if-then statement in C

General Form:

if ( condition ) statement

where statement may be simple or compound.

Note: the C language does NOT use the word then

A simple statement is a single statement terminated by semicolon as in:

printf("abc") ;
or
sum = 0 ;
A compound statement is a group of one or more simple statements enclosed in
braces ({}) e.g.

{
sum = 0 ;
i = 10;
printf("abc");
}

The above constitutes a compound statement made up of three simple statements.


The rule is that a compound statement may be used anywhere that a simple
statement is allowed.

Example
/* prog2.c Example of Input Validation */
#include <stdio.h>

void main()
{
float number;

printf ( "Please type in a number < 100 ? " );


scanf ( "%f", &number );

if ( number >= 100 )


{
printf ( "ERROR: Your number is >= 100.\n" );
printf (“ You must enter numbers <= 100 \n”) ;
}
}

if-then-else statement in C
General Format:

if ( condition ) statement
else statement

where statement may be simple or compound.

Examples
1.
if ( i <= j )
printf(“value of j >= i \n”);
else
printf (“ i is bigger than j \n”);

2.
if ( hours > 40 )
{
overtime = (hours - 40) * 3.5 ;
rest = 40 * 2.5 ;
pay = overtime + rest ;
tax = pay * .32 ;
}
else
{
pay = hours * 2.5 ;
tax = pay * .30 ;
}

Constants
In the above code the numbers 40, 3.5, 2.5, .32 and .30 are constants. They will
never change when we run the program. In maths we often give constants a name
such as pi rather than writing down the value. This idea is also used in
programming. We give each constant a name like a variable name. We then use
this name in our code.

The two main advantages of using constants are

1. They make programs easier to read and understand

2. If you need to change the value of a constant you have only to change one
statement in your code i.e. where you give the constant a name.

For example, in the code above, if the rate per hour for hours less than 40 is
increased to 2.75, we must search our program for all the old values and replace
them all. If we omit one be mistake, we have a serious error.
Similarly for the tax rates.
Each language providing the facility to define constants has its own syntax for
doing so. Normally, as a convention, we use uppercase (capital) letters for the
names of constants so that we can easily distinguish them from variables in our
programs.

Constants in C
In C to define a constant we use #define

#define RATE 2.5


#define ORATE 3.5
#define TAXRATE1 .30
#define TAXRATE2 .32
#define WEEKHRS 40

if ( hours > WEEKHRS )


{
overtime = (hours - WEEKHRS) * ORATE ;
rest = WEEKHRS * RATE ;
pay = overtime + rest ;
tax = pay * TAXRATE2;
}
else
{
pay = hours * RATE ;
tax = pay * TAXRATE1;
}

From the above code, you can see how easy it is to change the program to take
account of a change in tax rates say. You simply change the value of the constant
in the #define. Every where the name appears it will be replaced by the value.

It is very important to note constants are not variables. They take on one value and
maintain it. You cannot assign a constant a value.

When you define a constant, the compiler simply replaces the constant name
by its value every where the name occurs.

Important Note:
C is a case sensitive language. This means that it distinguishes between upper and
lower case letters. Keywords (e.g. if, while, int, float, printf etc) must
be in lower case. Variables with names having the same spelling but in different
cases are treated as different variables.
Example:

Rate
RATE
rate
rAte

are all different from the C language’s point of view. This gives rise to many
syntax errors for beginners. As a convention, many C programmers spell variable
names in lower case letters. and use upper case letters usually for constants. This
allows you easily distinguish between constants and variables when reading a
program.

This is only a convention or style of programming. A good programming style


enhances the readability of programs. Programmers usually have their own
individual style for indentation, variable and constant names. The important point
is to be consistent. If you use lower case variable names then it is a good idea to
have all variables in lower case.

Exercises:
1. Write a simple wage calculation program: read in the hours, pay,
and taxrate of an employee and calculate the net pay and tax due. Print out a
sample payslip.

2. Write a program to read in the exam result of a student in percentage.


Your program should then print out the grade to be awarded. (A, B, .. F)

It should check for invalid results, e.g. a mark greater than 100.

(A: 85 .. 100; B: 70 .. 85; C: 55 .. 69; D: 40 .. 54; E: 30 .. 53; F < 30 )


Conditional Statements Continued

while Loop in C

General Format

while ( condition )
statement

where statement may be simple or compound.

statement will only be executed if the condition evaluates to true.

Examples
Here we keep processing salaries until a value other than 1 is entered.
Note this program will run forever (until the machine is switched off) unless some
value other than 1 is entered. In C this becomes:

printf ( "Enter 1 if you wish continue: " );


scanf ( "%d", &answer );

while ( answer == 1 )
{
printf ("Enter hours: ");
scanf ( "%f", &hours );
pay = hours + 2.5;
printf ( "\nPay = %f\n", pay );
printf ( "Enter 1 if you wish continue: " );
scanf ( "%d", &answer );
}
printf ( "\n\nProcessed.\n" );

Processing wages for 10 employees:


num = 1;
while ( num <= 10 )
{
scanf ( "%f", &hours );
pay = hours * 2.5;
printf ( "\nTotal = %f", pay );
num = num + 1;
}
printf(“Finished”);

Loop Errors:
1. A very common error is to use = instead of == in testing for equality.
ALWAYS check your programs for this error in C, when testing for equality in a
conditional statement.

2. Endless loop:

n = 1;
while ( n > 0 )
{
statements

n = n + 1;
}

In this example n will always be bigger than 0 and so we have an endless loop.
However, the program will crash after a while. WHY ?

If you omit the statement num = num + 1 in the earlier example so that it looks
like:
num = 1;
while ( num <= 10 )
{
scanf ( "%f", &hours );
total = hours * 2.5;
printf ( "\nTotal = %f", total );
}

we also have an endless loop; the program never stops! We must interrupt it or
switch the machine off. In this case the program will not crash. WHY?

/* wages.c: Wages Program for 10 employees


Joe Bloggs, First Science, Jan 23rd 1991*/

#define WEEKHRS 40
#define BRATE 2.5
#define OTRATE 3.5
#define TOOBIG 100
#define TOOSMALL 0
#define NUMEMP 10
#define BASIC (WEEKHRS * BRATE)

#include <stdio.h>

void main()
{
float hours, pay, otpay ;
int num ;
num = 1 ;

while ( num <= NUMEMP )


{
printf(“Enter hours: “);
scanf(“%f”, &hours);

if ( hours <= TOOSMALL || hours >= TOOBIG )


{
/*Invalid hours: print error messages */
printf(“Error: Hours are out of range %f \n”,
hours);
printf(“Hours must be between 0 and 100 \n”);
}
else
{
/* valid hours: calculate pay */

if ( hours > WEEKHRS )


{ /* calculate overtime */
otpay = ( hours - WEEKHRS ) * OTRATE ;
pay = otpay + BASIC ;
}
else
{ /* pay with no overtime */
pay = hours * BRATE ;
}
printf (“Hours: %f Pay: %f \n\n “, hours, pay);
num = num + 1 ;
}
}
}

Notes on Program Layout:

•Programs should begin with a comment giving:


filename of the program
program title
author’s name and date

• Programs should have comments explaining what’s happening at significant


points

• Conditional statements should be indented so that it is clear where they start and
finish.

• Constants should be used where appropriate

• Meaningful names should be used for variables and constants

• Input should always be validated if possible and appropriate messages displayed


in the event of an error

Logical AND in C
if ( hours > 0 && hours < 100)
statements for valid hours

Logical OR in C
if ( hours <= 0 || hours >= 100 )
statements for invalid hours

More about Loops

The For Loop

We have seen 2 cases in using the while loop:


Case 1: We knew how many times we wished to go around the loop.

Case 2: We did not know how many times we wished to go


around the loop.

Both occur very frequently. The while loop is almost always used for case 2.

A more convenient loop is often used for Case 1 (although it produces exactly the
same result as using the while loop). It is called the for loop.

In pseudo code it appears as:

for n = 1 to 10 do
statement

where statement may be simple or compound. The above may be interpreted as

“repeat statement (loop body) 10 times, increasing n by 1 each time around the
loop and stopping when n reaches 10”.

n is called the loop counter variable.

Example in pseudo-code:

for num = 1 to 10 do
begin
printout(“Enter hours:);
readin( hours ) ;
pay = hours * 2.5 ;
end

In this example the loop body will be executed 10 times and n will have the value
11 on termination of the loop..

Notes

1. The value of the loop counter variable on exit from a for loop varies from
language to language. In, Pascal it is undefined and unsafe to assume it will have a
particular value. In, Algol you cannot use the loop counter variable outside the
loop. In, C it behaves as in the pseudo-code above.
2. You do not increase the counter variable in the loop body as we did with the
while loop. This is carried out automatically in a for loop.

In C, the syntax of the for loop looks like that of the while loop.

General Format:

for ( var = value; condition ; var = var + 1 )


statement

where statement may be simple or compound

var = value assigns the counter variable its initial value

condition determines when the loop terminates

var = var + 1 increments the counter variable for each iteration of the loop. var is
initialised ONCE, before executing the loop body.

condition is tested before executing the loop body. The loop body will be executed
only if the condition yields true.

var is incremented after execution of the loop body, before re-testing the
condition.

Note: You must have semi-colons between the 3 components.

Example

for ( n = 1; n <= 10; n = n + 1 )


{
statements;
}

This is exactly the same, by definition, as

num = 1;
while ( num <= 10 )
{
statements;
num = num + 1;
}

Example:
#include <stdio.h>

void main()
{
int counter;
float value, sum, average;

sum = 0;
average = 0;
/* Now loop four times, once for each value */

for (counter =1; counter <=4; counter = counter +1)


{
printf ( "Enter value no.%d\n:", counter );
scanf ( "%f", &value );
sum = sum + value;
}
/* Out of the loop now, so calculate average. */
average = sum / 4;

printf ( "\nSum = %f", sum );


printf ( "\nAverage = %f\n\n", average );
}

Example 2
Sum the integers 1 to 100
/* prog3.c: */
#include <stdio.h>

void main()
{
int i, sum ;

sum = 0 ;

for ( i = 1; i <= 100 ; i = i + 1 )


{
sum = sum + i ;
}

printf(“Sum = %d \n”, sum ) ;


}

Note again: the for loop is used when you know or can calculate at runtime how
many times you wish to repeat some statement (simple or compound).

Review
Looking back we can see programs are made up of a list of statements. One
statement is executed, usually followed by the next one and so on. They are
executed in sequence. Some special statements allow us alter the sequence - these
are the conditional statements. There are two types. The first type allows us to
make decisions. They are called selection statements (branching). We can use them
to select what statements to do next. The most used selection statement is the if
statement. The second type allow us to repeat statements. They are called iteration
statements (or loops). The most used iteration statements are the while and for
statements.

The sequence of execution of statements is called the flow of control in a program.


Statements that alter which alter the flow of control (if, while, for) are called
control structures.
Principle
Every program that can be written only requires control structures for sequence,
selection and iteration.

An understanding of the concept of variables and control flow is fundamental


to programming.

You might also like