- 9/20/07 - Formatting - Integers - When you define a variable, (int numb=3) the comp uses some space in the memory to store it cout.width(3) // the next intiger should be printed in 3 positions - The problem with this is that it only works for one statement; you’d need to repeat it each time (if u put it in a loop, it’ll do it every time anyway, but it’s still tedious) cout.width(3); cout << numb1 << numb2; // only numb1 will get the alignment - Float and Double - When you define a variable in float or double, it gets stored in scientific notation ex. 56230 would be stored as 5.623*104 - So for this, you have to define how many decimal pts and then the alignment cout.setf(ios::fixed,ios::floatfield); Cout.precision(3) // 3 decimal places on floating or double numbers - These can be set in the beg of the program and will stay for the rest of the program, unless you change it later- so would probably be in towards beg of program and then later you can say cout.width(10); - Best idea would be to type it once at top of the program as a comment and then just copy and paste it as you need it - 10/15/07 - Input - for (numb=1000, numb<=2000, numb++) then you change the numbers from 100 to 200, and u can change it again to any number, but each time u change it, u have to change the program- the numbers, re-compile it, and recreate the object program--- requires human intervention we want to write a program that will change it for us - so instead of program generated data (done by programer) we want user generated data (by the user) sum=0; for (numb=first; numb<=last; numb++) sum+=numb; - so instead of numbers, it's now from 'first' to 'last' -- cin (vs. cout) cin >> first; cin >> last; - now the program is ineractive, the user can put in the numbers, so until a number is typed it, the program suspends activity cout << "enter starting number" << endl; cin >> first; cin >> last; cout << "enter last number" << endl; - 10/18/07 - Input - To set Width by using a function void printout (numb,wid) { cout.width (wid); cout << numb; return; } - so now you can print printout (numb,8); printout (xyz,4); - instead of saying 'print out all the prime numbers between 1 and 100' you can let the user see if the number's prime- write a function called 'prime' int prime (int numb) { for (i=2; i> count; for (i=1;i<=count; i++){ cout << "enter next number"; cin >> number; if (prime (number) ==1) cout << number << "is prime" << endl; else cout << number << "is composite" << endl; } return 0; } - most of the time, this method isn't practical, so we'll learn the other 2 next week - If you want to make a list of 500 numbers and then give the whole list to the computer, instead of manually typing in each number -- Input File- gets data from a file on disk - Output File means that when you finish, write the answer to a disk - To get the file: #include // how you used cin and cout # include // file stream - To use an input file- need to declare the file, open the file (can be done w one statement at the beg of the program), read the file, and close the file (oe statement at the end) - Declare and Open File ifstream infile; //infile is a made-up name, (i -input, fstream- file stream) infile.open ("ast5.dat"); // open file ast5.dat ifstream infile ("ast5.dat"); // or this way- both statements combined -- goes as beg of program - To Read the File infile >> x; - To Close the File infile.close () ; - Full Program: (again using 'prime' function) int main () { ifstream infile ("ast5.dat"); int number, count, i; infile >> count; for (i=1; i<=count; i++){ infile >> number; if (prime (number) == 1) cout << number << " is prime"; else cout << number << " is composite"; } infile.close () ; return 0; } - 10/22/07 - Nested Loops- you can also have more than one loop within a program, but instead of making the comp get the numbers several times, u should use nested loops-- going through numbers once and then doing all the computations - Trucking company sends a certain amount of trucks w certain amount of cartons and they each weigh a certain amount- to determine how many cartons it can handle-- so first number is 5 (number of trucks), then is the number of cartons- header (3), then is the weight (and will b 3 dif numbers), and you need five lines like this b/c it's 5 trucks -- we want to print out a report w truck number, number of cartons, total weight, overweight (any truck w more than 500 lbs)-- ex. truck 1, 3 cartons, total is 350 lbs and no overweight so will be blank (if overweight, put a star) -- we have to write a program that even if u change the data, will get the righ answers cin >> ntrucks; // will read the first number for (tr=1; tr<=ntrucks; tr++) { // will go around as many times as there are trucks ( now it's 5) // process next truck cin >> ncartons; // will read the next number as number of cartons for (ctn=1; ctn<=ncartons; ctn++) { // process next carton cin >> weight; twt=twt+weight; } cout << tr << ncartons << twt << endl; if (twt >=500) cout << "*" << endl; else cout << endl; } - there are 3 dif types of numbers here- numb of trucks, numb of cartons, and weight - Compound Interest- as you make more money, get more intereste - princ= 1000, rate is 10%, and you want to leave it there for 5 yrs - we want to write a function that will find total- accepts principle, numb of yrs, and rate; return- final amount, header would be double TotInt (double princ ,double rate, int yrs) double TotInt (double princ ,double rate, int yrs){ double amount= princ, interest; int yr; for (yr=1; yr<=yrs; yr++) { interest= amt * rate; amt+=interest; } return amt; } - formula for compund interest is P (1+r) n - compounding semi-annually, would call it 'start, interest, final' so interest for 1000 dollars for a yr would b 100, so 6 months would b 50, so end of 6 mo is 1050, 1 year is 1102.50 -- vs. just each yr would b 1100 -- so formula is now P(1+r/f)n*f so header for compound interest would be double compound (double princ,double rate, int yrs) double compound (double princ,double rate, int yrs, int freq) // new part is frequency- how often u compound for (yr=1; yr<=years*freq; yr++) { interest= amt*rate/freq } - 10/25/07 - Arrays- stores homogeneous data all together, ex. all numbers-- characters etc would be kept in other things- Classes or Structures - Summary Statistics - We've looked at Sum, Count, and Average already-- you can also look at variants, mode, statistical deviation etc. - Minimum and Maximum are also impt- smallest and largest numbers, and then you can find the range too- (maximum -minimum) let x= largest of a and b if (a>b) x=a; else x=b; - the problem comes up when there's more than 2 numbers because that has too many options (ex. 3 numbers has 6 possibilities) a=3, b=15,c=8 we want x to equal the largest if (a>b) x=a; else x=b; // now we know x will be the larger of a and b, but we still have c if (c>x) // now we can check if c is greater than a and b x=c; - if we have a,b,c,d if (a>b) x=a; else x=b; if (c>x) x=c; if (d>x) x=d; - minimum would be the same, except instead of greater than, do less than - function for 2 numbers: int big2 (int a, int b){ if (a>b) return a; else return b; } - function for 3 numbers: int big3 (int a, int b, int c) { int x; x= big 2 (a,b) // you can just call the other function x= big 2 (c,x) return x; } // or you can return big2 (big 2 (a,b), c); - function for 4 numbers: int big4 (int a, int b, int c, int d) { x=big 3 (a, b, c); x=big 2 (x,d); return x; - There is way to write a function for 'big' that will accept any number of parameters and will find the greatest of any numbers without telling it before (we won't learn that now) - I have a file of data and I don't know how many numbers are in it, find the largest in the file-- loop, input, with a count-- the first number in the file is the amount of numbers large = -9999; // it's hard to know what to initialize 'large' to, b/c even if u do this, the numbers might b smaller cin >> cnt; // manual user input for (i=1, i<=cnt; i ++) { // process next number cin >> number; if (number > large) large = number; } cout << "largest number is " << large << endl; - To find the smallest: small= 10000000 // very large number if (number < small) small = number; cout << "the smallest number is " << small << endl; - New Program: To say the largest number, but also where the number came from (position) large = -1; cin >> cnt; for (i=1; 1<= cnt; i++) if (number> large){ large= number; lgpso=i; } } cout << "largest number is " << large << " at position " << lgpos << endl; - Approximation- you know principle, years, and final investment-- you want to know what the rate is to get that amount-- we might not get the exact amount, but it'll b close - you're looking for a rate, most interest rates are between 0 and 1 (0% and 100%), so you start with .0001 and end with .9999, assume that rate will be directly in the middle (.50)- try that, final amount is too high, so now try .25 -- and it's still too big, so try mid again .125, if that's too small, then u'll take the number half way and it's in the upper half etc. double calcrate (double princ, int yrs, int freq, double finalamt) low=.0001; // better not to make it 0 cuz u might end up dividing by 0 and stuff like that high = .9999; // can't use a for loop because u dont know how many times u're gonna go around while (high-low > .0001) { // whatever level of accuracy you want- getting the numbers to b almost the same rate= (low+high)/2; // to find the number directly in mid amt = FinAmt (princ, rate, yrs, freq) // function to find total sum, assignment 5 if (amt > famt); // compare the answer we got with the final amt high = rate; // low stays the same, and high becomes the half way pt else low = rate; } return rate; } - 10/29/07 - Input Control - how many times you go around the loop - Count Controlled- you provide the count, first number in the file and then do the loop cin >> count; for (i=1;i<=2;i++) { cin >> value; // process value } - Trailer Data- keep sending the data, and at the end will be another piece of data which signals that i'm done 50 50 50 40 30 100 500 -1 // -1 is the signal that ure done, it's the trailer - Code: cin >> value; // for the first number, to enter the loop while (value!= -1) { // process value cin >> value; // to get the next number from the file } - End of File- the program will just run out or data and that's wen the program ends - Arrays - you can store as many numbers as you want in an integer, there are 5 dif boxes for a and they're divided by an index or subscript (a 0, a 1, a 2, a 3 etc.) -- the first number is 0 -- remember that, we reference elements of the array by the subscript -- int a [3]; // a will have 3 possible values stored as a 0, a 1, and a 2 cout << a[2]; a[2] = 14 // goes to box a 2 and makes it 14 cin >> a[1] // takes the value from input and puts it into a 1 box if you say a[4] =10; it's out of the bounds of the integer, will either get an error or will do nothing - Code, a single statement that uses i as index can use b[0] till the end int b[4]; for (i=0; i<4; i++) // MUST be less than, not less than or equal b/c u'll end up w out of bounds b[i]=5*i; - another code- int c [6] = {10,20,30,40,50,60}; // so c[0] = 10, c[1]= 20 etc. for (i=0; i<6; i++) c [i] = c[i] -2 *i; // c [1] = 20, - 2*1, so c[1] becomes 18 etc. (c[0] stays 10) - 2 * d(i-1) -- is whatever d[4] is (i=5) , 2*d[i] - 1, so it's d[5] value and -1 from that - you can create as many arrays as you want, for what purpose you want int a[5] = {10,20,30,40,50]; int b[5] = [1,2,3,4,5]; for (i=o; i <=3; i++) { b[i]= b[1] + a [i+1]; - 10 stores, purchases are made-- 3 100 , 2 50, 8 700, 5 20, 2 100 (store number price), you want a report of total sales by store (we have to number from 0-9 cuz we're using arrays) and we're going to add up all the sales by store, we'll only have 10 numbers at the end no matter how much info is put in -- unknown number of input lines, but will be 10 output lines, first you have to decide how you know wen ure done -- here we'll use -1 to mean the end (trailer data) double sales [10] = // makes 10 slots for data (0-9), one for each store // initialize sales to 0 for (st=0; st <=9; st++) sales [st] =0; cin >> st >> amt; // reads in to pieces of info while (st!=-1){ // process new transaction sales [st] = sales [st]+amt; // sales of the store number, plus amt (sum) cin >> st>> amt; // then you need to read in the next number } // this will update all the values of 'sales' // print for (st=0, st<=9; st++) cout << st << sales [st] << endl; - 11/1/07 - Arrays and Functions - you use arrays when you're gonna need them throughout the program, if you need it once, you dont need it - another way you might need an array would be if you want to print them all out backwards- when you will need to get to dif numbers - read in a set of numbers, store them in an array, call a function to find the sum and print the sum (u dont really need an array to get a sum, we're just gonna use it here), and we're going to use count method to tell it when to stop data is: 4, 8, 3, 7, 2 int main () { int numb[100], i, sum; cin >> count; for (i=0;i<5, i++){ // read data into array cin >> n; // or you can do cin>> numb[i]; numb[i]=n; } sum=SArray(numb,count) // you need to pass 2 variables, because you need to tell the function how many elements are in the array cout << "the sum of the elements is " << sum << endl; return 0; } // function (type, name, parameters) int SArray (int numb[ ], int count); // [ ] says we're using an array, but we dont put a number int sm=0; for (j=0; j> n; int i=0; while (n>=0) { numb [i] = n; i++; // or you can do numb[i++]=n cin >> n; // when it reads it -1, goes back to top, and then leaves loop } count =i; // you need to make a separate count for the function, could do it however - function to compute the average of elements of an array double avg (int a [] , int count) { double sum=0; for (i=0;i big) big= a [i]; return big; - 11/5/07 - Exam- write program to generate output and find the output of a written program - arrays, functions - look at assignment he gave us in the book - ex. write a function that will computer the sum of the array-- pass 2 things to a function - range- dif between largest and smallest - third method is end of file - you just reach the end of the file and then stop - go to the return - (we're not going to do this now) - a warehouse that receives goods and ships goods, so u want it to manipulate the right part of the element-- ex. he wants 50 units of item number 4 or add 100 to item number 3 - each transaction needs 3 pieces of info- if it's ship or receive (1 or 2), which item number (0-6), and how much (quantity) - one transaction might look like 1 4 100 (ship 100 units of item 4) int inv[7]; int trtype, item, qty; // first u need to read in trtype from the data infile >> trtype >> item >> qty; while (trtype!=-1){ // process next transaction if (trtype=2) // receipt inv [item] += qty; else if (qty > inv [item] ) // shipment- you have to deal w neg amounts, 3 options, here we dont want our inventory to go negative, so if u get order of more than u have, just disregard cout << "insufficient stock of item " << item << endl; else inv [item] -=qty; infile >> trtype >> item >> qty; } - a paper trail aka a log - it's messages that will say what the transaction did- ex. shipped 400 units of item 5 - put a cout in the if if (trtype=2){ inv [item] += qty; cout << "received " << qty << " units of item " << item << endl; } - to calculate how many transactions were made, use a count - ntrans=0 -- and every time u get into the while loop, do ntrans++ - avg quantity shipped, totalshipped and nship (initialize both to 0) and in the else of shipping, nship ++, and totalshipped+=qty; and then totalshipped/ nship -- keep in mind to watch out for zeros - you need a -1 for all 3 variables to be ur trailer because it is going to take in 3 pieces of data so need the first to be -1 for the trailer, and then just 2 random numbers for it to take in data - you can get around this by just reading in trtype at the end and then only if they're a 1 or 2, and then enter the while loop, then read in item and qty - Searching- you have an array and you want to know if it's there yet, and where it is - array a [10] and numbers in each column, u want to know if there's a 50 in the array - we need 3 pieces of data- the array, how many elements in the range, what are u looking for (for function 'search') int search (int a [], int nelts (how many elements u're using in the array), int val) for (i=0; i > a [i] // reads data into all the part of the array, we want to know if 1000 is in the array p= search (a, 100, 1000); // p will equal 1 or 0 and u also dont need to put brackets here if (p==1) // dont forget the double = cout << "1000 is present" << endl; else cout << "1000 is not present" << endl; - to know where it is: return i; ( in the function) and then outside the loop, cant put return 0 so that has to change too-- return -1 (or something that isnt a legal array element) and in main: if (p>=0) // it's not -1 (the other return) cout << "1000 is present in position " << p << endl; else << "1000 is not present" << endl;