bg287

csc110

Posted in csc110 by bnmng on 2010 04/27

Thursday: Lab
Final: Tuesday, May 4th: Starts at 10 but can show late.
Final exam will be 7 questions. Two of them will be on arrays.
1) Chapter 1 or 2 on Brookshear
2) Chapters 1 through 3 of Bronson
3) Chapter 4 of Bronson
4) Chapter 5 of Bronson
5) One on Chapter 6 of Bronson/Brookshear
6)Arrays
7)Arrays

Be sure to review older material: Read Write time for various media; Precedence rules of operators.

Advertisements

csc110:Arrays

Posted in csc110 by bnmng on 2010 04/20

Next program is 20 Percent of grade. Due may 4th during the final.

Final Tuesday May 4th at 1000. If you show late you’ll be OK.

Homework due Tuesday, April 27. Chap 8 Bronson

Lab on the 29th.

8.1: 1, 2
8.2 1,5
8.3 1, 2, 3, 4 part(a)

Today:
Arrays as arguments

Arrays are a structured type. An array defined with 100 elements is numbered 0 to 99.
An array has an index.
Processing an array involves a loop. Means if you have an array.
Arrays should be named with a plural form.

void getlist (int [], int &) // Arrays are always passed by reference (don’t use a & for an array).
void putlist (cost int [] ) // this allows the array to be passed but the function can’t change it.

We won’t be responsible for the stuct feature in Mr. Sterling’s program.

Finding the minimum index (that is the index of the minimum value).
0=45
1=57
2=14
3=19
4=59

use an auxiliary variable called Min Index.

csc110

Posted in csc110 by bnmng on 2010 04/15

Today:
One Dimensional Arrays (8.1 Bronson)
Declaration
Indexing
IO

Array Initialization

Homework: 8.3 Bronson.

April 22: Free Class.

One more program due & one more homework due.

What we can do with arrays.
You can use arrays as arguments to functions. But for the most part, you don’t do much with arrays as a whole. Instead, you work with individual elements in the array. What that means is, you don’t say “myarray=12”; Instead you say “myarray[0]=12” or “myarray[6]=27″ or whatever.

Array Initialization.
We can assign a series of values to the array at compile time.

You can initialize arrays as follows:
int grade[] = {98,87,38,50,97};
This will initialize and populate a 5 element array.

int grade[10] = {98,87,38,50,97};
This will initialize a ten element and populate the first 5 elements (grade[0] to grade[4]). It will also populate the remaining elements (grade[5] through grade[9]) with zero.

cstrings are arrays of characters. There are special features in c++ which allow us to do things with cstrings that we can’t do with other arrays. The last character has to be followed by a zero.

char name1[]=”mary”; //This works. It creates a 5 element array of ‘m’, ‘a’, ‘r’, ‘y’, and 0.
char name1[4]={‘m’,’a’,’r’,’y’}; //This creates an array BUT it’s not a cstring because it doesn’t terminate with a zero.
char name1[]={‘m’,’a’,’r’,’y’}; //Same as above. This will initialize a four variable array that is not terminated with a zero.
char name1[5]={‘m’,’a’,’r’,’y’}; //This works. Because it’s specified as a 5 element array, it will initialize the array with ‘m’, ‘a’, ‘r’, ‘y’, and 0.

Last program next Tuesday.

csc110 2010 April 13

Posted in csc110 by bnmng on 2010 04/13

Program due Thursday.

Today:

Read 8.1, 8.2 Bronson

Test 3

Free time for questions and help with test.

– – – –

Going over test:

The output of the first loop goes from 1 to 9.
Even though it starts with I equaling zero, it increments before the first cout, so it couts after i++, when I equals one.
Even though the test was i<=8, it passes the <=8 test, then increments, then couts. Now it’s 9 and fails the test for the next time around, so the loop ends. But that’s after it incremented and printed.

The second loop prints from zero to 8. It starts with i equaling zero. Since i equals zero, it passes the test, then couts. Since it counts before it increments, it couts zero. It increments to 1, but before it couts, it it passes the test again. Then it couts with I equaling 1, then i increments. When i increments to 8, it passes the test and couts. Than i gets incremented so it equals 9. But even though i makes it to 9, it never gets couted as 9, because it fails the test before it prints.

Using Functions:

Test #3.

Posted in csc110 by bnmng on 2010 04/04

Here’s my take on the sample test that we got on Thursday

1)
The following loop calculates 2 to the power of n.
For example, when n is 3, it calculates 2*2*2 (three times)

Identify the parts of the loop using the following list:
1) Test
2) Update of control
3) Initialization of Execution
4) Update of Execution
5) Initialization of control

n=2;
i=1;  // initialization of control
product=1; // initialization of execution
while(i <=n) // test
{ product=product*2; // update of execution
i=i+1} // update of control

When two people are talking, the word “execution” refers to something like an activity or an event; as in the execution of an order, or the execution of an operation, or the execution of Paul Powel.  I’m against the death penalty – not because some people don’t need killing; but because the government shouldn’t have that authority.  But I digress.  For our purposes, and the purpose of test3, think of “execution” not as an activity but as a variable.  The purpose of the loop is to update the execution.  In the above example, the execution is productproduct is the reaon for the loop’s existence.  So you can say to you’re girlfriend or boyfriend, “You’re my execution.”  She or he won’t know what you’re talking about but you’re a computer geek so it probably happens all the time.  So when product gets initialized, that’s the initialization of execution, and when product gets updated, that’s the update of execution.

The control is like a traffic light.  You’ll base your decision on what to do by the color of the traffic light (stop, go, or go fast before it changes).  The traffic light doesn’t make you stop; That’s a decision you have to make on your own. You decide to stop (hopefully) when you see a red light.  In the loop, the control is i.  i has a value which changes as the loop executes, and each time the loop goes around, the program makes a decision, based on the value of the control, whether to stop or go.

The test is where the decision is made.  At the traffic light, the test is “Go if the light is green” or “Stop if the light is red”,  In the example above, the test is “Go while i is less than n“.

What is the output of the following program?

#include <iostream>
using namespace std;
void inorder(float &, float &);

int main()
{
	float n1=41.6, n2=19.2;

	inorder (n1, n2);
	cout << "n1= "<< n1 << "n2=" << n2 << endl;
	return 0;
}
void inorder (float &num1, float & num2)
{
	float temp;
	if(num1 > num2) 
	{
		temp=num1;
		num1=num2;
		num2=temp;
	}
}

nl =  19.2        n2 = 41.6

Answer the same question if the protype and heading are changed as follows:

void inorder (float, float);
void inorder(float num1, float num2)

nl =  41.6        n2 = 19.2

Remember the simile with the teacher and the students.  Passing by reference (using the “&”) is like sending the function to the board to work on the original data.  Passing by value (not using the “&”) is like giving a copy of the data to the function and expecting brand new data back.  

In the first program, the plan worked.  We said to the function, “Here’s two references to variables, n1 and n2.  Go find them and do your thing on them.   But don’t take them; When you’re done, leave them right were they are.”

In the second program, we screwed up.  We said “Here’s two copies of my variables, go do your thing on them.”  But we never got any data back because the function doesn’t have a return statement. Even if the function did have a return statement, it could only return one value.

Once you give something to a function, you never get it back.  You can get back something else, if the function has a return statement, but the data you gave to the function will die when the function ends..  

Rewrite the following while loop as both a do-while and a for loop.  Write in C++, not pseudocode.

i=5;
while (i >=1)
{ 
	cout << i << endl;
	i = i-1;
}

A do-while loop:

I actually screwed up my do -while loop on the last test, but I got it right now. You can trust me.

i=5;

do 

{

	cout <<i << endl;

	i = i-1;

} while (i >=1);




A for loop:

for(i=5; i>=1; i=i-1)

{

	cout << i << endl;

}




A do-while is similar to a while but the test is at the end of the loop instead of the beginning. Remember to put the semicolon after the test on the do while loop but not on the while loop.

A for loop has the initialaztion, test, and the update of the contol all in one line.

What is the output of the following code?

#include 
void proc4(int &, int)
int main()
{
	int D, E;
	D=27; E=18;
	proc4(D,E);
	cout <<"After call in main" << D << " " << E << endl;
	return 0;
}
void proc4 (int & r, int s)
{
	cout << " Beginning of function " << r << " " < < s << endl;
	r=41;
	r=63;
	cout << " end of function " << r << " " < < s << endl;
}

Beginning of function 27 18
end of function 41 63
After the call in main 41 18

This is another exercise in by-reference vs by value.  Main called proc4 and passed two parameters to it.  The first was called D, and the second was called  E.  

For the fist parameter, proc4, using the “&”, took the parameter as a reference.  It said, “I need to find this variable and do something with it”.  For the second parameter, proc4 took it as a value.  It said, “I got a variable to keep for the rest of my life”.  

It doesn’t matter that main and proc4 called these variables by different names.    I call my son “Bill”,  but where he works, everyone calls him “Billy”.  It’s the same guy with different names.  On the other hand, there’s another guy were he works also named “Bill”, but he’s not my son.  Different guy; same name.  They don’t have the same name in the same place, which is why they call my son “Billy”.  He would prefer they called him “William” but that’s beside the point.  The point is, don’t worry about the names.  Worry about the order they were passed and whether they were passed by reference or value.

So proc4 took a reference to one variable and a copy of another.  The variable that it had a reference to, it called r.  It had to find r but it couldn’t take it away.  The copy of the other variable, it called s.  It owned that copy and never give it back.

The first thing that proc4 did was cout the values of r and s.  Then proc4 changed r, and left it where it found it.  Proc4 also changed s, but s was proc4‘s own personal copy.  

Proc4 then couted the new values of r and s.  Having done it’s thing, Proc4 ended and took its copy of s with it.  

Meanwhile, back at main, after calling proc4, D was changed.  That’s because D was the variable that proc4 called “r”.  It was the variable that proc4 found, changed, and left in place.  But nothing happened to E.  Proc4 had a copy of E, which it called s, but proc4 never had the original E.

Given the following code, answer the questions after it

#include 
void proc4 (int &, int);  // function prototype 


int main ()
{
	int D, E;
	D = 27; E=18;
	proc4 (D,E);  //function call
	cout << "After call in main " << D << " " << E << endl;
	return 0;
}
 void proc4(int & r, int s)
// function body starts here
{
	cout << " Beginning of function " << r << " " << s << endl;
	r=41;
	s=63;
	cout << " end of function " << r << " " << s << endl;
}// function body ends here

What are the actual parameters? D and E

What are the formal parameters? r and s

I don’t like the terminology, but I wasn’t there when they were passing out names. Just remember that the actual parameters are in the call. Actual:Call.

csc110

Posted in csc110 by bnmng on 2010 04/01

Homework, (paper handed out) due Thursday, April 15t.

Test 3 covers chapters 5 and six of both textbooks. Sample test handed out. Test 3 is Tuesday April 6th. Lab Thursday April 18th.
Bronson: two on Chapter 5
Brookshear Three on 6.3 Brookshear and 6.3 Bronson.

Not introducing new material today. Just looking at the program.

Today: Look a t program 3 and sample test 3.

If yo missed turning in your program, or have errors to correct, you can resubmit with a 15 point late fee.

Programming functions:

Skip the temptation to start programming without functions and then try to put your code into functions later.

Example: A program with a sentinel loop.
The proper structure for a sentinel loop is : primary read, test, read data.

getData ( principle, years, rate).

Casting. You can use casting

Initializing the control

Parameters in calling statements, headers, and prototypes must agree in type, number, and order.

Alias. (I’ll write about Alias later, but it’s pretty much the same as reference

Three things for functions: Prototype, Call, Definition. For references, the ampersand appears in the prototype and definition, Not in the call.

Actual parameters appear in the call. Formal parameters are in the heading.

The function call is in the main.

The function body is between the curly braces in the definition.

The prototype is above the main.

csc110

Posted in csc110 by bnmng on 2010 03/30

Homework due Thursday
Brookshear (eoc exercises): Chapter 6 : 7, 8, and 29
Bronson Chapter 6 Section 6.1 1, 2a, 6a
Sectin 6.2

Test 3 will be Next Tuesday, April 6.

Today: Bronson 6.2 Returning a simple value; 6.3 Call by reference, pass by reference.

Procedural: A jump from the normal program flow.
Advantages: Useful thinking tool. Modularizes parts of code into separate sections.

Arguments in the caller are “actual arguments”
Arguments in the header are called “formal arguments.”.

Passing arguments. Sometimes you want to pass a

You can call function which returns a value.

Our instructor doesn’t like 6.1. he Emphasizes functional cohesiveness.

When using a function we need three things: Prototype; Call; Definition. By convention, you don’t need names for the arguments in the prototype, but modern teaching includes names in the prototypes.

Also, the prototype is only needed if we define the function after

You need a return statement for any function that returns a value. If you forget your return statement, the program will compile but it will run improperly.

Parameters are passed in order. The order of parameters in the prototype, call, and definition must match.

Example:
prototype:
void larger (int, int, int &);

Overloading. You can use the same name for two function that have different parameters. Example:
void something (int int);
int something (float int int&);
are two different functions.

By convention, two functions with the same name should do the same thing. The reason you would have two functions like this is because you might have to use different code for float inputs as you would for int inputs. For instance:

void divide (int numer int deno) {
int quo;
int mo;
quo=numer / deno;
mo=numer % deno;

cout << numer << "divided by " << deno << " equals " << quo << " remainder " << mo << endl;

}

void divide (float numer float deno) {
float quo;

quo=numer / deno;

cout << numer << "divided by " << deno << " equals " << quo << endl;

}

Using dummy variables inside functions.

csc110: Passing by Value or Reference

Posted in csc110 by bnmng on 2010 03/30

You’re a teacher, and you tested your students, but you gave each student a different test.

To one student, you provided a paragraph filled with mistakes, like “The Declaration of Independence was signed on April 1st, 1987”. You told that student to provide a clean, error-free paragraph on a new piece of paper. She asked, “What should I do with the paper you gave me?” and you replied, “It doesn’t matter; I have a copy.”

You also wrote some paragraphs on the board, and to one student, you provided a paper which said “Paragraph #2 on the board”. That student went up to the board and fixed the the paragraph right on the board.

To the first student, you passed a value. You gave the student a paragraph to fix. But you didn’t give that student you’re only copy, instead you gave that student something that had the same value as your original. And you didn’t want your paper back because it was just a copy. Instead you wanted a fresh, clean paper.

To the second student, you passed a reference. You didn’t actually give the student a paragraph; what you gave was the location of a paragraph. That student had to find the paragraph and fix it. When the student fixed the paragraph, he did so by altering the original. He didn’t have to give anything back to you because the only thing he had was a location.

Back to functions. You either pass the function a value or a reference. The value is a copy of the original; it has the same value. The reference is the location of the original; you’re telling the function to go get the original.

Passing by value is the default. To pass by reference, you have to write the prototype and the header slightly differently. This is a partial program with a function that takes a parameter by value:

int doublethis ( int ); 

void main () {
	int number=1;
	int doubled;
	doubled=doublethis(number);
	cout << doubled << endl;
}

int doublethis(int somenumber) {
	somenumber=somenumber*2;
	return somenumber;
}

This is a partial program with a function that takes a parameter by reference:

void doublethis ( int& ); 

void main () {
	int number=1;
	doublethis(number);
	cout << number << endl;
}

void doublethis(int& somenumber) {
	somenumber=somenumber*2;
}


The major difference is the “&” in the prototype and the header. This tells the function that the parameters which it will receive are references. So “int&” doesn’t mean that the function is getting an integer; it means that the function is getting an address to where an integer is stored.

Besides the differences in the prototype and header, the code is a little different. The function in the first program returns a value but one in the second doesn’t.

You can have many different combinations of references and values. Going back to the teacher/student example, you can tell you’re students to work on the board AND turn in a paper. You can even tell the student to fix the paragraph on the board AND turn in a paper with the number of problems that he fixed. The catch is you can only get one paper back ( and in my example, there is only one answer on a paper ). If you want more than one answer, you have to send the student to the board. But you can send him to the board as often as you like.

csc110: Functions and Procedures Part II

Posted in csc110 by bnmng on 2010 03/26

In C++, there’s no formal difference between a procedure and a function, and most programmers will use the term “function” to describe either one. But when “procedure” is used, it is used to describe a function that doesn’t return a value. Procedures are defined as void, as in:

	void displayvalueof( int somevalue )
	{
		cout << "The value of something is: " << somevalue << endl;
	}

The procedure above can be called as follows:

	cout << "Enter a value: ";
	cin >> usersvalue;
	cout << endl;
	displayvalueof (usersvalue);

Functions often return a value. When they do, they are not called “procedures”, and they are defined by the type of value they return.

	int doublevalueof( int somevalue )
	{
		somevalue=somevalue*2;
		return somevalue;
	}

The function above doubles the value that it was given, then returns it. The line

	return somevalue;

, tells the function to pass the value of somevalue back to the caller.

When you call a function that returns a value, the function can be used as if it was that value.
The above function can be called as follows:

	cout << "Enter a value: ";
	cin >> usersvalue;
	doubledvalue=doublevalueof (usersvalue);
	cout << "The doubled value is: " << doubledvalue << endl;

The line
doubledvalue=doublevalueof (usersvalue);
assigns the value that the function returns to doubledvalue.

Note that I didn’t put a cout statement in the function. I could have done so, but generally it’s better to have your functions and procedures stay on mission. What I mean is, doublevalueof‘s mission is to double the value of something, displayvalueof‘s mission is to display the value of something. I could easily have written something that does both, but as a general rule, give your functions and procedures a mission and let them stay on that mission. This is the problem that our instructor has with the book. He feels that some of the functions in the book do too many different things.

The return type of the function and the types of its parameters don’t have to match. The function in the following program takes integer parameters but returns a float:

#include 
#include 

using namespace std;

float divide (int, int);

int main () {
	int firstnumber = 0, secondnumber=1;
	float quotient;
	
	cout << "Enter two integers for division.  A zero in the second integer will trigger an exit ('cause you can't divide by zero): " ;
	cin >> firstnumber >> secondnumber;
	cout << setw(5) << setprecision(7);


	while (secondnumber != 0)
	{
		cout << endl;

		quotient=divide (firstnumber, secondnumber);
		cout << "The result is: " << quotient << endl;
		cout << "Enter two more integers.  A zero in the second integer will trigger an exit: " ;
	
		cin >> firstnumber >> secondnumber;
	}
			

	//optional for Windows: replace both cin.get() with one system("PAUSE").
	cin.get();
	cin.get();

	return 0;
}

float divide (int numerator, int denominator) 
{
	float quotient;
	quotient= (float (numerator) / float (denominator)) ;
	return quotient;
}
	

csc110: C++ Functions and Procedures, Part I

Posted in csc110 by bnmng on 2010 03/25

My take on what we learned today

Say you have a program like this:
This program twice asks for a number between 1 and 10. If the user enters a something bigger than 10 or smaller than 1, it insults the user.

#include <iostream>
#include <iomanip>

using namespace std;
 
int main()  
	{
	int onetoten =0;
	int anotheronetoten=0;

	cout << "Enter a number from 1 to 10" << endl;
	cin >> onetoten;
 
	if (onetoten>=1 && onetoten<=10) {
		cout << "great, you can follow instructions" << endl;
	} else {
		cout << "You're an Idiot!" << endl;
	}
	
	
	cout << "Enter another number from 1 to 10" << endl;
	cin >> anotheronetoten;

	if (anotheronetoten>=1 && anotheronetoten<=10) {
		cout << "great, you can follow instructions" << endl;
	} else {
		cout << "You're an Idiot!" << endl;
	}
	
	cin.get() // I use this instead of system(“PAUSE”)  
	cin.get() // because “PAUSE” is an MS Windows command
	return 0;
}

As you see, you there’s some redundancy. It would be nice if you could take some of the redundancy out. Here’s how:

#include <iostream>
#include <iomanip>

using namespace std;

void checknumber(int);

int main()  
	{
	int onetoten =0;
	int anotheronetoten=0;

	cout << "Enter a number from 1 to 10" << endl;
	cin >> onetoten;

	checknumber(onetoten);

	cout << "Enter another number from 1 to 10" << endl;
	cin >> anotheronetoten;

	checknumber(anotheronetoten);

	cin.get(); // I use this instead of system(“PAUSE”)  
	cin.get(); // because “PAUSE” is an MS Windows command 
	return 0;
}

void checknumber (int thenumber) 
{
	if (thenumber>=1 && thenumber<=10) {
		cout << "great, you can follow instructions" << endl;
	} else {
		cout << "You're an Idiot!" << endl;
	}
}


In this example, I might not have actually saved any typing because the program is pretty simple. As your programs get more complex, you’re going to appreciate the advantages of taking some of your code outside of the main() routine and placing them in separate functions or procedures (I wrote about the terminology of “functions” and “procedures” in my next post).

I took the lines that check the number and insult the user and I put them in a procedure which I called “checknumber”. When I wanted to use it, I called it from inside main.

At the top of the program I wrote:

	void checknumber(int);

That was the prototype. Prototypes don’t seem to have any purpose but we have to have them in C++ . They actually do have a purpose, but for now just accept the fact that we need them. Some programming languages don’t require them.

In main() I wrote:

	checknumber(onetoten);


and later, still in main(), I wrote

	checknumber(anotheronetoten); 

Those were the calling statements. At that point, the program flow jumped out of main(), jumped to the checknumber procedure, ran the code in that procedure, then jumped back to line after the call. When the program jumped from the calling statement to the procedure, it took the value of the argument onetoten with it, the first time, and the value of anotheronetoten the second time.

Below main(), I wrote:

	void checknumber (int thenumber)


And under that I wrote the body of the procedure. This is the definition. The definition includes the header and the body. thenumber took the value of the argument that was passed to it.

It’s important to note:
In the prototype, you only need to describe the arguments, you don’t have to name them

	void checknumber(int); 

In the call, you need to pass required arguments to the function

	checknumber(onetoten);
	checknumber(anotheronetoten);

In the definition, you need to describe the arguments and name them:

	void checknumber (int thenumber) 
	{	
		if (thenumber>=1 && thenumber<=10) {
			cout << "great, you can follow instructions" << endl;
		} else {
			cout << "You're an Idiot!" << endl;
		}
	}

It’s important to be clear about why I didn’t use the same name for the argument in the calls that I did in the definition. In the definition I used thenumber; In the first call, I used onetoten and in the second I used anotheronetoten. It would suck if I had to match the names of the arguments in the calls to the names of the arguments in the procedure, because I’d have to use the same variable each time I called the procedure. I wouldn’t be able to use onetoten the first time and anotheronetoten the second time. Since the argument names in the call don’t have to match the argument names in the procedure, I can call the procedure with different variables each time. I can also do this, if I wanted to:

	checknumber(4);
	checknumber(15);

That’s all for tonight. This weekend I’ll write something about the difference between functions and procedures, about using functions as values, and about passing by reference or by value.