Initial commit of lecture code

This commit is contained in:
Louise Brown
2022-04-07 16:58:01 +01:00
commit 5b205092a7
60 changed files with 2413 additions and 0 deletions

28
LC12/global_ex1.c Normal file
View File

@@ -0,0 +1,28 @@
/*
This makes global variables look like a good idea
THEY ARE NOT - DO NOT USE THEM
*/
#include <stdio.h>
#include <stdlib.h>
int y,k,ans; /* Define GLOBAL variables */
void NastyGlobalFunction (void ) /* Define function */
{
ans = ( y * k ); /* y, k and ans are defined globally above */
return ;
}
int main( void )
{
y = 2; /* Set value of y */
k = 3; /* Set value of k */
NastyGlobalFunction(); /* call the function */
printf("%d multiplied by %d is %d " ,y ,k ,ans ); /* Display values */
return 0;
}

37
LC12/global_ex2.c Normal file
View File

@@ -0,0 +1,37 @@
/*
In this example, we do not have a problem as although
we have a global variable 'i', we do not corrupt it in
the function
*/
#include <stdlib.h>
#include <stdio.h>
int i; /* Nasty global variable ! */
/*
This function returns the sum of the number 1->10
Note that although we use 'i' it is not defined in
the function its self.
*/
int SumToTen ( void )
{
int Result = 0;
for ( i = 10 ; i >= 0 ; i-- ) // Count down as more effecient
Result = Result + i;
return Result;
}
/* This is our main function */
int main(void)
{
printf ("\nThe sum of the values 0 to 10 is %d ",SumToTen() );
return 0;
}

57
LC12/global_ex3.c Normal file
View File

@@ -0,0 +1,57 @@
/*
This time we have a real problem. We are using the variable
'i' in the main loop to count and again in the function.
Thus the function will change the value seen by the 'main'
routine - and will cause *Serious* problems
*/
#include <stdlib.h>
#include <stdio.h>
int i; /* Again, the nasty global variable */
/*
This function returns the sum of the number 0 -> i, but
summing from the limit back to zero ( to prove a point ! )
The problem this will cause is that at the end of the routine
the value of 'i' will always be '1' which will stop the loop
in 'main' working !
*/
int SumToValue ( int Limit )
{
int Result = 0;
printf("\nIn function ");
for ( i = Limit ; i > 0 ; i-- )
Result = Result + i;
return Result;
}
/*
This is our main function - this time we are aiming to print out
at table of the sums of values from 1 to 10
*/
int main( void )
{
for ( i = 0 ; i < 10 ; i++ )
{
printf ("\nThe sum of the values 0 to %d is %d ",i,SumToValue(i));
}
return 0;
}