last code

This commit is contained in:
left_adjoint 2024-03-11 16:03:49 -07:00
parent c23e31d3d4
commit c714f40f5c
5 changed files with 116 additions and 0 deletions

21
arrayRef.cpp Normal file
View File

@ -0,0 +1,21 @@
#include <iostream>
using namespace std;
// write a function that doubles the elements in an array of ints
void doubler(int arr[], int l){
for(int i=0; i<l; i++){
arr[i] = 2*arr[i];
}
}
int main(){
int myArr[5] = {0,1,2,3,4};
doubler(myArr,5);
for(int i = 0; i < 5; i++){
cout << myArr[i] << endl;
}
return 0;
}

13
arrayTheTruth.cpp Normal file
View File

@ -0,0 +1,13 @@
#include <iostream>
using namespace std;
int main(){
int myArr[5] = {0,1,2,3,4};
cout << myArr << endl;
cout << *(myArr + 0) << endl; // myArr[0]
cout << *(myArr + 1) << endl; // myArr[1]
cout << *(myArr + 2) << endl; // myArr[2]
return 0;
}

22
byRef.cpp Normal file
View File

@ -0,0 +1,22 @@
#include <iostream>
using namespace std;
void howManyPets(string petType, int &numPets){
int temp =0;
cout << "How many " << petType << " do you have?" << endl;
cin >> temp;
// if we were doing error handling we'd put that here
numPets = numPets + temp;
}
int main(){
int totalPets = 0;
howManyPets("cats", totalPets);
howManyPets("dogs", totalPets);
howManyPets("chickens", totalPets);
cout << "you have " << totalPets << " pets" << endl;
return 0;
}

24
byVal.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <iostream>
using namespace std;
int howManyPets(string petType){
int temp =0;
cout << "How many " << petType << " do you have?" << endl;
cin >> temp;
// if we were doing error handling we'd put that here
return temp;
}
int main(){
int totalPets = 0;
// totalPets = totalPets + howManyPets("cats");
// totalPets = totalPets + howManyPets("dogs");
// totalPets = totalPets + howManyPets("chickens");
totalPets = howManyPets("cats") + howManyPets("dogs") + howManyPets("chickens");
cout << "you have " << totalPets << " pets" << endl;
return 0;
}

36
rectRef.cpp Normal file
View File

@ -0,0 +1,36 @@
#include <iostream>
using namespace std;
struct Rect {
int width;
int height;
int area;
};
Rect makeRect(int w, int h){
Rect rect;
rect.width = w;
rect.height = h;
rect.area = -1;
return rect;
}
int area(Rect &r){
if(r.area == -1){
cout << "Calculating area: " << endl;
r.area = r.width * r.height;
}
return r.area;
}
int main(){
Rect myRect = makeRect(10,20);
cout << myRect.width << endl;
cout << myRect.height << endl;
cout << "Area: " << area(myRect) << endl;
// assume a long time passes in the program
cout << "Area: " << area(myRect) << endl;
return 0;
}