Rabu, 01 April 2026

C++ From Year 1995 File From "S"

 // Filename: SALES4.CPP

// Get and average up to four sales values.

#include <iostream.h>

void main()

{

  int count;     // for loop's control variable

  float sales;   // Will hold each weeks sales value

  float total=0.0;

  float avg;


  for (count=0; count<4; count++)

    { cout << "What is the sales value for week "

           << (count+1) << "? ";

      cin >> sales;

      if (sales < 0.0)

        { break; }

      total+=sales;  // Update the sales value

    }


  avg = total / count;  // Count holds the number of

                        // sales values entered

  cout.precision(2);

  cout << "The monthly average is $" << avg << endl;

  return;

}

======================

// Filename: SEASONS.CPP

// Stores Fahrenheit temperatures for

// four seasons and prints the values

#include <iostream.h>


void main()

{

  int c;   // for-loop counter

  // Winter, Spring, Summer, Autumn

  float temps[4] = { 32.0, 75.0, 87.5, 72.0};


  cout.precision(1);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << "Here are the temperatures from Winter to Autumn:" << endl;

  for (c = 0; c < 4; c++)

    { cout << *(temps + c) << endl; }


  cout << endl << "Here are the temperatures from Autumn to Winter:" << endl;

  for (c = 3; c >= 0; c--)

    { cout << *(temps+c) << endl; }


  return;

}

===========================

// Filename: SEQUENCS.CPP

// Prints the first 20 odd, then even, numbers.

// Once done, it prints them in reverse order.

#include <iostream.h>

void main()

{

  int num;   // The for loop control variable


  cout << "The first 20 odd numbers:" << endl;

  for (num = 1; num < 40; num += 2)

    { cout << num << ' '; }


  cout << endl << endl << "The first 20 even numbers:" << endl;

  for (num = 2; num <= 40; num += 2)

    { cout << num << ' '; }


  cout << endl << endl << "The first 20 odd numbers in reverse:" << endl;

  for (num = 39; num >= 1; num -= 2)

    { cout << num << ' '; }


  cout << endl << endl << "The first 20 even numbers in reverse:" << endl;

  for (num = 40; num >= 2; num -= 2)

    { cout << num << ' '; }


  return;

}

======================

// SHOWHEX.CPP

// A program to show how pointers can be cast

// and what storage looks like for different types


#include <iostream.h>  


void ShowHex(const unsigned char *p, int length);


void main()

  { 

    // Initialize arrays - use hex for the first four

    // so can match the output to what we initialize

    // Check the result of decimal 1000 for the output

    int   i[5] = {0x1,0x22,0x333,0x4444,1000};

    long  l[5] = {0x1,0x22,0x333,0x4444,1000};

    char  c[5] = {'1','2','3','4','5'};

    cout << endl << "Array of ints";

    ShowHex((unsigned char*)i,sizeof(i));

    cout << endl << "Array of longs";

    ShowHex((unsigned char*)l,sizeof(l));

    cout << endl << "Array of chars";

    ShowHex((unsigned char*)c,sizeof(c));

        

  } 

  

void ShowHex(const unsigned char * p,int length)

  {

    for (int i = 0; i < length; i++)

      {

        // Skip every 4 characters shown

        if (!(i % 4))

          cout << endl;                 

        // Don't worry about the following:

        // Change the output format to show switch

        // between decimal and hexadecimal - hex

        // numbers are traditionally shown with

        // leading zeros

        cout << "[" ;

        cout.width(2); 

        cout.unsetf(ios::hex);

        cout.fill(' '); 

        cout << i << "] ";

        cout.width(2);

        cout.setf(ios::hex);

        cout.fill('0'); 

        // any pointer can use array notation

        // cast to an unsigned int so the output

        // can format the number

        cout << (unsigned int)p[i] << ' ';

      }

   }

==============================

 // Filename: SIZEOF.CPP

 // The sizeof operator always returns the amount of memory

 // (the number of bytes) that it takes to store a value

 #include <iostream.h>

 void main()

 {

   char c = 'x';

   char name[] = "Italy";

   int i = 29;

   float f = 6.7643;

   double d = 9493945.6656543;

 

   // Print the sizes of the data

   // Typecast sizeof to an integer because sizeof returns its

   // value as a long integer and this program prints with %d only

   cout << "The sizes of variables:" << endl;

   cout << "The size of c is " << int(sizeof(c)) << endl;

   cout << "The size of name is " << int(sizeof(name)) << endl;

   cout << "(See, that was not the length of the string!)" << endl;

   cout << "The size of i is " << int(sizeof(i)) << endl;

   cout << "The size of f is " << int(sizeof(f)) << endl;

   cout << "The size of d is " << int(sizeof(d)) << endl;

   cout << endl << "The sizes of literals:" << endl;

   cout << "The size of 4.3445 is " << int(sizeof(4.3445))

        << endl;

   cout << "The size of Hello is " << int(sizeof("Hello"))

        << endl;

   cout << "The sizes of data types:" << endl;

   cout << "The size of a long double is "

        << int(sizeof(long double)) << endl;

   cout << "The size of a float is " << int(sizeof(float));

   return;

 }

=====================

// Filename: SKATERS.CPP

// Tracks an array of eight Olympic

// skaters and prints their statistics

#include <iostream.h>


struct skaterStr {

  char name[25];

  float score;

};


void main()

{

  int ctr;   // for-loop variables

  int highSub, lowSub;   // Keep high and low score subscripts

  double avg = 0.0;

  float high, low;


  // Define and initialize the structure variables

  struct skaterStr skaters[8] = {

             {"Laura Marina", 7.6}, {"Ellen Horne", 8.5},

             {"P. O. Napon", 6.4}, {"Lia Thorton", 5.8},

             {"Jessica Reynolds", 9.4}, {"Susan Lynde", 8.0},

             {"Tina Freyer", 8.1}, {"Nancy Ogden", 4.6}};


  // Compute the average

  for (ctr = 0; ctr < 8; ctr++)

    { avg += skaters[ctr].score; }   // Use avg to total now

  avg /= 8.0;   // Compute the average score

  cout.precision(1);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  cout << "The average score is " << avg << endl << endl;


  // Find the highest and lowest score.

  // First, store the first score in both

  // low and high variables and then compare

  // against the other seven values.

  high = low = skaters[0].score;

  for (ctr = 1; ctr < 8; ctr++)

    { if (skaters[ctr].score > high)

        { high = skaters[ctr].score;

          highSub = ctr; }

      if (skaters[ctr].score < low)

        { low = skaters[ctr].score;

          lowSub = ctr; }

    }

  cout << "High skater: " << skaters[highSub].name

       << ", with a " << skaters[highSub].score << endl;

  cout << "Low skater: " << skaters[lowSub].name

       << ", with a " << skaters[lowSub].score << " score" << endl;

  return;

}

===========================

// Filename: SONGS.CPP

// Writes song data to a disk file

#include <fstream.h>


void main()

{

  ofstream fp;

  fp.open("C:\\SONGS.DAT", ios::out);   // Creates a new file


  fp << "My Love, My Baby, My Cat" << endl;

  fp << "S. T. Larkey" << endl;

  fp << "1994" << endl;

  fp.close();   // Releases the file

  return;

}




=============================

// Filename: STARS.CPP

// Print a line of stars

#include <iostream.h>


int getNum(void);

void asterisk(int num);


void main()

{

  int num;


  num = getNum();

  asterisk(num);   // Print the stars


  return;

}

//*********************************************************

int getNum(void)

{

  int num;

  do

  {  cout << "Enter a number from 1 to 80: ";

     cin >> num;

  } while ((num < 1) || (num > 80));

  return num;

}

//*********************************************************

void asterisk(int num)

{

  int c;

  for (c=0; c<num; c++)

    { cout << '*'; }

  cout << endl;

  return;

}

=============================

// Filename: STLITPR.CPP

 // Printing string literals is easy

 #include <iostream.h>


 void main()

 {

    cout << "This is a string literal.";

    return;

 }

============================

// Filename: STR.CPP

 // Stores and initializes four character

 // arrays for three friends first names


 #include <iostream.h>

 #include <string.h>

 void main()

 {

   // Declares all arrays and initializes the first one

   char friend1[20]="Lucy";

   char friend2[20];

   char friend3[20];

   char friend4[20];


   // Uses a function to initialize the second array

   strcpy(friend2, "James");


   friend3[0] = 'T';   // Initializes the third array

   friend3[1] = 'o';   // an element at a time

   friend3[2] = 'n';

   friend3[3] = 'y';

   friend3[4]= '\0';   // Without this, friend3 wouldn't

                       // hold a string


   // Get a name from the user

   cout << "What is one of your friend's first name? ";

   cin >> friend4;


   // Prints the names

   cout << friend1  << endl;

   cout << friend2  << endl;

   cout << friend3  << endl;

   cout << friend4  << endl;

   return;

 }

==========================

// Filename: STRLEN.CPP

// Prints the length of the user's entered string

#include <iostream.h>

void main()

{

  char inArray[80];

  int length = 0;


  cout << "What is your first name? ";

  cin >> inArray;


  while (inArray[length] != '\0')

    {

      length++;   // Add 1 to length if not null zero

    }

  // TIP: This is the same as the previous while:

  //      while (inArray[length++])


  cout << "Your name contains " << length << " letters." << endl;

  return;

}

=================================

// Filename: STRPGM.CPP

// Program that uses string functions to

// work with string input

#include <iostream.h>

#include <string.h>

#include <stdlib.h>


void main()

{

  char name[31];

  char age[4];     // Will hold a string of integer digits

  int intAge;


  cout << "What is your name? ";

  cin.getline(name, 30);

  cout << "How old are you? ";

  cin.getline(age, 3);


  // Make into one string if room for comma, space, and null

  if ((strlen(name) + strlen(age) + 3) <= 30)

    {  

       strcat(name, ", ");

       strcat(name, age);

       cout << "Your name and age: " << name << endl; 

    }

  else

    { // Here if name cannot hold entire string

      cout << endl << "Thanks, " << name << endl; 

    }


  // Convert the age string to an integer

  intAge = atoi(age);  // Convert the age to an integer

  intAge += 10;

  cout << "In ten years, you'll be " << intAge << endl;

  return;

}

=============================

// Filename: STRSORT.CPP

// Asks the user for eight song titles and stores

// each title on the heap as the user enters the

// song. When all eight have been entered, sorts

// the songs and prints them in alphabetical order.


const int NUM = 8;


#include <iostream.h>

#include <string.h>


void getSongs(char * songs[NUM]);

void sortSongs(char * songs[NUM]);

void prSongs(char * songs[NUM]);

void frSongs(char * songs[NUM]);


void main()

{

  char * songs[NUM];   // To point to the songs


  cout << "Song Sorter" << endl << endl << endl;

  getSongs(songs);

  sortSongs(songs);

  prSongs(songs);

  frSongs(songs);   // Delete the allocated heap


  return;

}

//**********************************************************

void getSongs(char * songs[NUM])

{

  int ctr;   // for-loop control variable

  char inBuffer[80];   // To hold an entered string


  for (ctr = 0; ctr < NUM; ctr++)

    { cout << "Please enter a song title: ";

      cin.get(inBuffer, 80);

      cin.ignore();  // Eliminate any newlines left in buffer

      // Allocate enough heap to hold that song

      // and leave enough room for the null zero

      songs[ctr] = new char [strlen(inBuffer)+1];

      // Now that room is reserved, copy the string

      strcpy(songs[ctr], inBuffer);

    }

  return;

}

//**********************************************************

void sortSongs(char * songs[NUM])

{

  int inner, outer;   // for-loop control variables

  char * temp;        // Temporary value for swapping

  int didSwap;        // 1 if a swap took place in each pass

  for (outer = 0; outer < (NUM - 1); outer++)

    {

      didSwap = 0;   // Initialize after each pass

      // Next loop steps through each pair of values

      for (inner = outer; inner < NUM; inner++)

        {

          // Use strcmp() to see if first string is higher

          if (strcmp(songs[outer], songs[inner]) > 0)

            { temp = songs[outer];   // Swap pointers

              songs[outer] = songs[inner];

              songs[inner] = temp;

              didSwap = 1;   // Indicate that a swap occurred

            }

        }

      if (!didSwap)   // If no swap happened,

        { break; }    // terminate the sort

    }

  return;

}

//**********************************************************

void prSongs(char * songs[NUM])

{

  int ctr;   // for-loop counter

  cout << endl << endl << "Here are the songs alphabetized:" << endl;

  for (ctr = 0; ctr < NUM; ctr++)

    {  cout << songs[ctr] << endl; }

  return;

}

//**********************************************************

void frSongs(char * songs[NUM])

{

  int ctr;   // for-loop counter

  for (ctr = 0; ctr < NUM; ctr++)

    {  delete songs[ctr]; }

  return;

}

=====================

// Filename: STRUSORT.CPP

// Defines and initializes an array of five structure

// variables. The price member is then used as a

// comparison for the descending sort that follows.

#include <iostream.h>


const int NUM = 5;


struct inv {

  char partID[6];

  int quantity;

  float price;

};


void invSort(struct inv items[NUM]);

void invPrint(struct inv items[NUM]);



void main()

{

  struct inv items[NUM] = {{"HDWR9", 13, 4.53},

                           {"WDGT4", 2, 15.82},

                           {"POPL0", 4, 8.32},

                           {"RTYN6", 7, 5.40},

                           {"LOUN4", 61, 7.43}};


  cout << "Inventory Listing from High Price to Low Price" << endl << endl;

  invSort(items);

  invPrint(items);


  return;

}

//**********************************************************

void invSort(struct inv items[NUM])

{

  int inner, outer;   // for-loop control variables

  struct inv temp;    // Temporary value for swapping

  int didSwap;        // 1 if a swap took place in each pass

  for (outer = 0; outer < (NUM - 1); outer++)

    {

      didSwap = 0;   // Initialize after each pass

      // Next loop steps through each pair of values

      for (inner = outer; inner < NUM; inner++)

        {

          if (items[outer].price < items[inner].price)

            { temp = items[outer];   // Swap

              items[outer] = items[inner];

              items[inner] = temp;

              didSwap = 1;   // Indicate that a swap occurred

            }

        }

      if (!didSwap)  // If no swap happened,

        { break; }   // terminate the sort

    }

  return;

}

//**********************************************************

void invPrint(struct inv items[NUM])

{

  int ctr = 0;   // for-loop control variable

  cout.precision(2);

  cout.setf(ios::showpoint);

  cout.setf(ios::fixed);

  for (ctr = 0; ctr < NUM; ctr++)

    { cout << "Part ID: " << items[ctr].partID << ", Quantity: ";

      cout.width(2);

      cout << items[ctr].quantity << ", Price: $";

      cout.width(6);

      cout << items[ctr].price << endl;

    }

  return;

}

=========================================

// Filename: SWITCHTV.CPP

// This program uses a switch statement to print a message

// to the user. The printed message corresponds to the

// user's favorite television channel.

#include <iostream.h>


void main()

{

  int channel;


  cout << "In this town, there are five non-cable television ";

  cout << "channels." << endl;

  cout << "What is your favorite (2, 4, 6, 8, or 11)? ";

  cin >> channel;

  cout << endl << endl;   // Output two blank lines


  // Use a switch to print appropriate messages

  switch (channel)

    { 

      case (2) : 

        { 

          cout << "Channel 2 got top ratings last week!";

          break; 

        }

      case (4) : 

        { 

          cout << "Channel 4 shows the most news!";

          break; 

        }

      case (6) : 

        { 

          cout << "Channel 6 shows old movies!";

          break;

        }

      case (8) : 

        { 

          cout << "Channel 8 covers many local events!";

          break; 

        }

      case (11):

        { 

          cout << "Channel 11 is public broadcasting!";

          break; 

        }

      default  :  // Logic gets here only if

                  // user entered an incorrect channel

        { 

          cout << "Channel " << channel

               << " does not exist, it must be cable."; 

        }

    }


  cout << endl << "Happy watching!";

  return;

}


Tidak ada komentar: