C/C++ Review and Basics
-
Upload
brennan-jensen -
Category
Documents
-
view
21 -
download
1
description
Transcript of C/C++ Review and Basics
C/C++ Review and Basics
A Basic C++ Program#include <cstdlib>#include <iostream>#include <string>
using namespace std;
int main() { string first, last; cout << "Please enter your name: "; cin >> first >> last; cout << "Hello, " << first << " " << last << "!" << endl; int age; cout << "How old are you? "; cin >> age; cout << "Great " << first << ", you are " << age << " years
old!" << endl; return EXIT_SUCCESS;}
A Basic C++ Program#include <cstdlib>#include <iostream>#include <string>
using namespace std;
int main() { string first, last; cout << "Please enter your name: "; cin >> first >> last; cout << "Hello, " << first << " " << last << "!" << endl; int age; cout << "How old are you? "; cin >> age; cout << "Great " << first << ", you are " << age << " years
old!" << endl; return EXIT_SUCCESS;}
Types and Characters
• Types– int– string– others?
• Characters– alternative to endl?
Types and Characters
• Types– int– string– others?
• Characters– alternative to endl?
Header#include <cstdlib>#include <iostream>#include <string>
using namespace std;
struct Person { string name; int age;}; //no typedef
const int MAX_PEOPLE = 10; //instead of #define
string getName();int getAge();void print(Person* f_people); //overloadingvoid print(int oldest, int avg_age); //of print function//operator overloading possible as wellvoid calc (Person* f_people, int* f_oldest, double* f_avg_age);
Mainint main() {
Person* people = new Person[MAX_PEOPLE]; //new instead of malloc //Person people[MAX_PEOPLE]; -- alternative array declaration int oldest = 0; double avg_age = 0;
for(int i = 0; i < MAX_PEOPLE; i++) { people[i].name = getName(); setAge(&people[i]); } print(people); calc(people, &oldest, &avg_age); print(oldest, avg_age); delete[] people; //delete instead of free return EXIT_SUCCESS;}
getName, setAge
string getName() { string tmp_name; cout << "Enter name: "; cin >> tmp_name; return tmp_name;}
void setAge(Person* f_person) { cout << "Enter age: "; cin >> f_person->age;}
printvoid print(Person* f_people) { int i = 0; while(i < MAX_PEOPLE) { cout << "Name of person number (" << (i+1) << "): " <<
f_people[i].name << endl; cout << "Age of person number (" << (i+1) << "): " << f_people[i].age
<< endl << endl; i++; }}
void print(int oldest, double avg_age) { cout << "The oldest person is: " << oldest << "." << endl; cout << "The average age is: " << avg_age << "." << endl;}
calcvoid calc (Person* f_people, int* f_oldest, double* f_avg_age) { double avg_total = 0; for(int i = 0; i < MAX_PEOPLE; i++) {
if(i == 0 || f_people[i].age > *f_oldest) { *f_oldest = f_people[i].age; } avg_total += f_people[i].age; } *f_avg_age = avg_total/(double)MAX_PEOPLE; //cast }