Friday 22 April 2011

Files: Read a text file of integers, and print the contents.

/* Read a text file of integers, and print the contents.*/
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
// Local Declarations
FILE* spIn;
int   numIn;

// Statements
spIn = fopen("P07-03.DAT", "r");
if (!spIn)
  {
   printf("Could not open file\a\n");
   exit  (101);
  } // if open fail

while ((fscanf(spIn, "%d", &numIn)) == 1)
  printf("%d ", numIn);
 
printf("\n");

return 0;
} // main


/* Results:
1 2 3 4 5 6 7 8 9 10
*/
Files:

Files: Example program on fprintf()

/* Copy a text file of integers.
  Written by:
  Date:
*/
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
// Local Declarations
FILE* spIn;
FILE* spOut;
int   numIn;
int   closeResult;

// Statements
printf("Running file copy\n");
spIn = fopen("P07-03.DAT", "r");
if (!spIn)
  {
   printf("Could not open input file\a\n");
   exit  (101);
  } // if open fail

spOut = fopen("P07-04.DAT", "w");
if (!spOut)
  {
   printf("Could not open output file\a\n");
   exit  (102);
  } // if open fail

while ((fscanf(spIn, "%d", &numIn)) == 1)
  fprintf(spOut, "%d\n", numIn);

closeResult = fclose(spOut);
if (closeResult == EOF)
  {
   printf("Could not close output file\a\n");
   exit  (201);
  } // if close fail

printf("File copy complete\n");
return 0;
} // main

/* Results:
Running file copy
File copy complete

P07-04.DAT contains
1
2
3
4
5
6
7
8
9
10
*/
Files:

Files: Example program on fopen() and fclose() functions

#include <stdio.h>
#include <stdlib.h>
// ...

int main (void)
{
// Local Declarations
FILE* spTemps;

// Statements
// ...

if ((spTemps = fopen("TEMPS.DAT", "r")) == NULL)
  {
   printf("\aERROR opening TEMPS.DAT\n");
   exit (100);
  } // if open
// ...

if (fclose(spTemps) == EOF)
  {
   printf("\aERROR closing TEMPS.DAT\n");
   exit (102);
  } // if close
// ...

} // main

/* Results:
ERROR opening TEMPS.DAT

Note: The close cannot be tested unless the file has been opened.
*/
Files:

Files: Create a grades file for transmission to Registrar.

/* Create a grades file for transmission to Registrar.*/
#include <stdio.h>

// Function Declarations
int getStu     (FILE* spStu,
                int* stuID, int*  exam1,
                int*  exam2, int* final);
int writeStu   (FILE* spGrades,
                int   stuID, int   avrg,  char grade);
void calcGrade (int   exam1, int   exam2, int  final,
                int*  avrg,  char* grade);

int main (void)
{
// Local Declarations
FILE* spStu;
FILE* spGrades;

int stuID;
int exam1;
int exam2;
int final;
int avrg;

char grade;

// Statements
printf("Begin student grading\n");
if (!(spStu = fopen ("P07-06.DAT", "r")))
  {
   printf("\aError opening student file\n");
   return 100;
  } // if open input

if (!(spGrades = fopen ("P07-06Gr.DAT", "w")))
  {
   printf("\aError opening grades file\n");
   return 102;
  } // if open output

while (getStu (spStu, &stuID, &exam1, &exam2, &final))
  {
   calcGrade (exam1, exam2, final, &avrg, &grade);
   writeStu  (spGrades, stuID, avrg, grade);
  } // while

fclose (spStu);
fclose (spGrades);

printf("End student grading\n");
return 0;
} // main

/* ======================== getStu =======================
Reads data from student file.
  Pre   spStu is an open file.
        stuID, exam1, exam2, final pass by address
  Post  reads student ID and exam scores
        if data read   --returns 1
        if EOF or error--returns 0
*/
int getStu (FILE* spStu, int* stuID, int* exam1,
            int*  exam2, int* final)
{
// Local Declarations
int ioResult;

// Statements
ioResult = fscanf(spStu, "%d%d%d%d", stuID,
                 exam1, exam2, final);
if (ioResult == EOF)
   return 0;
else if (ioResult != 4)
  {
   printf("\aError reading data\n");
   return 0;
  } // if
else
  return 1;
} // getStu

/* ==================== calcGrade ===================
Determine student grade based on absolute scale.
  Pre   exam1, exam2, and final contain scores
        avrg and grade are addresses of variables
  Post  Average and grade copied to addresses
*/
void calcGrade (int  exam1, int   exam2, int final,
                int* avrg,  char* grade)
{
// Statements
*avrg = (exam1 + exam2 + final) / 3;
if (*avrg >= 90)
  *grade = 'A';
else if (*avrg >= 80)
  *grade = 'B';
else if (*avrg >= 70)
  *grade = 'C';
else if (*avrg >= 60)
  *grade = 'D';
else
  *grade = 'F';
return;
} // calcGrade

/* ===================== writeStu ====================
Writes student grade data to output file.
  Pre   spGrades is an open file
        stuID, avrg, and grade have values to write
  Post  Data written to file
*/
int writeStu  (FILE* spGrades, int  stuID,
               int   avrg,     char grade)
{
// Statements
fprintf(spGrades, "%04d %d %c\n",
                  stuID, avrg, grade);
return 0;
} // writeStu

/* Results:
Begin student grading
End student grading

Input--------
0090 90 90 90
0089 88 90 89
0081 80 82 81
0079 79 79 79
0070 70 70 70
0069 69 69 69
0060 60 60 60
0059 59 59 59

Output----
0090 90 A \n
0089 89 B \n
0081 81 B \n
0079 79 C \n
0070 70 C \n
0069 69 D \n
0060 60 D \n
0059 59 F \n
*/
Files:

Files: This program creates a text file from the keyboard.

/* This program creates a text file from the keyboard.*/
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
// Local Declarations
char  str[100];
FILE* spOut;

// Statements
if (!(spOut = fopen ("P11-07.TXT", "w")))
  {
   printf("\aCould not open output file.\n");
   exit (100);
  } // if

printf("Enter some text and then enter <EOF> (Ctrl + d) when you finish:\n");

while (fgets(str, sizeof (str), stdin))
  fputs(str,  spOut);
fclose (spOut);
return 0;
} // main

/* Results (file contents):
Now is the time for all good students
To come to the aid of their college.
*/
Files:

Files: Demonstrate reading names from a file.

/* Demonstrate reading names from a file. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
// Local Declarations
char  first[80];
char  last[80];
int   score;
FILE* spStuScores;

// Statements
if (!(spStuScores = fopen ("P11-04.TXT", "r")))
  {
   printf("\aCould not open student file.\n");
   exit (100);
  } // if

// Read and print first name, last name, and score  
while (fscanf(spStuScores, " %s %s %d",
       first, last, &score) == 3)
  printf("%s %s %3d\n", first, last, score);

printf("End of Student List\n");
fclose (spStuScores);
return 0;
} // main

/* Results:
George Washington  95
Benedict Arnold  53
Mary Todd-Lincoln  91
End of Student List
*/
Files:

Files: Copy a text file of integers.

/* Copy a text file of integers.*/
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
// Local Declarations
FILE* spAppnd;
int   numIn;
int   closeResult;

// Statements
printf("This program appends data to a file\n");
spAppnd = fopen("P07-05.DAT", "a");
if (!spAppnd)
  {
   printf("Could not open input file\a\n");
   exit  (101);
  } // if open fail

printf("Please enter first number:  ");
while ((scanf("%d", &numIn)) != EOF)
  {
   fprintf(spAppnd, "%d\n", numIn);
   printf("Enter next number or <EOF> (Ctrl + d): ");
  } // while

closeResult = fclose(spAppnd);
if (closeResult == EOF)
  {
   printf("Could not close output file\a\n");
   exit  (201);
  } // if close fail

printf("\nFile append complete\n");
return 0;
} // main

/* Results:
First Run:
This program appends data to a file
Please enter first number:  1
Enter next number or <EOF>: 2
Enter next number or <EOF>: 3
Enter next number or <EOF>:^d
File append complete

Second Run:
This program appends data to a file
Please enter first number:  11
Enter next number or <EOF>: 12
Enter next number or <EOF>: 13
Enter next number or <EOF>: 14
Enter next number or <EOF>: 15
Enter next number or <EOF>:
File append complete

File after second run:
1
2
3
11
12
13
14
15
*/


Files

Tuesday 19 April 2011

Nested If: Example program on nested if statement

/*    Nested if in two-way selection.*/
#include < stdio.h >

 int main(void) {
  //    Local Declarations
  int a;
  int b;

  //    Statements
  printf("Please enter two integers: ");
  scanf("%d%d", & a, & b);

  if (a <= b)
   if (a < b)
    printf("%d < %d\n", a, b);
   else
    printf("%d == %d\n", a, b);
  else
   printf("%d > %d\n", a, b);

  return 0;
 } // main

/*    Results:
Please enter two integers: 10 10
10 == 10
*/

demonstrate on switch statement

/*    Test Driver to demonstrate switch statement.*/
#include < stdio.h >

 int main(void) {
  //    Local Declarations
  int printFlag = 0;

  printf("Enter an integer value: ");
  scanf(" %d", & printFlag);

  /*    Program fragment that demonstrates multiple
      cases for one set of statements
  */
  switch (printFlag) {
   case 1:
   case 3:
    printf("Good Day\n");
    printf("Odds have it!\n");
    break;

   case 2:
   case 4:
    printf("Good Day\n");
    printf("Evens have it!\n");
    break;

   default:
    printf("Good Day, IÕm confused!\n");
    printf("Bye!\n");
    break;

  } // switch
  return 0;
 } // main

/*    Results
printFlag is 3:
    Good Day
    Odds have it!
printFlag is 2:
    Good Day
    Evens have it!
printFlag is 8
    Good Day, IÕm confused!
    Bye!
*/

switch statement

Switch Statements : Example program on switch statements

/*     switch statement.       */
#include < stdio.h >
 int main(void) {
  //    Local Declarations
  int printFlag = 0;

  printf("Enter an intger value: ");
  scanf(" %d", & printFlag);

  //    Program fragment to demonstrate switch
  switch (printFlag) {
   case 1:
    printf("This is case 1\n");
    break;

   case 2:
    printf("This is case 2\n");
    break;

   default:
    printf("This is default\n");
    break;
  } // switch
  return 0;
 } // main



switch statement

logical operators: Example programs on Logical Operators

/*    Demonstrate the results of logical operators.       */
#include < stdio.h >
#include < stdbool.h >

 int main(void) {
  //    Local Declarations
  bool a = true;
  bool b = true;
  bool c = false;

  //    Statements
  printf("    %2d AND     %2d: %2d\n", a, b, a && b);
  printf("    %2d AND     %2d: %2d\n", a, c, a && c);
  printf("    %2d AND     %2d: %2d\n", c, a, c && a);
  printf("    %2d OR      %2d: %2d\n", a, c, a || c);
  printf("    %2d OR      %2d: %2d\n", c, a, c || a);
  printf("    %2d OR      %2d: %2d\n", c, c, c || c);
  printf("NOT %2d AND NOT %2d: %2d\n", a, c, !a && !c);
  printf("NOT %2d AND     %2d: %2d\n", a, c, !a && c);
  printf("    %2d AND NOT %2d: %2d\n", a, c, a && !c);
  return 0;
 } // main

/*    Results:
     1 AND      1:  1
     1 AND      0:  0
     0 AND      1:  0
     1 OR       0:  1
     0 OR       1:  1
     0 OR       0:  0
NOT  1 AND NOT  0:  0
NOT  1 AND      0:  0
     1 AND NOT  0:  1
*/

operators


Relational Operators: Example program on Relational Operators

/*    Demonstrates the results of relational operators.
       Written by:
       Date:
*/
#
include < stdio.h >

 int main(void) {
  //    Local Declarations
  int a = 5;
  int b = -3;

  //    Statements *
  printf(" %2d <  %2d is %2d\n", a, b, a < b);
  printf(" %2d == %2d is %2d\n", a, b, a == b);
  printf(" %2d != %2d is %2d\n", a, b, a != b);
  printf(" %2d >  %2d is %2d\n", a, b, a > b);
  printf(" %2d <= %2d is %2d\n", a, b, a <= b);
  printf(" %2d >= %2d is %2d\n", a, b, a >= b);
  return 0;
 } // main

/*    Results:
5 <  -3 is  0
5 == -3 is  0
5 != -3 is  1
5 >  -3 is  1
5 <= -3 is  0
5 >= -3 is  1
*/
operators

else if: Example program on else if

/*    This program reads a test score, calculates the letter
    grade based on the absolute scale, and prints it.
 */
#include < stdio.h >

 //    Function Declarations
 char scoreToGrade(int score);

int main(void) {
  //    Local Declarations
  int score;
  char grade;

  //    Statements
  printf("Enter the test score (0-100): ");
  scanf("%d", & score);

  grade = scoreToGrade(score);
  printf("The grade is: %c\n", grade);

  return 0;
 } // main

/*    =================== scoreToGrade ===================
    This function calculates letter grade for a score.
       Pre   the parameter score
       Post  returns the grade
*/
char scoreToGrade(int score) {
  //    Local Declarations
  char grade;

  //    Statements
  if (score >= 90) {
   grade = 'A';
  } else if (score >= 80) {
   grade = 'B';
  } else if (score >= 70) {
   grade = 'C';
  } else if (score >= 60) {
   grade = 'D';
  } else {
   grade = 'F';
  } //end if

  return grade;

 } // scoreToGrade

/*    Results:
Enter the test score (0-100): 90
The grade is: A
*/


 Conditional statements