CS108 – C
Introduction to Programming
Instructor: Rosemary Mullick, Ph.D.
Menu:
- Hello World
- Temperature Conversion
- Rounding Numbers
- Gas Cylinder Codes
- Daily High Temperature
- Correct Change
- Summation
- Hangman
- Nouns
- Recursion
- Automobile Information
- Link List
Hello World:
/* Hello World Program
By: Ronny L. Bull
CS108 */
# include <stdio.h>
int main(void)
{
printf("Hello World\n");
return 0;
}
Temperature Conversion:
/* Ronny L. Bull
CS108-04,11
GPH#2 - Temperature Conversion Program
09-05-2009
Purpose: This program converts the inputed temperature
in farenheit to its celsius equivalent */
#include <stdio.h>
int
main(void)
{
int farenheit; // temp in farenheit
double celsius; // temp in celsius
// Input the temp in farenheit
printf("Please enter the current temperature in farenheit:\n ");
scanf("%d", &farenheit);
// Calculate the temperature in celsius
celsius = 0.555555556 * (farenheit-32);
// Display the temperature in celsius
printf("That equals %.2f degrees celsius.\n", celsius);
return (0);
}
Rounding Numbers:
/* By: Ronny L. Bull
CS108-04,11
GPH#3 - Round a positive number to two decimal places
09-18-2009
Purpose: This program takes a positive number with a fraction part
and rounds it to two decimal places. */
#include <stdio.h>
#include <math.h>
double scale(double x, int n); // Function Prototype
int main(void)
{
double x; // Set x as a double
double pass1; // Set pass1 as a double
double pass2; // Set pass2 as a double
int rounded_x; // Set rounded_x as an integer
int scale1; // Set scale1 as an integer
int scale2; // Set scale2 as an integer
scale1 = 2; // Assign the value 2 to scale1
scale2 = -2; // Assign the value -2 to scale2
// Ask user for a positive number with more than two decimal places.
printf("Please enter a positive number with more than two decimal places\n");
// Store the number in x
scanf("%lf", &x);
// Use function scale to raise x to the power of 2.
pass1 = scale(x,scale1);
// For debugging
//printf("pass1 is: %f\n", pass1);
// Give pass1 a value omitted (citation: handout)
rounded_x = (int)(pass1 + 0.5);
//For debugging
//printf("rounded_x is: %d\n", rounded_x);
// Use function scale to raise x to the power of -2.
pass2 = scale(rounded_x, scale2);
// Print the output to the screen
printf("Your number rounded to 2 decimal places is: %6.2f\n", pass2);
return 0;
}
// Scale Function
double
scale(double x, int n)
{
double scale_factor;
scale_factor = pow(10,n);
return (x * scale_factor);
}
Gas Cylinder Codes:
/* By: Ronny L. Bull
CS108-04,11
GPH#4 - Report the contents of gas-cylinder based on first letter of color
09-24-2009
Purpose: This program reports the contents of a gas-cylinder based
on the input of the first letter of the cylinder's color. */
#include <stdio.h>
int main(void)
{
char x; // Set x as a character
//Print the prompt and store the input in x
printf("Enter the first letter of the gas cylinder's color:");
scanf("%c", &x);
//Case set to print the cylinder contents
//to the screen based on the value of the input
switch (x)
{
case 'o': case 'O': printf("That cylinder contains ammonia\n");
break;
case 'b': case 'B': printf("That cylinder contains carbon monoxide\n");
break;
case 'y': case 'Y': printf("That cylinder contains hydrogen\n");
break;
case 'g': case 'G': printf("That cylinder contains oxygen\n");
break;
default: printf("Contents unknown\n");
}
return 0;
}
Daily High Temperature:
/* By: Ronny L. Bull
CS108-04,11
GPH#5 - Daily High Temperature Collection
10-2-2009
Purpose: This program processes a collection of daily
high temperatures and dislays a category of each temperature. */
/* Dictionary of Variables:
cnt - integer, temp input counter
hot - integer, hot temp counter
cold - integer, cold temp counter
warm - integer, pleasent temp counter
sum - double, sum of temp inputs
temp - double, temp inputed by user
sent - double, sentinal value
avg - double, average of temp inputs */
#include <stdio.h>
int main(void)
{
// Variables
int cnt = 0;
int hot = 0;
int cold = 0;
int warm = 0;
double sum = 0;
double temp;
double sent;
double avg;
sent = -999;
//Print the prompt to request temperature input
printf("Please type in the daily high temperature or -999 to quit:\n");
scanf ("%lf", &temp);
// Create a loop to request temperature input until the sential value is read
// Code Citation: Dr. R.J. Mullick - SENWHILE.C
while(temp != sent)
{
cnt ++;
sum = sum + temp;
printf("Please type in the daily high temperature or -999 to quit:\n");
scanf("%lf", &temp);
// Count the number of hot, cold, and pleasent days
if(temp >= 85)
{
hot ++;
}
else if(temp <= 59)
{
cold ++;
}
else
{
warm ++;
}
}
// Calculate the average temperature
avg = sum / cnt;
// Print the Output
printf("\n\n");
printf("There were %d temperatures recorded\n", cnt);
printf("The sum of your temperatures is: %3.2f\n", sum);
printf("The average temperature was: %3.2f\n", avg);
printf("There were %d hot days\n", hot);
printf("There were %d cold days\n", cold);
printf("There were %d pleasant days\n", warm);
return 0;
}
Correct Change:
/* By: Ronny L. Bull
CS108-04,11
GPH#6 - Counting Change
10-9-2009
Purpose: This program dispenses change by determining how many
dollars, quarters, dimes, nickles and pennies should be given back. */
/* Dictionary of Variables:
total - double, the grand total of the sale
tendered - double, the amount of cash tendered
change - double, the change due
dollar - integer, the number of dollar bills
quarter - integer, the number of quarters
dime - integer, the number of dimes
nickel - integer, the number of nickels
penny - double, the number of pennies
g - double, change after dollars
q - double, change after quarters
d - double, change after dimes
n - double, change after nickels
*/
#include <stdio.h>
//Function Prototype
void exact_change(double);
int main(void)
{
//Variables
double total;
double tendered;
double change;
//Prompt for total
printf("Please enter the total amount due:\n" );
scanf("%lf", &total);
//Print the total to the screen
printf("The total amount due is: $%4.2f\n\n", total);
//Prompt for cash tendered
printf("Please enter the amount tendered:\n" );
scanf("%lf", &tendered);
//Print the amount of cash tendered to the screen
printf("You recieved: $%4.2lf\n\n", tendered);
//Calculate the change due
change = tendered - total;
printf("The amount of change due is: $%4.2f\n\n", change);
//Call to function that returns change type
exact_change(change);
return (0);
}
//Calculates each type of change to return
void exact_change(double change)
{
//Variables
int dollar;
int quarter;
int dime;
int nickel;
double penny;
double g;
double q;
double d;
double n;
//Calculate dollars to return
dollar = change/1;
//Calculate change value after dollars
g = change - dollar;
//Debug
//printf("g is %4.2f\n", g);
//Calculate quarters to return
quarter = g/.25;
//Calculate change value after quarters
q = g - (quarter * .25);
//Debug
//printf("q is %4.2f\n", q);
//Calculate dimes to return
dime = q/.10;
//Calculate change value after dimes
d = q - (dime * .10);
//Debug
//printf("d is %4.2f\n", d);
//Calculate nickels to return
nickel = d/.05;
//Calculate change value after nickels
n = d - (nickel * .05);
//Debug
//printf("n is %4.2f\n", n);
//Calculate pennies to return
penny = n/.01;
//Debug
//printf("penny is %4.2f\n", penny);
//Print the change to return to the screen
printf("Give back: %d Dollars, %d Quarters, %d Dimes, %d Nickels, and %1.0f Pennies.\n", dollar,quarter,dime,nickel,penny);
}
Summation:
/* By: Ronny L. Bull
CS108-04,11
GHP#7 - Sumation
10-18-2009
Purpose: This program computes the sum of the given equation.
*/
/* Dictionary of Variables:
sf - float, sum of the equation (Float)
xf - float, the product that is being looped (Float)
i - int, counter (Float)
ferror - float, amount of error (Float)
sd - double, sum of equation (Double)
xd - double, the product that is being looped (Double)
j - int, counter (Double)
derror - double, amount of error (Double)
*/
#include <stdio.h>
//Function Prototype
float float_sum(void);
double double_sum(void);
int main(void)
{
//Print the output of the float function
printf("The value of the equation using a float for x is:\n");
//Call to function that returns a float
float_sum();
//Print the output of the double function
printf("The value of the equation using a double for x is:\n");
//Call to function that returns a double
double_sum();
return(0);
}
//Perform the equation using a float for x
float float_sum(void)
{
//Variables
float sf;
float xf = 0.1;
int i;
float ferror;
printf ("x is: %2.1f\n", xf);
//Calculate the sum
for (i = 1; i < 1000; i++)
{
sf = xf + sf;
}
printf("The sum is: %f\n", sf);
//Calculate the amount of error
ferror = 100.0 - sf;
printf("The amount of error is: %f\n\n", ferror);
}
//Perform the equation using a double for x
double double_sum(void)
{
//Variables
double sd;
double xd = 0.1;
int j;
double derror;
printf("x is: %2.1f\n", xd);
//Calculate the sum
for (j = 1; j < 1000; j++)
{
sd = xd + sd;
}
printf("The sum is: %f\n", sd);
//Calculate the amount of error
derror = 100.0 - sd;
printf("The amount of error is: %f\n\n", derror);
}
Hangman:
/* By: Ronny L. Bull
CS108-04,11
GHP#8 - Hangman
10-20-2009
Purpose: This program is an interactive game of hangman
*/
/* Dictionary of Variables:
word - char, array of characters in the word to be guessed
guessed - char, array of characters attempted by the user
start - char, stores user input for game start question
i - int, loop counter
t - int, attempt counter
guess - char, users guess
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Function Prototype
void start_game(char);
void guess_word(void);
int main(void)
{
//Variables
char start;
//Prompt the user to start the game
printf("Welcome to hangman! Are you ready to play? (y/n)\n");
scanf("%c", &start);
//Call to function start_game
start_game(start);
return(0);
}
//Functions
//start_game function
void start_game(char start)
{
//Check to see if user is ready
if(start == 'y' || start == 'Y')
{
//Call to function guess_word
printf("Start Guessing!\n");
printf("Hint ****\n");
guess_word();
}
else
{
printf("Game Over!\n\n");
exit(EXIT_SUCCESS);
}
}
//guessing function
void guess_word(void)
{
//Variables
char word[] = {'d', 'r', 'o', 'p', '\0'};
char guessed[] = {'*', '*', '*', '*', '\0'};
char guess;
int t = 6;
int i;
//Process users guess and add correct entries to the guessed array
for(i = 1; i <= 6; i++)
{
//Debug
//printf("%s\n", word);
//printf("%s\n", guessed);
//Start Game
printf("Please guess a letter\n");
scanf(" %c", &guess);
switch (guess)
{
case 'd': guessed[0] = guess;
break;
case 'r': guessed[1] = guess;
break;
case 'o': guessed[2] = guess;
break;
case 'p': guessed[3] = guess;
break;
default: printf("Sorry that is incorrect\n");
}
//Take away from tries count
t--;
//Print the guessed word up to the current point, unguessed letters remain as *'s
printf("Hint: %c%c%c%c\n", guessed[0], guessed[1], guessed[2], guessed[3]);
//Print the amount of attemps the user has left
if(t == 0)
{
printf("You are out of attempts, you loose!\n");
}
//Compare arrays using strcmp function
//If they are equal the function returns a 0
//Print You Win and exit the program
else if( strcmp ( word, guessed ) == 0 )
{
printf("You Win!\n");
printf("Game Over!\n");
exit(EXIT_SUCCESS);
}
else
{
printf("You have %d attempts left.\n", t);
}
}
}
Nouns:
/* By: Ronny L. Bull
CS108-04,11
GHP#9 - Nouns
10-31-2009
Purpose: This program takes a noun as an input and forms the plural version.
If the noun ends in "y", it removes the "y" and adds "ies".
If the noun ends in "s", "c", "ch" or "sh", it adds "es".
In all other cases it adds an "s".
*/
/* Dictionary of Variables:
n = integer - number of nouns the user entered
i,j = integer - counter variables
c = integer - variable to hold data from getchar() function
nouns = character - 2d array to hold the list of nouns the user entered
orig = character - 2d array to hold an original copy of the nouns
*ies = character - pointer array that holds the string "ies"
*es = character - pointer array that holds the string "es"
*s = character - pointer array that holds the string "s"
z = integer - string length of the array passed to the process function
*a = character - pointer array to hold a strncpy of the original string
*/
#include <stdio.h>
#include <string.h>
//Setup max sizes for rows and columns
#define MAX_COLS 20
#define MAX_ROWS 20
//Function Prototypes
void process (char *);
//Main
int main(void)
{
//Variables
int n;
int i,j;
int c;
char nouns[MAX_ROWS][MAX_COLS];
char orig[MAX_ROWS][MAX_COLS];
i=0;
j=0;
//Prompt the user to input a quantity of nouns to process
printf("Please enter the number of nouns you would like to process\n");
printf("You may process up to 20 nouns ");
scanf("%d", &n);
//Prompt the user to enter the nouns in singular form
printf("\nPlease enter the %d nouns in their singular form.\n", n);
//Process the list into a 2d array (code modified from: twodarraynames.c by R. Mullick)
c = getchar(); // to throw away the new line from the scanf statement
while (i < n)
{
c = getchar();
while (c != '\n')
{
nouns[i][j++] = c;
c = getchar();
}
nouns[i][j] = '\0';
//make a copy of the noun in the orig 2d array
strcpy(orig[i],nouns[i]);
//Call to function process
process (nouns[i]);
i++;
j=0;
}
//Print the nouns and plurals to the screen
printf("\n\nThe %d nouns that you entered were : \n", n);
for (i=0;i<n;i++)
{
printf("%s %s\n", orig[i],nouns[i]);
}
return (0);
}
//Functions
//Process - Processes the nouns into their plural form
void process (char *narray)
{
//Variables
char *ies = "ies";
char *es = "es";
char *s = "s";
char a[MAX_COLS] = "";
int z = strlen(narray);
//Check to see what the last character of the noun is
//and either replace or append the proper string
//on to the end to make the noun plural
if (narray[z-1] == 'y')
{
strncpy(a,narray,z-1);
strcat(a,ies);
strcpy(narray,a);
}
else if (narray[z-1] == 's' || narray[z-1] == 'c' || narray[z-1] == 'h')
{
strcat(narray,es);
}
else
{
strcat(narray,s);
}
}
Recursion:
/* By: Ronny L. Bull
CS108-04,11
GHP#10 - Recursive
11-15-2009
Purpose: This program performs a recursive function
*/
/* Dictionary of Variables:
value - integer, value returned by the function f
x - integer, number inputed by user
ans - integer, answer returned by function f
*/
#include <stdio.h>
//Function Prototype
int f(int);
int value;
//Main
int main(void)
{
//Variables
int x;
//Prompt the user to enter a number
printf("Please enter a number\n");
scanf("%d", &x);
//Call to recursive function f
value = f(x);
//Print the value to the screen
printf("The value is: %d\n", value);
return (0);
}
//Function
//f - Recursive function
int f(int x)
{
//Variables
int ans;
//printf("X: %d\n", x);
if (x <= 0)
ans = 0;
else
ans = f(x-1) + 2;
//printf("ans: %d\n", ans);
return ans;
}
Automobile Information:
/* By: Ronny L. Bull
CS108-04,11
GHP#11 - auto.c
11-19-2009
Purpose: This program collects information on automobiles.
The program collects and reports the following for each auto entered:
Make
Model
Miles
Manufacture Date
Purchase Date
Gas Tank Capacity (Gallons)
Current Fuel Level (Gallons)
*/
/* Dictionary of Variables:
auto_t - typedef struct - contains char variables make and model as well as int variable miles.
Holds information about the make, model and miles of an automobile.
date_t - typedef struct - contains int variables manuf[m,d,y] and purch[m,d,y]. Stores information about the
manufacture and purchase dates of an automobile.
tank_t - typedef struct - contains double variables cap and cur. Stores information abou the
gas tank capacity as well as the current fuel level in gallons.
num - integer used to store the amount of autos a user wants to input
i,j,k - integers used as a counters
m - integer used to store miles
dm,mm,ym - integers used to store manufacture date
dp,mp,yp - integer used to store purchase date
cap - double used to store tank capacity in gallons
cur - double used to store current tank level in gallons
eof - char array holding the characers 'E','O','F'
cont - char array to hold the continue string to check against eof
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 20
//User Defined Structs
typedef struct
{
char make[MAX];
char model[MAX];
int miles;
} auto_t;
typedef struct
{
int manufm;
int manufd;
int manufy;
int purchm;
int purchd;
int purchy;
} date_t;
typedef struct
{
double cap;
double cur;
} tank_t;
//Variables
auto_t car[MAX];
date_t dates[MAX];
tank_t gas[MAX];
//Function Prototypes
void scan_auto(auto_t [], int);
void scan_date(date_t [], int);
void scan_tank(tank_t [], int);
void print_auto(auto_t [], int);
void print_date(date_t [], int);
void print_tank(tank_t [], int);
void driver(int);
//Main
int main(void)
{
//Variables
int num;
int i;
char eof[] = {'E','O','F','\0'};
char cont[4];
//Prompt user for auto info
printf("You may input up to 20 automobiles into this program.\n\n");
printf("**If you wish to use an input file make sure each data set starts\n");
printf("with a c and the end of the file is notated with an EOF\n");
printf("each part of the data set must be on it's own line**\n");
for(i=0;i<MAX;i++)
{
printf("\nPress c and enter to continue or type EOF to quit.\n\n");
scanf("%s", cont);
if(strcmp(cont,eof) != 0)
{
printf("\nPlease enter the information for automobile %d\n\n", i+1);
driver(i);
}
else
{
i=MAX;
}
}
return(0);
}
//Functions
//Driver Function - Scans and displays information for each vehical
void driver(int j)
{
//Get make, model, and miles from function scan_auto
scan_auto(car, j);
//Get the manufacture and purchase dates from function scan_dates
scan_date(dates, j);
//Get tank capacity, and current fuel level from function scan_tank
scan_tank(gas, j);
//Print the information to the screen from print functions
printf("\n\n***********Auto %d Info**********\n", j+1);
print_auto(car, j);
print_date(dates, j);
print_tank(gas, j);
printf("\n************End Auto %d***********\n", j+1);
}
//Scan Auto Function
void scan_auto(auto_t car[MAX], int k)
{
//Variables
int m;
//Prompt user for make, model, and odometer reading
printf("\nEnter the make of the vehicle up to 20 characters long: ");
scanf("%s", (car[k]).make);
printf("\nEnter the model of the vehicle up to 20 characters long: ");
scanf("%s", (car[k]).model);
printf("\nEnter the current odometer reading: ");
scanf("%d", &m);
(car[k]).miles = m;
}
//Print Auto Function
void print_auto(auto_t car[MAX], int k)
{
//Print the make and model
printf("\nMake: %s\n",(car[k]).make);
printf("Model: %s\n", (car[k]).model);
printf("Miles: %d\n", (car[k]).miles);
}
//Scan Date Function
void scan_date(date_t dates[MAX], int k)
{
//Variables
int mm;
int dm;
int ym;
int mp;
int dp;
int yp;
//Prompt user for manufacture and purchase dates
printf("\nEnter the purchase date: \n");
printf("\nMonth: ");
scanf("%d", &mp);
(dates[k]).purchm = mp;
printf("\nDay: ");
scanf("%d", &dp);
(dates[k]).purchd = dp;
printf("\nYear: ");
scanf("%d", &yp);
(dates[k]).purchy = yp;
printf("\nEnter the manufacture date: \n");
printf("\nMonth: ");
scanf("%d", &mm);
(dates[k]).manufm = mm;
printf("\nDay: ");
scanf("%d", &dm);
(dates[k]).manufd = dm;
printf("\nYear: ");
scanf("%d", &ym);
(dates[k]).manufy = ym;
}
//Print Date Function
void print_date(date_t dates[MAX], int k)
{
//Print the manufacture and purchase dates
printf("Purchased: %d %d %d\n", (dates[k]).purchm, (dates[k]).purchd, (dates[k]).purchy);
printf("Manufactured: %d %d %d\n", (dates[k]).manufm, (dates[k]).manufd, (dates[k]).manufy);
}
//Scan Tank Function
void scan_tank(tank_t gas[MAX], int k)
{
//Variables
double cap;
double cur;
//Get tank capacity and current fuel level
printf("\nEnter the capacity of the gas tank in gallons: ");
scanf("%lf", &cap);
(gas[k]).cap = cap;
printf("\nEnter the current fuel level in gallons: ");
scanf("%lf", &cur);
(gas[k]).cur = cur;
}
//Print Tank Function
void print_tank(tank_t gas[MAX], int k)
{
//Print tank capacity and current fuel level in gallons
printf("Fuel Capacity: %3.2f gals\n", (gas[k]).cap);
printf("Current Fuel: %3.2f gals\n", (gas[k]).cur);
}
Link List:
/* By: Ronny L. Bull
CS108-04,11
GHP#12 - linklist.c
12-4-2009
Purpose: This program creates a linked list of 10 characters then
creates a copy of the list in reverse order.
*/
/* Dictionary of Variables:
Characters - typedef struct that holds the linked list of characters
data - character in Characters struct to hold the character entered by a user
printNodes - Function that prints the characters to the screen from the linked list and reverse array
i - integer - counter
letter - character - holds character inputed by user
c - character - used for getchar();
reverse - character array that holds the linked list in reverse order
*/
//Reference: Code Modified from makelistprog.c by Dr. R. Mullick
#include <stdio.h>
#include <stdlib.h>
//User Defined Structs
typedef struct Characters {
char data;
struct Characters *next;
} NODE;
typedef NODE *NPTR;
//Function Prototypes
void printNodes(NPTR);
//Global Variables
char reverse[10];
//Main
int main(void)
{
//Variables
NPTR p,newp;
int i;
char letter;
char c;
NPTR head = NULL;
//Print program info to user
printf("This program creates a linked list with 10 nodes\n");
printf("each node contains a character and a link to the next node\n");
//Collect the data
for (i = 0; i < 10; i++)
{
//Prompt user for a character
printf("\n enter a character for node %d: ", i);
scanf("%c", &letter);
//Flush the new line from scanf
c = getchar();
//Store a copy in reverse array starting from the end
reverse[9-i] = letter;
//Debugging
//printf("reverse %d is: %d", 10-i,reverse[10-i]);
//Put character into the linked list
newp = (NODE *)malloc(sizeof (NODE));
newp->data = letter;
if(head == NULL)
{
head = newp;
newp->next = NULL;
}
else
{
p = head;
while(p->next != NULL)
{
p = p->next;
}
p->next = newp;
newp->next = NULL;
}
}
//Call to function printNodes
printNodes(head);
//Print complete
printf("Complete\n");
return (0);
}
//Functions
//Function printNodes - prints the linked list
//in forward and reverse directions
void printNodes(NPTR p)
{
//variables
int i;
//Print the list in forward direction
printf("Printing list in forward direction:\n");
while(p != NULL)
{
printf("%c\n", p->data);
p = p->next;
}
printf("\n");
//Print the list in reverse direction
printf("Printing list in reverse direction:\n");
for(i=0;i<10;i++)
{
printf("%c\n", reverse[i]);
}
}
