Added book examples

This commit is contained in:
Louise Brown 2022-04-08 16:12:38 +01:00
parent 5b205092a7
commit 1c0a9e7b6a
59 changed files with 1381 additions and 0 deletions

43
C10/function_example.c Normal file
View File

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Define HOW the function is to be used, code comes later
float CalculateSurfaceAreaOfCylinder ( float R, float L );
// Function to calculate the volume of a cylinder
float CalculateVolumneOfCylinder ( float R, float L )
{
// Calculate \& return value
float Result;
Result = (M_PI * R * R * L);
return (Result);
}
int main(void)
{
// Declare variables
float r, l, SurfaceArea, Volume;
// Obtain values
printf("\nPlease enter the radius");
scanf("%f", &r);
printf("\nPlease enter the length");
scanf("%f", &l);
// Get and display the volume
Volume = CalculateVolumneOfCylinder(r, l);
printf ("\nThe volume is %f", Volume);
// Get and display the surface area
SurfaceArea = CalculateSurfaceAreaOfCylinder(r, l);
printf ("\nThe surface area is %f", SurfaceArea);
return 0;
}
// Calculate the surface areas of a cylinder
float CalculateSurfaceAreaOfCylinder ( float R, float L )
{
// Calculate \& return value
return (2 * M_PI * R * R ) + ( 2 * M_PI * R * L);
}

View File

@ -0,0 +1,38 @@
#include <stdio.h>
#include <stdlib.h>
// Define HOW the function is to be used, code comes later
void DisplayDayOfTheWeek ( int Day );
int main(void) // Execution starts here
{
int d; // Declare variable
// Obtain values
printf("\nPlease enter a number betwwen 0 and 6");
scanf("%d", &d);
// Use a function to display the day of the week
DisplayDayOfTheWeek(d);
return 0;
}
// Function to display day of week - nothing is returned
void DisplayDayOfTheWeek ( int Day )
{
// Display date based on value
// Case values on one line as easier to cut/paste :-)
switch (Day)
{
case 0 : printf ("Sunday") ; break;
case 1 : printf ("Monday") ; break;
case 2 : printf ("Tuesday") ; break;
/* etc. for other days of the week */
default:
printf ("Invaid day provided");
}
return; // No value needed as the return type is void
}

View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include <stdlib.h>
int main(void) // Main : Execution starts here...
{
// Declare variables - pre-populate the array
int Ages[10] = {12,34,23,11,8,19,6,44,9,16};
int i;
// Loop from 0 to 9 inclusive
for ( i = 0 ; i < 10 ; i++ )
printf ("Item %d contains value %d\n",i ,Ages[i]);
// Exit the application
return 0;
}

View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
// Main () - execution starts here
int main (void)
{
// Declare variables
int SampleData[10];
int a=0;
// Show initial value of a
printf ("Values in a is %d \n", a);
// Change an array item that IS NOT DEFINED
SampleData[10] = 20;
// See how thi affect the value in a
printf ("Values in a is %d \n", a);
// Note: we can retieive this 'invalid' value - it is however 'a' we are getting
printf ("Values in SampleData[10] is %d \n", SampleData[10]);
return (0); // Exit indicating sucess
}

View File

@ -0,0 +1,16 @@
#include <stdio.h>
#include <stdlib.h>
// Main : Execution starts here...
int main(void)
{
// Declare variable - pre-populate the array
char msg[] = {'H','i',' ','W','o','r','l','d','\0'};
// Output with printf
printf ("The text is: %s\n", msg);
puts(msg); // We could also use puts to display the string
return 0; // Exit the application
}

View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <stdlib.h>
int main(void) // Main : Execution starts here...
{
// Declare variable - pre-populate the array
char msg[] = "Hello World";
// Output with printf
printf ("The text is: %s\n", msg);
puts(msg); // We could also use puts to display the string
return 0; // Exit the application
}

20
C12/scope_of_variables.c Normal file
View File

@ -0,0 +1,20 @@
void SampleFunction1 ( int x )
{
int i,j,k;
return;
}
void SampleFunction2 ( int x )
{
int i,j,k;
SampleFunction1(x);
return;
}
// Main : Execution starts here...
int main(void)
{
int i = 1;
SampleFunction2(i);
return 0;
}

View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
int main (void )
{
// Declare a in integer
int c,d;
// Declar and integer pointer
int *ptrC;
// Some assgnments
c = 10; // C now contains the value 10
ptrC = &c; // ptrC now 'Points' to c
// Get the value of c via the pointer and store in d
d = *ptrC; // d now contains 10
printf ("\nThe value in d is %d", d);
// Change the value of c via the pointer ptrC
*ptrC = 1; //c now contains 1
printf ("\nThe value in c is %d", c);
return 0; // exit
}

24
C13/assigning_pointers.c Normal file
View File

@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
int main (void )
{
// Integer variables
int a, ValueB, d;
// integer pointers
int *ptrA=&a, *B=&ValueB, *Data=&d;
// Float variables
float f,y,z;
// Float pointers
float *pf=&f , *q=&y, *Zvalue=&z;
// We could also do this on separate lines e.g.
int SomeData;
int *Another;
Another = &SomeData;
return 0;
}

55
C14/quadratic_solver.c Normal file
View File

@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int SolveQuadraticEquation(float a, float b, float c, float *x1, float *x2)
{
float d; // For storing b^2 - 4*a*c
if ( a == 0) // Not a quadratie
{
return -1;
}
// calculate and store b*b-4*a*c for testing ans use later (if OK)
d = b*b - 4*a*c;
if ( d < 0 )
{
return -1; // Complex
}
// If we have got to here, we can calculate x1 and x2
*x1 = ( -b + sqrt (d)) / (2 * a); // Note the use of the * before x1 & x2
*x2 = ( -b - sqrt (d)) / (2 * a); // to write to the relevant memory locations
// As we got here OK, return 0 to indicate all is OK
return 0;
}
int main (void )
{
float A,B,C,x1,x2;
int retval;
printf ("Please enter coefficients A,B and C separated by a space\n");
scanf ("%f %f %f", &A, &B, &C);
// Make use of the function
retval = SolveQuadraticEquation(A, B, C, &x1, &x2);
// Use the retval to determine if we can display the answers or an derror message
if ( retval == -1 )
{
printf ("Not a quadratic\n");
}
else if (retval == -1)
{
printf ("The solution is complex - I cannot solve these\n");
}
else
{
printf("\nThe solutions are x1=%f, x2=%f", x1, x2);
}
return 0; // exit
}

View File

@ -0,0 +1,24 @@
int SolveQuadraticEquation(float a, float b, float c, float *x1, float *x2)
{
float d; // For storing b^2 - 4*a*c
if ( a == 0) // Not a quadratie
{
return -1;
}
// calculate and store b*b-4*a*c for testing ans use later (if OK)
d = b*b - 4*a*c;
if ( d < 0 )
{
return -1; // Complex
}
// If we have got to here, we can calculate x1 and x2
*x1 = ( -b + sqrt (d)) / (2 * a); // Note the use of the * before x1 & x2
*x2 = ( -b - sqrt (d)) / (2 * a); // to write to the relevant memory locations
// As we got here OK, return 0 to indicate all is OK
return 0;
}

View File

@ -0,0 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare and populate an integer array
int MyArray[10] = {2,4,6,8,10,12,14,18,20};
// Declate an integer pointer
int *pI;
// Get the start address by asking for the address iof array item [0]
pI = &MyArray[0];
// Or, use the fact the array name on its own is the start address of the array
pI = MyArray;
return 0; // Exit
}

View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int MyArray[10] = {2,4,6,8,10,12,14,16,18,20};
int *pI;
// Get the start address by asking for the address iof array item [0]
pI = &MyArray[0]; // Or use: pI = MyArray;
// Display the 1st item in the array, first be accessing rhe array
printf("The value at array item [0] is %d\n", MyArray[0]);
// Since the pointer points to the address of the 1st item we can
// access it as we would for a pointer pointing to any single variable
printf("The value at the memory address held in pI is %d\n", *pI);
return 0; // Exit
}

View File

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int MyArray[10] = {2,4,6,8,10,12,14,16,18,20};
int *pI;
int i;
// Get the start address by asking for the address iof array item [0]
pI = &MyArray[0]; // or use: pI = MyArray;
// Use loop to display values
for ( i = 0 ; i < 10 ; i++ )
{
printf ("Value at index %d (direct access to the arrays) is: %d\n", i, MyArray[i]);
printf ("Value at index %d (access via the pointer) is: %d\n", i, pI[i]);
}
return 0; // Exit
}

View File

@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int MyArray[10];
int *pI;
int i;
// Get the start address by asking for the address iof array item [0]
pI = &MyArray[0]; // or use: pI = MyArray;
// Use loop to display values
for ( i = 0 ; i < 10 ; i++ )
{
// Set the value then use the increment operator to move the pointer
// to the next memory location. you can picture this as two steps: '
//
// *pI = 5 + 4*i;
// then
// *pI++;
*pI++ = 5 + 4*i; // set value at index[i] to 5+4*i
}
// Display the values placed in the array
for ( i = 0 ; i < 10 ; i++)
{
printf("%d ", MyArray[i]);
}
return 0; // Exit
}

17
C16/alloc_example_1.c Normal file
View File

@ -0,0 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int *pData;
// Using malloc
pData = malloc ( 10000 * sizeof (int));
// Using calloc
pData = calloc ( 10000 , sizeof (int));
return 0; // Exit
}

14
C16/alloc_example_2.c Normal file
View File

@ -0,0 +1,14 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int *pData;
pData = calloc ( 10000 , sizeof (float)); // No warning
pData = (float *)calloc ( 10000 , sizeof (float)); // Warning
return 0; // Exit
}

22
C16/alloc_example_3.c Normal file
View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int *pData;
// Using calloc (same approach malloc)
pData = calloc ( 10000 , sizeof (int));
if ( pData == NULL)
{
printf ("\nMemory could not be allocated - terminating");
return -1; // Use minus one as we did not exit successfully
}
// We have our memory, make use of it here!
return 0; // Exit successfully
}

25
C16/alloc_example_4.c Normal file
View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare an integer array and an integer pointer
int *pData;
// Using calloc (same approach malloc)
pData = calloc ( 10000 , sizeof (int));
if ( pData == NULL)
{
printf ("\nMemory could not be allocated - terminating");
return -1; // Use minus one as we did not exit sucesfully
}
// We have our memory, make use of it here!
// Free up the allocated memoey
free (pData);
return 0; // Exit sucesfully
}

View File

@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
// Simple function to populate an integer array
void PopulateTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
ArrayData[i] = 2*i + 1; // Treat it like a normal array
}
}
// Simple function do display contents an integer array
void DisplayTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
printf ("Item %d of the array contains %d\n", i, ArrayData[i]);
}
}
// Main () - execution starts here
int main (void)
{
int Data[10];
// Pass the size of the array and the array to our function -
// remembering that the array name on its own is the base address,
// and so is the same as passing &Data[0]
PopulateTheArray(10, Data);
DisplayTheArray(10, Data);
return (0); // Exit indicating sucess
}

View File

@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
// Simple function to populate an integer array
void PopulateTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
ArrayData[i] = 2*i + 1; // Treat it like a normal array
}
}
// Simple function do display contents an integer array
void DisplayTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
printf ("Item %d of the array contains %d\n", i, ArrayData[i]);
}
}
// Main () - execution starts here
int main (void)
{
int iSizeForArray;
int *pData; // A pointer to hold the base address of out array
// Ask for the size of the array and store result
printf("\nPlease enter the size of the array to dynamically allocate");
scanf ("%d", &iSizeForArray);
// Use calloc with checking
pData = calloc ( iSizeForArray, sizeof (int));
// Check we got the memory
if ( pData == NULL)
{
printf ("\nSorry, I could not allocate the memory, bye!");
return -1;
}
// Pass the size, iSizeForArray) and the pointer created
// which points to the start of the sucesfully allocated memory
PopulateTheArray(iSizeForArray, pData);
DisplayTheArray(iSizeForArray, pData);
free (pData); // Free up the memory before exiting
return (0); // Exit indicating sucess
}

64
C18/binary_file_example.c Normal file
View File

@ -0,0 +1,64 @@
#include <stdio.h>
#include <stdlib.h>
// Main () - execution starts here
int main (void)
{
// Declate file stream variables
FILE *fInput, *fOutput;
// Other variables needed
int i;
int SampleArray[10] = {1,2,3,4,5,6,7,8,9,10};
float f = 23.4;
// Try and open the binary "numbers.dat" (in the current directory) file for writing
fOutput = fopen ("numbers.dat", "wb");
// Check we were able to open the file
if ( fOutput == NULL)
{
printf ("\nThe file could not be opened for writing, exiting");
return -1;
}
// Write out a single float to the binary file
fwrite ( &f, sizeof(float), 1 , fOutput);
// Now the entire array on one go
fwrite ( SampleArray, sizeof(int), 10 , fOutput);
// And close the file
fclose (fOutput);
// Try and open the binary "numbers.dat" (in the current directory) file for reading
fInput = fopen ("numbers.dat", "rb");
// Check we were able to open the file
if ( fInput== NULL)
{
printf ("\nthe file could not be opened for reading, exiting");
return -1;
}
// Read a single float from the binary file into f
fread ( &f, sizeof(float), 1 , fOutput);
// Now read the entire array on one go
fread ( SampleArray, sizeof(int), 10 , fOutput);
// Display the values read from the file on the screen
printf ("The value read into f is %f\n", f);;
for ( i = 0 ; i < 10 ; i++)
{
printf ("Item %d of the array contains %d\n",i, SampleArray[i]);
}
// And close the file
fclose (fInput);
return (0); // Exit indicating sucess
}

52
C18/file_open_example.c Normal file
View File

@ -0,0 +1,52 @@
#include <stdio.h>
#include <stdlib.h>
// Main () - execution starts here
int main (void)
{
// Declate file stream variables
FILE *fInput, *fOutput, *fRecords;
// Try and open the text "sample.txt" (in the current directory) file for reading
fInput = fopen ("sample.txt", "r");
// Check we were able to open the file
if ( fInput == NULL)
{
printf ("\nthe file could not be opened");
return -1; // Exit as unsuccessful
}
fclose (fInput); // Close the file
// Try and open the binary "samples.dat" (in the current directory) file for writing
// if a file of this name already exists it will be deleted
fOutput = fopen ("samples.dat", "wb");
// Check we were able to open the file
if ( fOutput == NULL)
{
printf ("\nthe file could not be opened");
return -1; // Exit as unsuccessful
}
fclose (fOutput); // Close the file
// Open, for appending, the text file "records.txt". If the file does not already
// exists, a new one of this name will be created (as if "w") were the mocde
fRecords = fopen ("records.txt", "a");
// Check we were able to open the file
if ( fRecords == NULL)
{
printf ("\nthe file could not be opened");
return -1; // Exit as unsuccessful
}
fclose (fRecords);
return (0); // Exit indicating sucess
}

55
C18/text_file_example.c Normal file
View File

@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
// Main () - execution starts here
int main (void)
{
// Declate file stream variables
FILE *fInput, *fOutput;
// Other variables needed
int i,d;
// Try and open the text "sample.txt" (in the current directory) file for writing
fOutput = fopen ("numbers.txt", "w");
// Check we were able to open the file
if ( fOutput == NULL)
{
printf ("\nthe file could not be opened for writing, exiting");
return -1;
}
// Use a loop to write values to the newly created file
for ( i = 1 ; i <= 10 ; i++)
{
fprintf (fOutput, "%d\n", i);
}
// And close the file
fclose (fOutput);
// Try and open the binary "numbers " (in the current directory) file for reading
fInput = fopen ("numbers.txt", "r");
// Check we were able to open the file
if ( fInput == NULL)
{
printf ("\nthe file could not be opened for reading, exiting");
return -1;
}
// Read, line by line the 10 values written into variable d
// and then display the contents of d on the screen
for ( i = 1 ; i <= 10 ; i++)
{
fscanf (fInput, "%d", &d);
printf ("Value read from file %d\n",d);
}
// And close the file
fclose (fInput);
return (0); // Exit indicating success
}

18
C19/define_example.c Normal file
View File

@ -0,0 +1,18 @@
#define UP 1
#define DOWN 2
int main()
{
int i = 1;
if (i == UP )
{
// Do something
}
if ( i == DOWN)
{
// Doe something else
}
return 0;
}

22
C19/enum_example.c Normal file
View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
enum DOW { sun, mon, tue, wed, thu, fri, sat } ;
// Main () - execution starts here
int main (void)
{
enum DOW day;
/* Code that get a value for 'day' */
day = tue;
switch (day)
{
case sun : printf ("Sunday\n") ; break ;
case mon : printf ("Monday\n") ; break ;
case tue : printf ("Tuesday\n") ; break ;
/* etc. */
}
return (0); // Exit indicating success
}

View File

@ -0,0 +1,26 @@
#include <stdio.h>
#include <stdlib.h>
void DisplayHelloWorld (void)
{
static int k = 0; // Counter for how many times the function is called
printf ("Hello World\n");
// Increment counter and display value
k = k + 1;
printf ("I have now said this %d times\n",k);
}
// Main () - execution starts here
int main (void)
{
int i;
// Loop calling out function 10 times
for ( i =0 ; i < 10 ; i++ )
{
DisplayHelloWorld();
}
return (0); // Exit indicating success
}

View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <conio.h>
#define DEBUG_ON 1
int main(void)
{
#if DEBUG_ON == 1
printf("Debug mode - about to do something\n");
#else
print("Running in standard mode");
#endif
return 0;
}

View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <conio.h>
#define DEBUG_ON 1
int main(void)
{
#ifdef DEBUG_ON
printf("Debug mode - about to do something\n");
#else
print("Running in standard mode");
#endif
return 0;
}

View File

@ -0,0 +1,8 @@
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
int main(void)
{
printf("The minimum value of 10 and 20 is: %d\n", MIN(10,20));
return 0;
}

19
C21/sprintf_example.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char FileName[100];
for ( i = 1 ; i < 10 ; i++)
{
//'Print' text into string
sprintf(FileName , "file%d.dat" , i);
// Sidplay the name created
printf("Current file name: %s\n", FileName);
}
return 0;
}

10
C3/hello_world.c Normal file
View File

@ -0,0 +1,10 @@
#include <stdlib.h>
#include <stdio.h>
/* My first program */
int main(void)
{
// This is a single line of comment
printf("Hello World");
return 0;
}

20
C4/correct_answer.c Normal file
View File

@ -0,0 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare and initialise as required
int a = 1,b = 4;
float ans;
// Perform calculation
// This time a & b are treated as if they are floats
// the result of this float calculation is stored in ans
ans = (float)a / (float)b;
// Display answer
printf ("\nThe answer is %f",ans);
return 0;
}

13
C4/declare_a_string.c Normal file
View File

@ -0,0 +1,13 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// A variable to store a name (maximum 49 characters)
char Name[50];
// Declare multiple strings on the same line
char AddressLine1[100], AddressLine2[100], PostCode[10];
// all done
return 0;
}

View File

@ -0,0 +1,4 @@
#include <stdio.h>
int main(void) { int revenue = 80; int cost = 50; int roi;
roi = (100 * (revenue - cost)) / cost; if (roi >= 0) {
printf ("%d\n", roi); } return 0; }

4
C4/poor_layout.c Normal file
View File

@ -0,0 +1,4 @@
#include <stdio.h>
/* My first program */
int main(void) { printf("Hello World"); return 0; }

19
C4/reformatted_code.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
int main(void)
{
// Declare variables and give initial values
int revenue = 80;
int cost = 50;
int roi;
// Perform calculation
roi = (100 * (revenue - cost)) / cost;
// Make decision based on value of roi
if (roi >= 0)
{
printf ("%d\n", roi);
}
return 0; // Exit indicating success
}

8
C4/simple_claculation.c Normal file
View File

@ -0,0 +1,8 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a = 6,b = 7,c; // Declare and initialiase as required
c = a + b; // Add the values and store in c
}

8
C4/well_laid_out_code.c Normal file
View File

@ -0,0 +1,8 @@
#include <stdio.h>
/* My first program */
int main(void)
{
printf("Hello World");
return 0;
}

17
C4/wrong_answer.c Normal file
View File

@ -0,0 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare and initialiase as required
int a = 1,b = 4;
float ans;
ans = a / b; // Perform calculation
// Display answer
printf ("\nThe answer is %f",ans);
// Exit from program
return 0;
}

15
C5/displaying_variables.c Normal file
View File

@ -0,0 +1,15 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 1, b = 2;
float f = 1.23f;
// Use printf display text on the screen
printf ("The variables are\na = %d\nb=%d\nf=%f", a, b, f);
// Exit from main
return 0;
}

24
C5/formatting_numbers.c Normal file
View File

@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 123;
float f = 12.456f;
// Use printf display text on the screen
printf ("Examples of integer formatting\n");
printf ("a = %d (no modifier)\n", a);
printf ("a = %6d (w:6, justify:right)\n", a);
printf ("a = %-6d (w:6 )\n", a);
// Use printf display text on the screen
printf ("Examples of float formatting\n");
printf ("f = %f (no modifier)\n", f);
printf ("f = %6.2f (w:6, 2dp, justify:right)\n", f);
printf ("f = %-6.1f (w:6, 1dp)\n", f);
// Exit from main
return 0;
}

17
C5/not_displaying.c Normal file
View File

@ -0,0 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 1, b = 2;
float f = 1.23f;
// Use printf display text on the screen
printf ("The variables are a, b and f");
// Exit from main
return 0;
}

12
C5/printf_example_1.c Normal file
View File

@ -0,0 +1,12 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf ("This is my first computer program");
printf ("Hello World");
return 0;
}

12
C5/printf_example_2.c Normal file
View File

@ -0,0 +1,12 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf ("This is my first computer program\n");
printf ("Hello World\n");
return 0;
}

22
C6/inc_dec_examples.c Normal file
View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a, b;
// Note: Order of a,b indicates the order in which operations are carried out on execution
// Increment operators
b = 3;
a = ++b; // b is now 4, a is also 4
a = b++; // a is 4, b is now 5,
// Decrement operators (reset a back to 3)
b = 3;
a = b--; // a is 3, b is now 2
a = --b; // b is now 1, a is also 1
return 0; // Exit from main
}

19
C7/getchar_example.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// declare variable
char c;
// Wait for a kepypress, store result in c
c = getchar();
// Display on the screen using printf
printf ("The charcter pressed was %c\n", c);
// Display the charcter using putchar()
putchar(c);
return 0; // Exit from main
}

28
C7/scanf_example_1.c Normal file
View File

@ -0,0 +1,28 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a; // Declare some variables
float f;
// Use printf to prompt the use to enter an integer
printf ("Please enter an integer\n");
// use scanf with %d to read into 'a'
scanf ("%d",&a); // note the important &
// And display on the screen
printf ("The value you entered for a is %d\n", a);
// Use printf to prompt the use to enter an float
printf ("Please enter a float\n");
// use scanf with %f to read into 'f'
scanf ("%f",&f); // note the important &
// And display on the screen
printf ("The value you entered for f is %f\n", f);
return 0; // Exit from main
}

28
C7/scanf_example_2.c Normal file
View File

@ -0,0 +1,28 @@
#include <stdio.h>
int main(void)
{
// Declare some variables
int a,b,c;
float f,g;
// Use printf to prompt the use to enter 3 integers
printf ("Please enter three integer\n");
// use scanf with %d to read into a, b and c
scanf ("%d %d %d",&a, &b, &c); // note the important &
// And display on the screen
printf ("The values entered were %d %d %d\n", a, b, c);
// Use printf to prompt the use to enter an float
printf ("Please enter two floats\n");
// use scanf with %f to read into f ang g
scanf ("%f %f",&f, &g); // note the important &
// And display on the screen
printf ("The value you entered were %f and %f \n", f,g);
return 0; // Exit from main
}

19
C7/string_with_gets.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Declare variable - maximum 99 characters
char str[100];
// Prompt for text
printf("enter some text\n");
// Store intput in str
gets(str);
// Display a message on the screen
printf("you entered : %s\n", str);
// Exit from main
return 0;
}

20
C7/string_with_scanf.c Normal file
View File

@ -0,0 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
char name[50];
// Wait for a kepypress, store result in c
printf ("Please enter your name");
// read in using scanf with %s
scanf ("%s",name);
// Display on the screen using printf
printf ("Hello %s\n", name);
// Exit from main
return 0;
}

22
C8/if_example.c Normal file
View File

@ -0,0 +1,22 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 7, b=6;
// A single line of code conditional on the value of a
if ( a == 7 )
printf ("The value of a is 7 - so I will do this\n");
// Multiple lines of code conditional on b not equalling 4
// so then need to be placed inside { and }
if ( b != 4 )
{
printf ("The value of b is not 4\n");
printf ("So I will do multiple tasks\n");
}
return 0; // Exit from main
}

29
C8/switch_example_1.c Normal file
View File

@ -0,0 +1,29 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 1;
switch ( a )
{
case 0 :
printf ("Sunday\n");
break ; // end of the lines of code to execute
case 1:
printf ("Monday\n");
break ; // end of the lines of code to execute
case 2:
printf ("Tuesday\n");
break ; // end of the lines of code to execute
// etc...
default: // If no case is met (OPTIONAL)
printf ("\nThe value supplied is out of range\n");
}
return 0;
}

25
C8/switch_example_2.c Normal file
View File

@ -0,0 +1,25 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 1;
switch ( a )
{
case 1 :
case 2 :
case 3 :
// Code to do if a is 1, 2 or 3
break ; // end of the lines of code to execute
case 4:
case 5:
// Code to do if a is 4 or 5
break ; // end of the lines of code to execute
default: // If no case is met (OPTIONAL)
// Code to do if no case is met
}
return 0;
}

23
C8/switch_example_3.c Normal file
View File

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Declare some variables
int a = 1;
switch ( a )
{
case 1 :
printf ("This is case 1\n");
case 2 :
printf ("This is case 2\n");
case 3 :
printf ("This is case 3\n");
break ; // end of the lines of code to execute
default: // If no case is met
printf ("This default case\n");
// Code to do if no case is met
}
return 0;
}

24
C9/do_while_loop.c Normal file
View File

@ -0,0 +1,24 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int age; // Declare variable, no need to initialise this time
// as we read into it before it is tested against
// The loop is always entered as the test is at the end
do
{
// Code must be executed at least once
printf ("\nPlease enter your age");
scanf("%d", &age);
printf ("You are %d years old\n", age);
// Test is now made and the code
// repeats if the test equates as non-zerp
// (i.e. is age is not zero)
}
while ( age != 0);
return 0;
}

31
C9/for_loop_examples.c Normal file
View File

@ -0,0 +1,31 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// Ddeclare variable and initialise to 1
int i;
// Count up from 1 to 100 in steps of 1
// Note the test could also be: i <= 100
for ( i = 0 ; i < 101 ; i++ )
{
printf ("The value of i is %d\n",i);
}
// Count down form 10 to zero
// Note: we could also use the test: i != 0
for ( i = 10 ; i >= 0 ; i-- )
{
printf ("The value of i is %d\n",i);
}
// Count up from 1 to 100 in steps of 3
// Note the test could also be: i <= 100
// Increement could also be written as i+=3
for ( i = 0 ; i < 101 ; i=i+1 )
{
printf ("The value of i is %d\n",i);
}
return 0;
}

23
C9/infinite_while_loop.c Normal file
View File

@ -0,0 +1,23 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int age ; // Declare variable, no need to initialise this time
// as the test condition is not based on its value
// This is always non-zero, the loop will never break
while ( 1 )
{
// Code in {} executed if condition is true (non-zero)
printf ("\nPlease enter your age");
scanf("%d", &age);
printf ("You are %d years old\n", age);
// Code now goes back and repeats
// as the conditions is always non-zero (true)
}
return 0; // Exit code
}

19
C9/while_loop.c Normal file
View File

@ -0,0 +1,19 @@
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int age = 1; // Declare variable and initialise to 1
while ( age != 0) // Loop as long as age is not zero
{
// Code in {} executed if condition is true (non-zero)
printf ("\nPlease enter your age");
scanf("%d", &age);
printf ("You are %d years old\n", age);
// Code now goes back and repeats the test with the value of age just entered
}
return 0; // Exit code
}