Class Activities CS1440

Spring Break Programming Projects Programming Projects - Paper-based

Mon Feb. 23, 27
In our last class we wrote a program that displayed fraction(s).  The first program read 2 pairs of numbers and used a function to display them as a fraction.

The first version fract.C was the one that asked users for 2 pairs.  It was limited to 2 pairs of functions only.
//fract.C – reads 4 values and will display them as 2 fractions
#include <iostream>

using namespace std;

void display_fraction(int num, int den);

int main()
{
int a, b, c, d;

cout << "Enter a, b, c, d \n";
cin >> a >> b >> c >> d;
cout << endl;

display_fraction(a, b);
display_fraction(c, d);

return 0;
}
void display_fraction(int num, int den)
{
cout << num << "/" << den << endl;
return;
}

We wanted to improve this code so it can read more than just two fractions. One way to improve it was to ask users to input the number of fractions they want to enter right up front, and then read as many values (pairs of values) as needed to make the fractions.  We called this program fract_loop .C.  Note how we used a counting loop to do this. There is also another way to do this program using Yes and No option.  In that case we ask users whether they have another fraction to enter.

In a much different way, we let the reading continues until there is no more value left or entered.  The end of such process is marked by EOF (End of File).  That is Ctrl-D at the keyboard.  If you use an input file that is marked at the end of your file automatically.  Please see the program on the last page, fract_loop_inp.C.

// fract_loop.C – reads as many as number of fractions and will display
#include <iostream>

using namespace std;

void display_fraction(int num, int den);

int main()
{
int numerator, denominator;
int number;

cout << "How many fraction";
cin >> number;

while(number > 0)
{
cout << "Enter numerator and denominator\n";
cin >> numerator >> denominator;
cout << endl;

display_fraction(numerator, denominator);

number--;
}

return 0;
}

void display_fraction(int num, int den)
{
cout << num << "/" << den << endl;
return;
}

This program reads from the keyboard pairs of values until Ctrl-D is pressed. Or will read values from an input file when it is run (a.out < input) until the end of the file is reached.

//fract_loop_inp.C
#include <iostream>

using namespace std;

void display_fraction(int num, int den);

int main()
{
int numerator, denominator;

while( cin >> numerator >> denominator )
{
cout << endl;

display_fraction(numerator, denominator);

}

return 0;
}

void display_fraction(int num, int den)
{
cout << num << "/" << den << endl;
return;
}

The above program also can be written using the I/O file.  As you may recall to be able to do this we need to go through some steps:
1) Include <fstream>
2) declare the input and/or output streams
ifstream  sinp;
ofstream sout;
3) connect the streams to appriperiate files (input streams to input streams and output streams to output streams).
3a) fail test the connection to make sure it is established correctly
4) start reading from and/or writing to input and/or output files
5) once done close the connections, sinp.close();  or sout.close();

Here is the above program with the file I/O:
//fract_loop_inp.C
#include <iostream>
#include <fstream> // (1)

using namespace std;

void display_fraction(int num, int den);

int main()
{
int numerator, denominator;
ifstream sinp;  // (2) declare the input stream

sinp.open(“myinput”); (3) attempt to connect to input file

//Fail test
if(sinp.fail( ))
{
cout << “Input file Open failed \n”;
exit (1);  //terminate the program
}

while( sinp >> numerator >> denominator )
{
cout << endl;

display_fraction(numerator, denominator);

}

sinp.close( );  //(5) close it
return 0;
}

void display_fraction(int num, int den)
{
cout << num << "/" << den << endl;
return;
}

Mon Feb. 23
We started Chapter (5) File I/O

Fri Feb. 20
We talked about functions again.  We talk about call-by-reference.  In order to show how it works we wrote a program.

Write a program that uses one function called rotate_them that takes three variables of type double and makes the value of each assign to the next.  Display the three variables before and after you called this function. Example:

Suppose, before you call this function, you have:
first = 2, second 5, third = 9

After you call the function, you should have:
first = 9, second 2, third = 5

For this to happen we need to do something like this:
temp = first;  // To preserve the initial value of the first
first = third;
third = second;
second = temp;

#include <iostream>

using namespace std;

void rotate_them(double& , double&, double&);

int main()
{
double first, second, third;
cout << " Enter three double values  \n";
cin >> first >> second >> third;

cout << "the values before I call the function were\n";
cout << "first = " << first << " second = " << second
<< " third = " << third << endl;

rotate_them(first, second, third);

cout << "the values after I call the function were\n";
cout << "first = " << first << " second = " << second
<< " third = " << third << endl;

return 0;
}

void rotate_them(double& a, double& b, double& c)
{
double temp;
temp = b;
b = a;
a = c;
c = temp;

return;
}

Note that the key thing here is & that we used when we declare the function and we defined it. As I said if we don't have this, then the first, second, and third will not take the changes you have made in the function. IT DOES NOT STICK. And by the way once again remember the YES_NO_YES rule. In the declaration (Yes to &), in the function call (No to &) and in the function definition (Yes to &).

Then we wrote a program that would display some characters as a row. The program used a function that would take as its argument the number of characters in the row and the character itself.
#include <iostream>
using namespace std;

void display_a_row(int num, char ch);

int main()
{

int num;
char ch;

cout << "Enter number of rows: ";
cin >> num;
cout << endl;

cout << "Enter a character: ";
cin >> ch;
cout << endl;
display_a_row(num, ch);

return 0;
}
void display_a_row(int num, char ch)
{
while(num > 0)
{
cout << ch << " " ;
num--;
}

cout << endl;

return;
}

This program displays:
C C C C

When you enter 4 and C.

Note that is this program we have called display_a_row function but we did not pass any arguments to it as call-by-reference.  This function does not change the values of num or ch, so no need for &.

I want you to make changes in this program so this time it displays a column like this:
C
C
C
C

Wed. Feb. 11, Fri. Feb. 13, Mon. Feb 16, and Wed. Feb. 18

On Friday Feb. 13, we had a mini quiz for 50 points.  On Monday Feb. 16, we solved that in class.

We worked on functions.  We started with the program that used two functions to compute the area of a circle or square depending on the choice that the user would make. We wrote the program in class and I sent you that program as an attachment.

We talked about type casting.  I gave an example about number of people in a course.  Assuming number of students is an integer and the number of classes are also integer. Then if we divide the number of students by number of classes, we would end up getting an integer.

int no_of_students = 300, no_of_classes 14;
double students_per_class;

One may think that since student_per class is of type double, then the following:
students_per_class = no_of_students/no_of_classes;

results in a double value. Actually that is not true. The double value does not have the correct decimal point because on the right hand side both values involved in the division are integers. There are several ways to fix this:

1) we can multiply the numerator or denominator by 1.0:
students_per_class = no_of_students*1.0/no_of_classes;

2) We can use static type casting.  Which means we call a pre-defined function to return the double version of no_of_students, or no_of_class.  Here is how we use it:
students_per_class = type_cast<double> (no_of_students)/ no_of_classes;

Note that the type is defined within < >, and can be changed to other types as needed.  Note also that this procedure DOES not change the type of no_of_students, the function will take no_of_students as an argument and will return its equivalent in double type.

We talked about overloading function names.   We re-wrote the program that computed the area of a circle and a square.  I sent that program also as an attachment to you.

Remember, you can overload a function name if:
2) The functions are of different types, and
3) Both 1 and 2

At last we wrote a program to swap the values of two variables.  In order to do this, we needed an extra temporary variable to hold one of the values (to preserve it) while we copy one variable onto another:

int temp, first = 7, second = 8;

temp = first;
first = second;
second = temp;

Now first = 8, and second = 7.

We wrote the program that swap the values.  I asked you to write this program using a function swap that takes the two values and swap them.

Friday Feb. 6 and Monday Feb. 9
We start talking about functions.  We deal with a function as if it is a black box.  A function MUST have 1) a name, 2) a type, and 3) proper arguments.

Let's work on this.  A name is what you know (or call) the function with.  A type is what the function (box) provides once it is done with the computations that are built inside of it, and the arguments are what you will give to the function to use in its computations. Sometimes, you may not have anything as argument.  Let's build on this.

//Computes the size of a dog house that can be purchased
//given the user’s budget.
#include <iostream>
#include <cmath>
using namespace std;

int main( )
{
const double COST_PER_SQ_FT = 10.50;
double budget, area, length_side;

cout << "Enter the amount budgeted for your dog house \$";
cin >> budget;

area = budget/COST_PER_SQ_FT;
length_side = sqrt(area);

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of \$" << budget << endl
<< "I can build you a luxurious square dog house\n"
<< "that is " << length_side
<< " feet on each side.\n";

return 0;
}

Suppose in this program, I want to have a black box to compute the area of the house. I need: 1) A name, 2) A type, and possibly 3) arguments.  Ok.
For obvious reason, a good name is:
1) area_pethouse,

Since this function is computing the area and area seems to be a value of type double in our program, then a proper type for this function is:
2) type for this function double,

Now, we need to talk about the argument(s).  If this function is to compute:
area = budget/COST_PER_SQ_FT;

Then it needs the budget and COST_PER_SQ_FT. Right? But the COST_PER_SQ_FT is a constant and there is no point of passing it to the function (although we could) ever time we call the function. So, we can declare that as a constant inside the function. However, the budget may change, so that is what we will pass as an argument.  So:
3) We have only one argument and that is of type double.

Now that we are at this discussion I want you to look at this statement from this program:
length_side = sqrt(area);

What does this do?
It is calling a function called sqrt and passing to it an argument of type double called area and the function returns a value of type double that we will store it in as length_side.  Since we are not defining the sqrt and is already defined for us, we call this type of function pre-defined function.  Different pre-defined functions come from different libraries. The sqrt function is defined in the cmath. That is the reason you have the #include<cmath> at the top.

This is the above program written with a function.

//Computes the size of a dog house that can be purchased
//given the user’s budget.
#include <iostream>
#include <cmath>
using namespace std;

double area_pethouse(double budget);  // (1) This is function declaration

int main( )
{
double budget, area, length_side;

cout << "Enter the amount budgeted for your dog house \$";
cin >> budget;

area = area_pethouse(budget);  // (2) The function call
length_side = sqrt(area);

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of \$" << budget << endl
<< "I can build you a luxurious square dog house\n"
<< "that is " << length_side
<< " feet on each side.\n";

return 0;
}

// (3) Function definition
double area_pethouse(double budget)
{
const double COST_PER_SQ_FT = 10.50;
return budget/COST_PER_SQ_FT;
}

Pay close attention on the changes we have made.

I am going to use the same program to compute the size of the house for many different pets.  Suppose I want to ask users to enter 'y' or 'Y', if they wish to compute a new house.
//Computes the size of a dog house that can be purchased
//given the user’s budget.
#include <iostream>
#include <cmath>
using namespace std;

double area_pethouse(double budget);  // (1) This is function declaration
void display_length(double length_side, double budget); // Function declaration

int main( )
{
double budget, area, length_side;
char ans;

do
{

cout << "Enter the amount budgeted for your pet house \$";
cin >> budget;

area = area_pethouse(budget);  // (2) The function call
length_side = sqrt(area);

display_length(length_side, budget); // Function call
cout << "Do you want to repeat for another house \n";
cin >> ans;

} while( ans == 'y' || ans == 'Y');

return 0;
}

// (3) Function definition
double area_pethouse(double budget)
{
const double COST_PER_SQ_FT = 10.50;
return budget/COST_PER_SQ_FT;
}

// Function definition
void display_length(double l, double b)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of \$" << b << endl
<< "I can build you a luxurious square pet house\n"
<< "that is " << l
<< " feet on each side.\n";
return;  // Since it is a void function, return nothing
}

One last thing and I will be done :-).  The display_length function was used for display purpose ONLY. It didn't return anythimg, so we have it of type void.  That is one thing.  The other thing I wanted to tell you is this.  Suppose for some un know reason, I wanted also to display the cost-per-square-foot along with the budget and the length. What could I do?  Notice that cost-per-square-ffot is now declared as a constant inside the area_pethouse function. That variable is local in that function, he is the kid known in that block only. So, somehow I have to introduce it to the display_length.  Since this is a constant we can make it known by all functions, make it be a global rather local.  To make a variable of type global, we will declare it just before the main function.  Here is a new version of the program.

//Computes the size of a dog house that can be purchased
//given the user’s budget.
#include <iostream>
#include <cmath>
using namespace std;

double area_pethouse(double budget);  // (1) This is function declaration
void display_length(double length_side, double b); // Function declaration

const double COST_PER_SQ_FT = 10.50;  //Declare globally

int main( )
{
double budget, area, length_side;
char ans;

do
{

cout << "Enter the amount budgeted for your pet house \$";
cin >> budget;

area = area_pethouse(budget);  // (2) The function call
length_side = sqrt(area);

display_length(length_side, budget); // Function call
cout << "Do you want to repeat for another house \n";
cin >> ans;

} while( ans == 'y' || ans == 'Y');

return 0;
}

// (3) Function definition
double area_pethouse(double budget)
{
return budget/COST_PER_SQ_FT;
}

// Function definition
void display_length(double l, double b)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "For a price of \$" << b << endl
<< " and cost-per-square-foot of " << COST_PER_SQ_FT<< endl
<< "I can build you a luxurious square pet house\n"
<< "that is " << l
<< " feet on each side.\n";
return;  // Since it is a void function, return nothing
}

Wednesday Feb. 4
We continued with the while loop.  One of the things we discuss was the correctness of the condition.  For example, look at the following example:

char c = 'y';
int count = 0;
while( c == 'y' || c == 'Y')
{
cout << "Enter a new character \n";
cin >> c;
count++;
}

Here are the question I have for you:
1) Which condition are you checking in the while?
We check to see whether c is 'y' or 'Y'
2) Ok, Good.  What is your update statement?
Believe me or not, I have so many students telling me that is count++.  We update the count by 1.  But is that really true.  If you are checking on the character c, then your update has something to do with c. Right? Right. So the true update statement is cin >> c.  That is where you are getting a new character. Right?

3) Of course now you can answer this one, what was the proper initialization for the loop?
NOT int count = 0; said the wizard.  It is char = 'c', you know why? right?
Please study the programs and study questions in Chapter (2). We are done with it.

Monday Feb. 2
We talked about loops.  We gave two example using 5 pens.  In the first one, we asked someone to pick 5 pens one-by-one.  For him to do this correctly:
1) He needs a counter to keep track of the counts, and that counter should be set at 0 at the start
2) Then he needed a mechanism to check on the counter to see if it has reached 5.  And if it didn't then he would get another pen,
3) Then he would need to update the count every time he would go to get a new pen.

This lead us to a program segment like this:

int count = 0;

while(count < 5)
{
get another pen;
count++;
}

We could do this using reverse count:

int count = 5;

while(count > 0 )
{
get another pen;
count--;
}

Then, we talked about doing this in a different way.  This time, we ask the user to get pens as long as some left. So he gets the first one, and goes back and if there exist another pen, gets that one, and so and so forth, until there is no more pen left.  The program segment may look like this one:

get a pen

while(more pen left)
{
get another pen;
}

This way there is no guarantee we bring back 5 pens, we bring more or less depending on how many pens were there behind the desk.

There is also another way to do this:

char ans  = 'y';

while(ans == 'y' || ans == 'Y")
{
get another pen;
cout << "Do you want to get another pen ";
cin >> ans;
}

We looked at several examples from the text-book where while loop was used.

By the way, we have while and we have do ... while.  When we set up while loops we check the condition first. With a do while we check the condition last.

So for example in the above example that users need to enter a y or Y for yes and other things for no, we have to initialize the ans to 'y' or 'Y', so we go through the loop at least once.  But we can write that segment like this:

char ans;

do
{
get another pen;
cout << "Do you want to get another pen ";
cin >> ans;
}while(ans == 'y' || ans == 'Y");

As you perhaps have noticed, this time we haven't initialized ans. But, we go through the loop once before we check the condition.

Friday Jan. 30
I know what day today is, we get a paycheck.  Wow.  But wait.  Suppose I get my paycheck and find out that I am getting \$120 less than what I usually get.  That was actually the case this time. So what are the things I can do to find out that out.  What are possible scenarios.  Help me out here:
2) Does insurance or parking cost go up?
3) Was there an increase in our State or Federal Tax?
4) Did I use my cash card more often than usual?
5)
6)

What else? Well, I leave this up to you to think about.  Hopefully, you can find an answer.  I am getting you further in the if statement maybe you can use it to solve the mystery.

We re-wrote the age-gpa program of last class using a different if statement at first..  Here is the new program:
#include <iostream>

using namespace std;

int main()
{
double age, gpa;

cout << "Enter an age \n";
cin >> age ;
// Determine whether age is a valid one
if( age >= 0 && age <= 120)
{
cout << "Enter an GPA \n";
cin >> gpa;
// Determine whether gpa is a valid one
if( gpa >= 0 && gpa <= 4.0)
{
cout << "Age = " << age << "GPA = " << gpa << endl;
}
//Invalid gpa
else
{
cout << "Invalid gpa \n";
return 0;
}
}
// Invalid age
else
{
cout << "Invalid age \n";
return 0;
}
return 0;
}

We talked about things that our program do many times, thus we needed a Looping Mechanism.  There are usually two different ways to make some activities repeat:
1) Use a counter to count as many times as we wish that thing to happen, or
2) Set a condition and stop the process once that condition is met.

Regardless of how we set our loop a good loop should always have:
1) Correct Initialization: We should know where to begin. If we are using a counter, the first count
2) Correct Condition: We need to have a good condition to check on the status of the process, and
3) Correct Update: We also need to have an update in what we are checking to stop the process.  If we are checking on the counts, then that counts should get updated every time we complete one loop.

The structure of a while loop looks like this:

Initialization

while( Boolean_Expression)
{
Statement 1;
Statement 2;
...
UPDATE;
}

Wed. Jan. 28
We talk about two different if statements: 1) that was put in place to separate a particular group, 2) an the other that was put in place to separate two different groups.

1) For this one we gave an example.  Suppose we want to read bunch of integers and turn the one that are negative to positive.  I such a case, we only look for negative values and we really don't have anything to do with the positive ones. So an if statement like the one below would do:

if( value < 0)
value = value * (-1);

I asked you to think about a program that asks users to input their age and gpa.  And display a message on what the age and gpa was, ONLY if a valid age (between 0-120, including both) or a valid gpa (between 0-4.0, including both) are entered.  Here is one approach:

#include <iostream>

using namespace std;

int main()
{
double age, gpa;

cout << "Enter an age \n";
cin >> age ;

//Determine whether age is Invalid
if( age < 0 || age > 120)
{
cout << "Invalid age \n";
return 0;
}
cout << "Enter an GPA \n";
cin >> gpa;
cout << endl;

//Determine whether gpa is Invalid
if( gpa < 0 || gpa > 4.0)
{
cout << "Invalid GPA \n";
return 0;
}

//If you last up to this point, then both age and gpa were valid
cout << "Age = " << age << "GPA = " << gpa << endl;

return 0;
}

Mon. Jan. 26
You must be in command mode.
vim Tips: Once you open a file you can search for a particular phrase,
:/Phrase
vim Tips: Once you find a phrase, you continue searching for other occurrences of it using
:/

We talked about   about different variable types, basically went through Display 2.2. Also we discussed what Boolean variables are.  We then talk about the program on Display 2.3.  In particular we mentioned how symbol3 became a single blank space when we used:
symbol3 = ' ';

We also shoed that if we attempt to put more than one space we will get an error warning.  We talked about three different error types:
1) Syntax error: due to syntax in your program, missing braces, missing ; , incorrect use of << or >>, etc.  Compilers pick this one for you and will usually tells you where to look for them. You need to fix them.
2) Run-time error. Happens when you try to do something that is not allowed by the compiler, like dividing by 0 or taking the square root of a negative value.  You will be warned of this one when you run the program.

3) Logic error, is your error.  Something like having + in place of - or using a wrong equation. In such cases, the only way to find the error is to test your answers.

Fri. Jan. 23
vim Tips: Once you open a file in vim editor, you can go to a particular line by typing
:LineNumber.
You must be in command mode.

Started Chapter (2).   We talked about how cout works and how C++ compiler displays a new line.  We wrote a small program to display:
Hello
Hello        Hello
Hello
//Here is the program
#include <iostream>
using namespace std;

int main( )
{
cout << "     Hello\n";             //This displays a Hello, and opens a new line
cout << "Hello      Hello\n";   //This displays a 2 Hellos, and opens a new line
cout << "     Hello\n";            //same as the first one

return 0;
}

Of course, the three lines that displayed the Hellos could be replaced with one.  With one you said? Yes. Here it is:

cout << "     Hello\nHello      Hello\n     Hello\n";

Then we wrote another program.  The new one asked users to enter two integers and then displayed the difference of the of two in two different ways: 1) first one - second one, and 2) second one - first one.

We took some steps to write this program:

START
Declare variables first, second;
Declare ans1, and ans2  (I like first_second, and second_first better)
Display a statement asking users to enter the two values
Compute ans1, ans1 = first - second
Compute ans2, ans2 = second - first
END

Now we can translate the above algorithm to a C++ code:

#include <iostream>
using namespace std;

int main( )
{
int first, second; //declaring the two input variables
int first_second, second_first; //declaring the variables for answers

cout << "Enter the two integers separated by a blank space\n";
cin >> first >> second;  //Read the two values from the keyboard

first_second = first - second;  //compute the first difference
second_first = second - first; // compute the second difference

cout << "The first - second =  " << first_second << endl;
cout << "The second - first = " << second_first << endl;

return 0;
}

We may have other variable types in a program.

Wed. Jan. 21
vim Tips: To open a file simply type vim filename at the prompt (% vim  Myfile.C).  If that file exists, it will be displayed. If that file doesn't exists, you will get a blank sheet.
vim Tips: To start typing in a vim page, you need to press "i" to go the Insert ode.  Look at the bottom left to see if you are in Insert Mode.  You use the Insert mode to type.  To Move around you need to be in the Normal mode.  To get to that mode, press Esc.  Note that he word Insert at the bottom left gets disappear once you are switched to normal mode.

vim Tips: To save a file, go to the Normal mode, then type : (this appears at the bottom left).  Here the possible options:
to save and quit, type  :wq
to save but stay in the same screen, type :w
to quit without a save, type :q!

Finished Chapter (1) and talked about a simple C++ programs.  Talked about different errors.
We discussed the last problem on Quiz (3).  I gave different examples and we tested the algorithm for that problem to make sure that all conditions are met.

We then discussed a sample program.  I noted that every program starts from a point and ends at another.  For now you can assume that the starting point in your programs is:

#include <iostream>
using namespace std;

int main( )
{

And the end point is:

return 0;
}

Whatever goes in between these two points determine the purpose of the main program.  For example, the following program displays three "Hello" statements, but can you tell in what format?
#include <iostream>
using namespace std;

int main( )
{
cout << "     Hello";
cout << "Hello  Hello \n";

return 0;
}

Note that due to indentation the open braces are seeing each other. Then they are happy.

At last, we talked about program on Display 1.8. I asked you to study it carefully.  We will have a short quiz on Friday.

Mon. Jan. 19
MLK Holiday

Fri. Jan. 16
Chapter 1, solved few problems.  quiz (2) Continue problem solving and algorithm design.
What do we need to solve a problem using a computer:
1) Define the problem clearly
2) Select your method, in our case we use a computer to solve our problems
3) Design an algorithm, we draw our thoughts on paper
4) Test that algorithm to make sure it does what you want it to do.