Date post: | 23-Dec-2015 |
Category: |
Documents |
Upload: | jonathan-nelson |
View: | 218 times |
Download: | 0 times |
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :1
Starting CStarting C
An introduction to programming in ANSI C This material is intended to get people started in writing
C code in reasonable style It is intended to be cross-platform and not compiler-
specific However there are a few slides about getting started in
Visual Studio ( VC++ 6)
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :2
Software needed - a C compilerSoftware needed - a C compiler
· Microsoft Visual C++ or MS Visual Studio or Watcom or CodeWarrior· Turbo C v.2.01, free from http://community.borland.com/museum/ (just 3 floppies, works in DOS)· Turbo C++ v. 4.5, free on a magazine CD-ROM ( Windows)The GNU C compiler, free from http://www.gnu.ai.mit.edu/software/gcc/ .This is a command line compiler which you may find tricky to set up and use to start withIf you use Linux or another version of Unix, you will find you already have a C compiler, either installed or still on the CD.
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :3
BooksBooks
Computer Science A Structured Programming Approach Using C by Forouzan and Gilberg publishers Brooks/Cole
The C Programming Language by Kernighan and Ritchie second edition published by Prentice Hall
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :4
Using MS Visual C++ IDE - 1Using MS Visual C++ IDE - 1
1. Start MS VC++
2. Click File..New
3. Set up the dialog box like this
a console application
project name
where it is saved
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :5
Using MS Visual C++ IDE - 2Using MS Visual C++ IDE - 2
1. A wizard starts – choose ‘Empty Project’
2. Click OK
3. You will see this
select FileView not ClassView
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :6
Using MS Visual C++ IDE - 3Using MS Visual C++ IDE - 31. From the
menu, click Project.. Add to Project.. New..
2. You will see this..
We are actually adding a C source code file
A filename ending in .c
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :7
Writing the programWriting the program
to run it
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :8
A first programA first program
/* A first program */ int main() { int x, y; x = 5; y = x + 7; return 0; }
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :9
OutputOutput
/* a program with output */ #include <stdio.h> int main() { int x,y; x = 5; y = x + 7; printf(" y is %i \n ", y ); return 0; }
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :10
1. Enter the first program into an editor -/* a program with output */ #include <stdio.h> int main() { int x,y; x = 5; y = x + 7; printf(" y is %i \n ", y ); return 0; }Save it and compile it. Correct any syntax errors reported. Run the program. If you do not get the answer 12, fix it! 2. Write a program to work out the area of a rectangle. Have 3 integer variables, called width, length and area. Make the width 5 and the length 10. Calculate the area and use printf to output it. 3. Use printf to output a Christmas tree, like * *** ***** ******* *
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :11
What compilers doWhat compilers do1: int main() 2: { 00401010 push ebp 00401011 mov ebp,esp 00401013 sub esp,8 3: int x,y; 4: x = 5; 00401016 mov dword ptr [x],5 5: y = x + 7; 0040101D mov eax,dword ptr [x] 00401020 add eax,7 00401023 mov dword ptr [y],eax 6: return 0; 00401026 xor eax,eax 7: } 00401028 mov esp,ebp 0040102A pop ebp 0040102B ret
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :12
#include <stdio.h> #include <limits.h> int main() { int i; short s; long x; printf("Biggest integer = %i\
n",INT_MAX); /* get 32767 */ i = 255; x = 128000L; printf("i = %i and x = %li\n",i,x); /* get 255 and 128000 */ return 0; }
Variables must be one of a small set of data types. All data is represented internally as binary patterns, but different types are encoded into binary in different ways
The standard data type for an integer (whole number) is int
Often, an int is stored in 2 bytes = 16 bits. In that case, ints are restricted to the range ±32000
but the range of all data types in C is implementation-dependent ie not defined by C - the opposite to Java
limits.h contains the ranges of these types and will contain different values in different versions
the type short is an integer which is uses the same or less memory than int
long uses at least as much as an int. Often long uses 4 bytes = 32 bits, giving a range of about ±2 500 000 000
Integral data typesIntegral data types
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :13
#include <stdio.h>
int main()
{ float f; double d;
f = 1.23456789; printf("%f\n",f);
d = 1.2345678912345; printf("%5.13f \n",d);
f = 7 / 2; /* f becomes 3.0 */
f = 7.0 / 2.0; /* f becomes 3.5 */ }
Floating point numbers contain decimal parts Floating point is less precise and slower than
integer The basic type is float which is often stored in 4
bytes The most often used is double which is extended
precision and greater range Details of ranges and precision (implementation-
dependent) is in <float.h> The formatting sequence for a double or float in
printf is %f. A form like %5.13f indicates the number of digits before and after the decimal point. %e gives scientific notation display.
7 / 2 requests the division of 1 integer by another, so integer division is used, giving the result 3
7.0 / 2.0 divides one float constant by another, so floating point division is used, and 3.5 is the result
Floating point typesFloating point types
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :14
Arithmetic operatorsArithmetic operators The arithmetic operators are + - * / and %, which is the
remainder eg 11 % 9 = 2. Each has a precedence level so that BODMAS works and
brackets may be needed eg 4 * 2 + 2 is 14, 4 * ( 3 + 2) is 20 There are floating point and integer versions of these,
depending on the types of the operands.eg 7 / 3 gives 2
For expressions with more than one type, values are converted to the ‘biggest’ typeeg in 3.5 + 7, the 7 is converted to 7.0 and floating point addition is used.
= is also an operator, and the value is the right hand side - for example x = 7; does 2 things - it makes x to be 7 (a side-effect), and it produces a value of 7.
So you can say for example y = x = 7; Set 1-2
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :15
1. Write a program which calculates and outputs the circumference ( 2 r ) and area ( r2 ) of a circle. Use a variable called radius of type double. Take as 3.1416. Test your program works. 2. Write a program which calculates the average of 3 numbers. Use double type variables called x1, x2 and x3 as the three numbers. Check it works.
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :16
Type castingType casting An expression of one data type can be assigned to a variable of
another type such as
int x;long lo;x = 3;lo = x;
This is called a type cast Casting a value to a ‘bigger’ type, such as char to int, or float to
double, produces no data loss - but the reverse potentially can The example above is an implicit cast - it is up to the compiler to
identify that a cast is needed, and provide the code to do it An explicit cast is like this
lo = (long) x;where (long) tells the compiler to convert the type to long
Implicit casts are bad practice - they imply that the programmer is unaware of the type of the data involved
Compiler settings should be such as to generate warnings on implicit casts - then the programmer can write explicit casts where appropriate
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :17
Conditional - ifConditional - if
The idea is that the machine evaluates an expression and takes different actions depending on whether the result is true or false
Note the round brackets around the condition The { and } form a block of statements to do. If
there is only one statement, they are not needed. The else part can be missed out if it is not
needed. A value of 0 is 'false', while any non-zero value is
'true' - see later the relational and logical operators can be used,
so that if ( ( x == 4 ) || ( y < x + 7 ) ) ..means if x is 4, or y is less than x+7, do something..
if ( x > y ) { x=7; y = 55; } else { y = 9+x; printf(“Hello”); }
Relational operatorsSymbol means..
> greater than
< less than
== equal to
>= Greater than or equal to
<= less than or equal to
!= not equal to
Logical operatorsSymbol Means Idea&& AND both things true|| OR either thing true! NOT
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :18
Input - scanfInput - scanf
This is run-time input of data, normally from the keyboard For example
int i; scanf("%i", &i);execution pauses at the scanf, and waits for the user to type in a value for i
Note the &, the address operator, in front of the variable scanf is prototyped in stdio.h
scanf is not usually used in real programs (not even DOS ones) because of the difficulty with validation. In other words if the user does not type in a valid value - its too late.. but scanf is OK for initial teaching programs
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :19
1. Write a program to work out the area of a rectangle, using scanf to input data at run-time. Have 3 integer variables, called width, length and area. Calculate the area and use printf to output it. Can you find data to enter which you crash the program? 2. Write a tax calculator, which inputs a person's salary then outputs the tax, calculated by the following - if they earn less than £10 000, the tax is zeroover £10 000, they pay tax at 20% 3. Write some code to input a person's age and validate it. If the age is less than 0 or more than 120, output a message 'Age invalid' - otherwise output 'Age OK'.
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :20
Increment, decrement and assignment Increment, decrement and assignment operatorsoperators
The need to increase a variable by 1 is so common there is an increment operator - for example x++; is the same as x = x + 1 ;
Similarly there is a decrement operator x--; is the same as x = x - 1 ;
For both these, there are pre and post versions. For example, post-increment - y = x++; first makes y equal to x, then increases x by 1 -
but pre-increment y = ++x; first increases x by one, then makes y equal this new value of x
Assignment operators are short-hand. For example += x = 7; x += 9; same as x = x + 9 - so x becomes 16
More examples -Operator Example Equivalent
-= x -= 4 ; x = x - 4;
*= x *= y + 3; x = x * (y + 3);
%= x %= 2; x = x % 2;
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :21
Expressions and statementsExpressions and statements An expression is something which has a value. For example assuming the
variables have been declared and given values, all of the following are expressions -
2 + 2 5 * x + 4 4 + ( y + 3 ) / ( x + 2 ) sin( 3 * x ) /* sin is a function prototyped in math. h */ 38 x = 4 /* remember = is an operator with a side-effect */ x++ /* post-increment, side-effect, value is the initial value of x */ An expression becomes a statement if it is followed by a ; So
x + 2; is a syntactically valid statement in C - but a good compiler would warn you that 'code has no effect'
maybe you meant to type x = 2;
especially since + and = are on the same key!!!
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :22
1. Look at this piece of code - int a, b, c; a = 4;b = ++a;c = a++;b *= a;c -= 3; What should be the values of a b and c after this? Work it out on paper, then write a program to check. 2. Classify each of the following as an expression, a statement, or as invalid -
1 + 1 x = 3; x + 2
1 + 1; x++ x++;
a = b = c; x++2; 2++
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :23
if - againif - again remember 0 is ‘false’, and any non-zero value is ‘true’ programmers often use this to compress code eg
x = 3 * y + 5;if ( x == 0 )……
would probably be coded asif ( ! ( x = 3 * y + 5 ) ) …. this uses the side-effect of = to execute the assignment and the value is the value of x if x is 0, !x is 1, which is true, so the if is triggered
bug number 1..y = ….something...;x = y;if (x=0)…..many compilers will warn this
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :24
conditional - switchconditional - switch suppose you want to execute various alternative blocks of code, depending on
the value of a variable - you might write
if (x==1)…..
else if (x==2)…..
else if (x==3)…..
the switch construct caters for this switch (x)
{ 1: ….. ……
2: ….…..3: ….....default: ….…}
but.. the 1, 2 ,3 etc must be constant integral expressions when one case triggers, it falls through all other cases so the usual form is..
switch (x){
1:
….. ……
break;2:
….…..
break;
default: ….…}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :25
conditional - the ternary operatorconditional - the ternary operator if you want to get one value if an expression is
something, and an alternative if it is not.. such as
if ( x > 38 )y = 47;
elsey = 32;
it is faster to writey = ( x > 38) ? 47 : 38 ;
which is likey is.. is x >38? if so, 47, else 38
Set 1-5
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :26
char typechar type/* char */ #include <stdio.h>
int main() { char c; c = 'a'; printf("c = %c or %i\n",c,c); /* a or 97 */ c = 'b'; c = c + 2; printf("c = %c\n",c); /* gives d */ return 0;
}
char is to be thought of as a character, or as a small integer
Traditionally, characters are represented in a machine by codes which are 1 byte long. Most PCs use the ASCII code system, in which A is 65, B is 66, C is 67,.. a is 97, b is 98,.. 0 is 48, 1 is 49, a SPACE is 32 and so on. There are other character codes which are 1 byte long, such as EBCDIC
A char variable can be assigned a value like 'a' single quotes 'like' and NOT "double quotes", which delimit strings
A char can be displayed using the %c formatting sequence in printf
Since chars are small integers, you can do arithmetic with them, like c = c + 2
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :27
1. Use switch to write a simple calculator which would run as follows (sample user input is in italics ) - Input first number: 2 Input second: 3Choose operation ( + - * or /): + Result = 5 Use scanf for input, and a char variable for the operation.
Note : if you try to input the char using scanf("%c",&c); it picks up the previous carraige return – so sayscanf(" %c",&c); // space before %c skips over CR
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :28
loops - do..whileloops - do..while use a loop if some process is to be repeated there are 3 basic loop structures in C the do while structure repeatedly executes a block of
code so long as some condition is true for example to output the numbers 1 to 10.. x = 1;
do{printf(“%i \n”, x);x++;}
while (x<11); or..
x = 1;do
printf(“%i \n”, x++);while (x<11);
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :29
a do..while loop will always execute the loop body at least once, since the condition is checked at the end. Sometimes this is inappropriate eg to delete all files in a directory and the directory is empty
an alternative loop checks the condition at the start for example to output the numbers 1 to 10..
x = 1;while (x<11)
{printf(“%i \n”, x);x++;}
or, to output 10 to 1..
x = 11;while (--x) printf("%i \n",x);
loops - whileloops - while
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :30
Loop templatesLoop templates
Task:
Output a message 10 times
This kind of process just needs an ‘index variable’ which is used to count the number of times the loop should repeat
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :31
Loop Template 1Loop Template 1
In pseudo-code
initialise counter to 0
while ( counter < 10 )output messageincrease counter by 1
In C:
#include <stdio.h>
int main(){int counter;counter = 0;while (counter<10)
{printf(“Hello\n”);counter++;}
return 0;}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :32
Loop template 2Loop template 2
Task:
•Add up the integers from 1 to 100
•There are 2 aspects to this –•Go through the numbers 1 to 100•Add them up
•We need a counter variable to represent the 1 to 100•and another which is the “running total”
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :33
Loop template 2Loop template 2
Pseudo-code plan –
Initialise counter to 1Initialise total to 0
while ( counter < ?? )add counter into totaladd 1 to counter
In C#include <stdio.h>
int main(){int counter, total;counter = 1;total = 0;while (counter<101)
{total += counter;counter++;}
printf("Total = %d\n",total);return 0;}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :34
Loop template 3Loop template 3
Task
Input integers from the keyboard, until a rogue value of –99 is enteredOutput the average
Thoughts – Input using scanf – need a ‘number’ variableWe have to add up the numbers – we need a total variableWe don’t know (at ‘compile time’) how many times we will loopWe have to count them – we need a counter variableWe must avoid adding in and counting the -99
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :35
Loop template 3Loop template 3Pseudo-code
Initialise total to 0Initialise counter to 0
Input number
while ( number not –99 )Add number to totalIncrement counterInput number
average = total / counterOutput average
#include <stdio.h>
int main(){int counter, total, number;double average;counter = 0;total = 0;scanf("%d",&number);while (number!= -99)
{total += number;counter++;scanf("%d",&number);}
average = (double)total / (double) counter;printf("Average = %lf\n",average);return 0;}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :36
1. Here is a program which outputs the integers 1 to 5 - #include <stdio.h>int main(){
int stepper;stepper = 1;while (stepper<6){
printf("%d ",stepper);stepper++;
}return 0;
} We will use this as a basis for several more programs. Type it in and run it. 2. Change the program so it outputs integers from 1 to 99 (inclusive).3. Change it so it outputs from -99 up to 99.4. Change it so it goes up in steps of 2 ( so you get -99 -97 -95........97 99 ).5. Change it so it starts at 100 and goes down to 1.
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :37
1. Use a do-while loop to output the even numbers from 2 to 100 inclusive. 2. Input an integer then output 'Hello' that number of times. Include the possibility of 0 iterations. 3. Use a loop to output the sequence 3, 6, 9, 12,..300 4. Add up the integers from 1 to 100. 5. The user inputs a sequence of integers, terminated by a 'rogue value' of -99. Add up the sequence and output the result -Sample input 1, 2, 3, -99Output 6
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :38
ArraysArrays
7 13 42 4 17 22 7 66 3 9
0 1 2 3 4 5 6 7 8 9
An array is a set of data values – not just one
Think of an array as a row of boxes
Each box is an element
The elements have an index – a label for which box is which
The 10 elements
index of each element
array of 10 integers
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :39
An array is a data structure – a way of arranging a set of data items
An array is a set of numbered boxes, each box holding a value
an array marks[20] could hold the exam marks of 20 students
This would be declared asint marks[20]; < must use square brackets
The boxes are numbered 0 to 19 Some examples are
marks[0] = 35; store 35 into the first boxmarks[9] = 48; store 48 into the 10th. boxx = marks[0] + marks[1]; add up first 2 boxesk = 34;marks[k] = 17; put 17 into 35th. Boxmarks[20] = 23; !! Array bounds error !!
ArraysArrays
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :40
To process arrays loops are often used to go through the different elements
For example, this would declare an array, read values in from the keyboard, then print them out again..int index = 0;int numbers[5];while ( index < 5 ) { printf("Enter a number.."); scanf("%i", &numbers[index] ); index++;
}
index = 0;while ( index < 5 ) { printf(“ %i %i \n ", index, numbers[ index ] ); index++; }
Arrays and loopsArrays and loops
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :41
Arrays - count zerosArrays - count zerosSuppose we have an array called numbers, containing 5 integers, and we want to count how many zeros there are -
zeroCount = 0;
index = 0;
while ( index < 5 )
{
if ( numbers [ index] == 0 )
zeroCount++;
index++;
}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :42
Arrays - find largest elementArrays - find largest element
biggest = 0;
index = 0;
while ( index < 5 )
{
if ( numbers [ index] > biggest )
biggest = numbers[index];
index++;
}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :43
Arrays - find totalArrays - find total
total = 0;index = 0;
while (index < 5 )
total = total + numbers[index++];
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :44
Arrays of charArrays of char Strings in C are stored as sequences of character codes,
and are terminated by a 0 - ASCIIZ so “ABC” is stored in 4 bytes, with values 65 66 67 0 this can be done using arrays eg
char word[4] = “ABC”; or
char word[4];word[0]=‘A’;word[1]=‘B’;word[2]=‘C’;word[3]=‘\0’; not word[3]=‘0’;
orchar word[] = “a longer string”;
the problem with this is an array is fixed in length, so you can’t store longer strings in the array. Consequently pointers to chars are more often used..
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :45
1. Fill an array with 5 random integers ( use the function rand() from stdlib.h ). Print them out, together with the average of the 5 numbers. 2. Fill an array with 50 random integers. Print them out, then reverse them, and print them out again
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :46
for loopsfor loops2 kinds of C loops – while( ) and do..while( )
The 3rd and last kind is a for loop
It looks like –
for (…………..){....}
There are 3 parts in this bracket
This is the loop body – the statements to repeat
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :47
for loopsfor loops
for ( x=0 ; x<5 ; x++ ){....}
Initialise
change at the end of each repeat
loop repeats so long as this is true
so this loops with x having the values
0 1 2 3 and 4
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :48
for loop – output 1 to 100 for loop – output 1 to 100 (nearly)(nearly)
..
int x;
..
for ( x = 0; x < 100; x++)
printf(“%d\n”, x);
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :49
for loop – counting downfor loop – counting down
..
int x;
..
for ( x = 100; x > 0; x = x - 2)
printf(“%d\n”, x);
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :50
for loop – totalling an arrayfor loop – totalling an array
int data[100]
int index, total = 0;
..
for ( index = 0; index < 100; index++ )
total = total + data[index];
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :51
nested loopsnested loopsint x;int y;y = 0;
..
for (x = 0; x<3; x++)printf(“%d ”, x + y );
for (y = 0; y<30; y = y + 10 ) {
printf(“\n”); }
0 1 2
0 1 2
10 11 12
20 21 22
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :52
1. Use a for loop to output 1 to 100 inclusive
2. Use a for loop to output the 4 times table like
1 X 4 = 4
2 X 4 = 8
..
12 X 4 = 48
3. Modify the program in 2 so it produces all the times tables from 2 to 12
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :53
Long pieces of code are very hard to manage It is more effective to structure programs into small pieces or
units All C programs are made of units called functions main() is a special function - where execution starts - so far
the only function in the program Real programs are broken up into several functions A function should not have more than around 30 lines of code
- or it should be broken up into other functions This modularity means that
small functions are easier to write they are easier to debug they can be tested separately faster they will not stop each other working they can be written by teams of programmers they can be re-used in other projects
Functions - ideasFunctions - ideas
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :54
Function call sequenceFunction call sequence
void func() { .. return; }....int main() { .. func(); .. }
the definition of function
func
a call of func()
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :55
function examplefunction example#include <stdio.h>
void greeting() { printf("Hello\n"); return; }
int main() { greeting(); return 0; }
void means the function does not ‘return a value’
it just does something
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :56
•This works –#include <stdio.h>
void greeting(); // function prototype
int main() { greeting(); return 0; } void greeting() { printf("Hello\n"); return; }•header files (like stdio.h) are mostly prototypes
function prototypesfunction prototypes•This doesn’t work –#include <stdio.h>int main() { greeting(); return 0; } void greeting() { printf("Hello\n"); return; }•because the compiler works through program top to bottom, and•it sees the call to greeting() before it has seen the definition of what greeting is
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :57
function parametersfunction parametersA value can be sent into a function to specify what it does
This is called a function parameter#include <stdio.h>
void greeting(int howManyTimes){ int i; for (i=0; i<howManyTimes; i++) printf("Hello\n"); return;}
int main(){ greeting(5); return 0;}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :58
functionfunction with a parameter with a parameter#include <stdio.h>
void table( int );
int main(){
table(5); return 0;}
void table( int n){
int i;for (i=1; i<13; i++)
printf("%i X %i = %i\n", i,n,i*n);return;
}
output…1 X 5 = 52 X 5 = 103 X 5 = 154 X 5 = 205 X 5 = 256 X 5 = 307 X 5 = 358 X 5 = 409 X 5 = 4510 X 5 = 5011 X 5 = 5512 X 5 = 60
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :59
global and local variablesglobal and local variablesint g;
void func()
{
int x;
..
}
int main()
{
int y;
..
}
This are local or automatic variables
This is a global or external variable
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :60
External variablesExternal variables this program is supposed to fill an
array with numbers, display them, reverse them, and display them again
so each function needs access to the array, and fill() and reverse() need to alter its contents
This can be done by making it an external variable
These are declared outside functions – they are ‘global variables’ – contrasted with those declared at the start of a function, which are automatic variables
External variables provide for unrestricted interaction between functions
In particular a function can alter them in invalid or accidental ways so..
External variables should be avoided if at all possible
int numbers[20];
void fill(void);void reverse(void);void display(void);
int main(){
fill();display();reverse();display();return 0;
}
void fill(){ /* define fill */
return;}
void display(){ /* define display */
return;}
void reverse(){ /* define reverse */
return;}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :61
ScopeScope The scope of a variable is the section of the
program within which the variable can be accessed
The scope of an automatic variable (local variable) is the function within which it is declared
The scope of an external variable is from where it is declared to the end of the file
Automatic variables with the same name in different functions are unrelated
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :62
#include <stdio.h>int ex = 0;void foo1()
{int a;a = 1;return ;}
void foo2(){int a;ex = 3;a = 3;return;}
int main(){ex = 7;foo1();foo2();return 0;}
ex is external and has this scope.
It can be accessed in foo1(), where it will have value 7 (set in main() )
Workshop 12
Scope exampleScope example
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :63
functionsfunctions returning values returning values
This program uses a function to calculate the average of two numbers – it has to return the answer
The protoypedouble average(double, double );tells the compiler the return type, and the number and type of the arguments
The prototype must be consistent with the header of the function definition
The names of the arguments in the definition ( x and y ) are matched with the values in the function call ( a and b ) in order
#include <stdio.h>
double average(double, double );
int main(){
double a,b,c;a=1.0;b=2.0;c=average(a,b);printf("%f\n",c);
return 0;}
double average(double x, double y){
double r;r = (x+y)/2.0;return r;
}
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :64
call by valuecall by valuevoid foo( int );
int main(){
int i=1;foo(i);/* how big is i now? */
return 0;}
void foo( int n){
n++;/* n is 2 - but what is i ? */return;
}
parameters are always ‘called by value’
this means that a copy of the value of a parameter is passed into the function
the function can alter the value of the copy, but not the original
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :65
FunctionsFunctions
1. Write a function which finds the average of 3 numbers rather than 2. Write a main() to test it.
2. Write a function bigger that takes 2 integer parameters, and returns the larger one.
3. Write a function IsUpper, which takes a char argument, and
returns 1 if the argument is a capital letter, and 0 otherwise. For example,
isUpper('A') returns 1isUpper('x') returns 0hint: if (c>='A' && c<='Z') … then c is an upper case character.
Introduction to C : set 1 © Walter Milner 2005 :::: Slide :66
1. Suppose you want to find the square root of x. Here is a method -
set y to 1
repeat
replace y by (y + x / y) / 2
y will get closer and closer to the square root of x. Write a function called root using this method.
2 The factorial of a number, written n!, is the product of all the integers up to n. So for example 4! = 4 X 3 X 2 X 1 = 24. Write a void function called PrintFactorial which has an integer argument, and which outputs the factorial of it. Test it with 10! = 3 628 800