Difference between revisions of "Principles of Computer Programming"

From David Vernon's Wiki
Jump to: navigation, search
Line 15: Line 15:
 
  }
 
  }
  
If you compile and run this on Microsoft Visual C++, you won't see anything because the window in which the program executes disappears as soon as the program exits.  One solution is wait until the user to press a key to exit.  You can use the following code to do this.
+
If you compile and run this on Microsoft Visual C++, you won't see anything because the window in which the program executes disappears as soon as the program exits.  One solution is to wait until the user presses a key to exit.  You can use the following code to do this.
  
 
  #include <conio.h>
 
  #include <conio.h>

Revision as of 12:20, 14 January 2020

Here are some code segments for the examples in the course on principles of computer programming.

/* Example 1                                       */
/* This is a C program to ask you to type a letter */
/* and then to tell you what you typed             */

#include <stdio.h>

void main() { 
   char letter;

   printf("Please type a letter & then press Return >>");
   scanf("%c",&letter);
   printf("You typed the letter %c", letter);
}

If you compile and run this on Microsoft Visual C++, you won't see anything because the window in which the program executes disappears as soon as the program exits. One solution is to wait until the user presses a key to exit. You can use the following code to do this.

#include <conio.h>

  ...

printf("\nPress any key to continue\n");
_getch();

Here are the rest of the examples.

/* Example 2                                       */
/* This is a C program to ask you to enter two     */
/* numbers; it then compares them and prints a     */
/* message to say whether they are equal or not    */

#include <stdio.h> 

void main() {
 
   int first_number, second_number;

   printf("Type a number and then press Enter >>");
   scanf("%d",&first_number);

  printf("Type another number and then press Enter >>");
  scanf("%d",&second_number);

  if (first_number == second_number) 
     printf("The two numbers %d are identical", first_number);
  else
     printf("The two numbers %d and %d are different",  first_number, second_number);
}
/* Example 2b                                                          */
/* This is a C program to ask you to enter three   */
/* numbers; it then compares them and prints a   */
/* message to say whether they are equal or not  */  

#include <stdio.h> 

void main() {

   int first_number, second_number, third_number;

   printf("Please type three numbers .... \n");
   printf("Enter the first number >>");
   scanf("%d",&first_number);

   printf("Enter the second number >>");
   scanf("%d",&second_number);

   printf("Enter the third number >>");
   scanf("%d",&third_number);


   if (first_number == second_number)
      if (second_number == third_number)
         printf("The three numbers %d are identical", 
                 first_number);

   if (first_number != second_number)
      if (second_number != third_number)
         if (first_number != third_number)
            printf("The three numbers %d %d %d are all different", 
                   first_number, second_number, third_number);
 
} 
/* Example 3a                                        */
/* Compute the total value of 7 Scrabble letters     */
/* Input:  the user is prompted to enter each letter */
/*         in turn                                   */
/* Output: the program prints the sum of the seven   */
/*         individual letter values                  */
 
#include <stdio.h> 
#include <ctype.h>

#define TRUE  1 
#define FALSE 0

void main() {

   char letter, enter;
   int scrabble_value, 
       total_scrabble_value,   
       i;   /*  not the same as 'i'  */
   int debug; 

 
   /* debug is a flag.  If it is TRUE we will execute some printf */
   /* statements to help see what the program is doing.           */
   /* if it is FALSE, we won't!                                   */

   debug = TRUE;

   /* initialize variables */

   total_scrabble_value = 0;
   scrabble_value = 0;

   /* use a for loop to read seven values*/

   for (i=0; i < 7; i++) 
   {
      printf("Please type a letter and then press Return >>");
      scanf("%c",&letter);
      scanf("%c",&enter);        /* skip enter character */

      letter = toupper(letter);  /* convert the letter to uppercase    */
                                 /* note this works even if the letter */
                                 /* is already in upper case           */

      if ((letter == 'A') || 
          (letter == 'E') ||
          (letter == 'I') || 
          (letter == 'L') || 
          (letter == 'N') || 
          (letter == 'O') || 
          (letter == 'R') || 
          (letter == 'S') || 
          (letter == 'T') || 
          (letter == 'U')) 

      {
         scrabble_value = 1;
         if (debug == TRUE)
            printf("the letter %c has the value %d\n", letter, scrabble_value);
      }
      else 
         if ((letter == 'D') || 
             (letter == 'G')) 
         {
            scrabble_value = 2;
            if (debug == TRUE) {
               printf("the letter %c has the value %d\n", letter, scrabble_value);
            } 
         } 
         else 
            if ((letter == 'B') || 
                (letter == 'C') || 
                (letter == 'M') || 
                (letter == 'P')) 
            { 
               scrabble_value = 3;
               if (debug == TRUE)
                  printf("the letter %c has the value %d\n", letter, scrabble_value);
            } 
            else 
               if ((letter == 'F') || 
                   (letter == 'H') || 
                   (letter == 'V') || 
                   (letter == 'W') || 
                   (letter == 'Y')) 
               { 
                 scrabble_value = 4;
                  if (debug == TRUE)
                     printf("the letter %c has the value %d\n", letter, scrabble_value);
               } 
               else 
                  if ((letter == 'K')) 
                  {
                     scrabble_value = 5;
                     if (debug == TRUE)
                        printf("the letter %c has the value %d\n", letter, scrabble_value);
                  } 
                  else 
                     if ((letter == 'J') || 
                         (letter == 'X') ) 
                     {
                        scrabble_value = 8;
                        if (debug == TRUE)
                           printf("the letter %c has the value %d\n", letter, scrabble_value);
                     } 
                     else 
                        if ((letter == 'Z') || 
                            (letter == 'Q') ) 
                        {
                           scrabble_value = 10;
                           if (debug == TRUE)
                              printf("the letter %c has the value %d\n", letter, scrabble_value);
                        } 
   
                        else

                           printf("You typed the character %c ... that's not allowed\n", letter);

      /* now add the value to the total */
      
      total_scrabble_value = total_scrabble_value + scrabble_value;
  }  
 
   printf("The Scrabble value of the seven letters is %d", 
           total_scrabble_value);
} 
/* Example 3b                                        */
/* Compute the total value of 7 Scrabble letters     */
/* Input:  the user is prompted to enter each letter */
/*         in turn                                   */
/* Output: the program prints the sum of the seven   */
/*         individual letter values                  */
 
#include <stdio.h> 
#include <ctype.h>

#define TRUE  1
#define FALSE 0

void main() {

   char letter, enter;
   int scrabble_value, 
       total_scrabble_value,   
       i;   /*  not the same as 'i'  */
   int debug;


   /* debug is a flag.  If it is TRUE we will execute some printf */
   /* statements to help see what the program is doing.           */
   /* if it is FALSE, we won't!                                   */

   debug = TRUE;

   /* initialize variables */

   total_scrabble_value = 0;
   scrabble_value = 0;

   /* use a for loop to read seven values*/

   for (i=0; i < 7; i++) 
   {
      printf("Please type a letter and then press Return >>");
      scanf("%c",&letter);
      scanf("%c",&enter);        /* skip enter character */

      letter = toupper(letter);  /* convert the letter to uppercase    */
                                 /* note this works even if the letter */
                                 /* is already in upper case           */


      switch (letter) {

         case 'A':
         case 'E':
         case 'I':
         case 'L':
         case 'N':
         case 'O':
         case 'R':
         case 'S':
         case 'T':
         case 'U':  scrabble_value = 1;
                    if (debug == TRUE)
                       printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         case 'D':
         case 'G':  scrabble_value = 2;
                    if (debug == TRUE) {
                       printf("the letter %c has the value %d\n", letter, scrabble_value);
                    }
                    break;

         case 'B':
         case 'C':  
         case 'M':
         case 'P':  scrabble_value = 3;
                    if (debug == TRUE)
                       printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         case 'F':
         case 'H':  
         case 'V':
         case 'W':  
         case 'Y':  scrabble_value = 4;
                    if (debug == TRUE)
                        printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         case 'K':  scrabble_value = 5;
                    if (debug == TRUE)
                       printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         case 'J':
         case 'X':  scrabble_value = 8;
                    if (debug == TRUE)
                       printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         case 'Z':
         case 'Q':  scrabble_value = 10;
                    if (debug == TRUE)
                        printf("the letter %c has the value %d\n", letter, scrabble_value);
                    break;

         default:   printf("You typed the character %c ... that's not allowed\n", letter);
                    break;

      } /* end of the switch statement */

      /* now add the value to the total */
      
      total_scrabble_value = total_scrabble_value + scrabble_value;
   }

   printf("The Scrabble value of the seven letters is %d", 
           total_scrabble_value);
} 
/* A program to prompt the user three times and reads three numbers. */
/* It compare these three numbers and tell the user whether          */
/*                                                                   */
/* - all three numbers are the same                                  */
/* - all three numbers are different                                 */
/* - just two numbers are the same                                   */
/*   in this case, it also tells the user which two numbers they are */
/*                                                                   */
/* The program continues to ask the user for input until he enters   */
/* three zeros.                                                      */   

#include <stdio.h> 

#define TRUE  1
#define FALSE 0

void main() {
   int n1, n2, n3;

   /* give the numbers initial values */

   n1 = 1; 
   n2 = 1; 
   n3 = 1;

   /* while the three numbers are not all zero */

   while ((n1 != 0) && (n2 != 0) && (n3 != 0)) {
 
      printf("Please enter the first number  >>");
      scanf("%d",&n1);
  
      printf("Please enter the second number >>");
      scanf("%d",&n2);

      printf("Please enter the third number  >>");
      scanf("%d",&n3);

      
      /* check to see if they are all the same */

      if ((n1 == n2) && (n2 == n3) && (n1 == n3)) {
         printf(" The three numbers are all the same. \n"); 
      } 
      else {
         if ((n1 != n2) && (n2 != n3) && (n1 != n3)) {
	          printf("The three numbers are all the different.\n");
	       }
         else {
     
            /* two are the same -  which are they? */

            if (n1 == n2) {
	            printf("The first and second numbers are the same: %d\n”,
               n1, n2);
	         }
	         else {
	            if (n2 == n3) {
	               printf("The second and third numbers are the same: %d\n",
                  n2, n3);
	            }

	            else {  /* no need to check if the first and third    */
		               /* are the same ... it's the only possibility */
        	    printf("The first and third numbers are the same:%d\n",
                   n1, n2);                                                         
	            }
	         }
	      }
       }
    }
}  
/* a program to call a function called max */
/* max returns the maximum of two floating point numbers */ 

#include <stdio.h>

float max(float a, float b)
{
    float  c;  /* local variable */

   if (a >  b) {
      c = a;  
   }
  else {
    c = b;   
  }
  return(c);
} 



void main()
{
   FILE *fp_in, *fp_out; 

   float x, y, z;
   int end_of_file;
 

   /* open the files */
   /* no checking for the moment */

   fp_in = fopen("input.txt", "r");
   fp_out = fopen("max.txt", "w");


   end_of_file = fscanf(fp_in, "%f %f", &x, &y);
   while (end_of_file != EOF) 
   {

      z = max(x, y);
      fprintf(fp_out, "%5.2f\n ", z);

     end_of_file = fscanf(fp_in, "%f %f", &x, &y);

   };


   fclose(fp_in);
   fclose(fp_out);

}
/* Program to read pairs of numbers from the input file    */
/* and calls a function max which returns the maximum of   */
/* of two floating point numbers.                          */
/* This maximum is then written to an output file          */
/* the input file is read until we reach the end of file   */


#include <stdio.h>

float max(float a, float b)
{
  float  c;  /* local variable */ 

  if (a >  b) {
    c = a;  
  } 
  else {
    c = b;   
  } 
  return(c);
}

void main()
{
   FILE *fp_in, *fp_out;

   float x, y, z;
   int end_of_file;


   /* open the files             */
   /* no checking for the moment */

   fp_in = fopen("input.txt", "r");
   fp_out = fopen("max.txt", "w");


   /* read until we reach the end of file ... version A */

   end_of_file = fscanf(fp_in, "%f %f", &x, &y);
   while (end_of_file != EOF) 
   {
      z = max(x, y);
      fprintf(fp_out, "%5.2f\n ", z);

      end_of_file = fscanf(fp_in, "%f %f", &x, &y);

   };

   /* read until we reach the end of file ... version B */
   /* note: this version is equivalent to version A     */
   /* but it puts the fscanf in the while condition     */

   /*   while (fscanf(fp_in, "%f %f", &x, &y) != EOF)   */
   /*   {                                               */
   /*      z = max(x, y);                               */
   /*      fprintf(fp_out, "%5.2f\n ", z);              */
   /*    };                                              */

   fclose(fp_in);
   fclose(fp_out);

} 
/* Program to read a sequence of numbers from the input file,    */
/* compute the average of the numbers (ignoring zeros)           */
/* replace all occurrences of zero with the average              */
/* and write the numbers to an output file                       */

/* Note: we use four loops ... we could use fewer but it         */
/* means doing more than one thing in each loop ...              */
/* we will do this next day.                                     */

#include <stdio.h>

#define MAX 100

void main()
{
   FILE *fp_in, *fp_out;

   float numbers[MAX];
   float average, sum=0;
   int n, count, i, non_zeros;
   int end_of_file;


   /* open the files             */
   /* no checking for the moment */

   fp_in = fopen("input.txt", "r");
   fp_out = fopen("output.txt", "w");


   /* read until we reach the end of file ... version A */
   /* store all the numbers in an array                 */

   count= 0;
   end_of_file = fscanf(fp_in, "%d", &n);
   while (end_of_file != EOF) 
   { 
      numbers[count] = n;
      count = count + 1;
      end_of_file = fscanf(fp_in, "%d", &n);
   } 

   /* the integers are in the array numbers and the variable count */
   /* hold the number we read                                      */

   /* find the average but ignore the zeros */

   sum = 0;
   non_zeros = 0;
   for (i=0; i<count; i++)
   { 
     if (numbers[i] != 0) {
        sum = sum + numbers[i];
        non_zeros = non_zeros + 1;
     } 
   }
   average = sum / non_zeros; 


   /* replace the zero with the average */

   for (i=0; i<count; i++)
   {
     if (numbers[i] == 0) {
        numbers[i]= average;
     }
   } 
 

   /* write out all the numbers to the output file */

   for (i=0; i<count; i++)
   {
     fprintf(fp_out, "%f ", numbers[i]);
   } 
 
   fclose(fp_in);
   fclose(fp_out);
}
/* Program to read a file of integer numbers, 5 per line        */
/* the 5 numbers represent the x, y, r, g, b values of a point  */
/* Each point is stored in an array                             */
/* Write out the r, g, b values of each point to an output file */
/*                                                              */
/* Input file: points.txt                                       */
/* Output file: colours.txt                                     */
/*                                                              */
/* NOTE: this program is intended to illustrate the use of      */
/*       structures in C                                        */ 

#include <stdio.h> 

main() {
  
   /*** define structure types ***/

   struct colour {
      int red;
      int green;
      int blue;
   }; 

   struct point {
      int x;
      int y;
      struct colour clr;
   }; 

   FILE *fin, *fout;

   struct point ps[100];  /* assume a maximum of 100 points in the input file */

   int temp_r, temp_g, temp_b, temp_x, temp_y,  i, count;

   fin = fopen("points.txt", "r");
   if (fin == 0) {
      printf("Error ... can't open file points.txt\n");
      exit(0);
   } 

   fout = fopen("colours.txt", "w");
   if (fout == 0) {
      printf("Error ... can't open file colours.txt\n");
      exit(0);
   } 

   /*  files are open so now we read in the point information */

   i = 0;

   while (fscanf(fin, "%d %d %d %d %d", &temp_x, &temp_y, 
                                        &temp_r, &temp_g, &temp_b) != EOF)   {

       /* store the values read in my array of points */

       ps[i].x  = temp_x;
       ps[i].y  = temp_y;
       ps[i].clr.red  = temp_r;
       ps[i].clr.green  = temp_g;
       ps[i].clr.blue  = temp_b;

       i++;
   }

   /* remember how many points we read */

   count = i;

   /* now write out just the rgb values to the output file */

   for (i=0; i<count; i++) {
      fprintf(fout, "%d %d %d \n", ps[i].clr.red, ps[i].clr.green, ps[i].clr.blue);
   }
   fclose(fin);
   fclose(fout);
} 
/* Program to read a file of integer numbers, 5 per line        */
/* the 5 numbers represent the x, y, r, g, b values of a point  */
/* Each point is stored in an array                             */
/* Remove all duplicate points (i.e. points with the same x y   */
/* value.                                                       */
/* Write out the x, y, r, g, b values of each point to an       */
/* file                                                         */
/*                                                              */
/* Input file: points.txt                                       */
/* Output file: new_points.txt                                  */
/*                                                              */
/* NOTE: this program is intended to illustrate the use of      */
/*       structures in C                                        */ 

#include <stdio.h>

main() {
  
   /*** define structure types ***/

   struct colour {
      int red;
      int green;
      int blue;
   }; 
 
   struct point {
      int x;
      int y;
      struct colour clr;
   }; 

   FILE *fin, *fout;
   struct point ps[100];  /* assume a maximum of 100 points in the input file */
   int temp_r, temp_g, temp_b, temp_x, temp_y,  i, j, k, count;

   fin = fopen("points.txt", "r");
   if (fin == 0) {
      printf("Error ... can't open file points.txt\n");
      exit(0);
   } 

   fout = fopen("new_points.txt", "w");
   if (fout == 0) {
      printf("Error ... can't open file colours.txt\n");
      exit(0);
   } 

   /*  files are open so now we read in the point information */

   i = 0;
   while (fscanf(fin, "%d %d %d %d %d", &temp_x, &temp_y, 
                                        &temp_r, &temp_g, &temp_b) != EOF)   {

       /* store the values read in my array of points */

       ps[i].x  = temp_x;
       ps[i].y  = temp_y;
       ps[i].clr.red  = temp_r;
       ps[i].clr.green  = temp_g;
       ps[i].clr.blue  = temp_b;

       i++;
   }

   /* remember how many points we read */

   count = i;

   /*** this section eliminates the duplicate values ***/

   /* look at each element in turn */

   for (i=0; i<count; i++) {

       /* check for duplicates in all the remaining elements */

       for (j=i+1; j<count; j++)  {
          if ((ps[j].x == ps[i].x)  &&  (ps[j].y == ps[i].y))  {

             /* we have found duplicate so shift all the rest */

             for (k=j; k<count-1; k++) {
                ps[k] = ps[k+1];
             }
             count = count - 1;
             j--;  /* decrement j so that when it is incremented in the     */
                   /* for loop it will still index the same element,        */
                   /* i.e. the element that was shifted into the j position */
          }
       } 
   }

   /* now write out the x, y, r, g, b values to the output file */

   for (i=0; i<count; i++) {
      fprintf(fout, "%5d %5d %5d %5d %5d \n", 
                    ps[i].x, ps[i].y, ps[i].clr.red, ps[i].clr.green, ps[i].clr.blue);
   } 
   fclose(fin);
   fclose(fout);
}