CC Review and Basics A Basic C Program

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?

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 get. Name(); void set. Age(Person* f_person); void print(Person* f_people); //overloading void print(int oldest, int avg_age); //of print function //operator overloading possible as well void calc (Person* f_people, int* f_oldest, double* f_avg_age);
![Main int main() { Person* people = new Person[MAX_PEOPLE]; //new instead of malloc //Person Main int main() { Person* people = new Person[MAX_PEOPLE]; //new instead of malloc //Person](http://slidetodoc.com/presentation_image_h2/1d837d87076359d641c2c2e57a62c020/image-6.jpg)
Main int 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 = get. Name(); set. Age(&people[i]); } print(people); calc(people, &oldest, &avg_age); print(oldest, avg_age); delete[] people; //delete instead of free return EXIT_SUCCESS; }

get. Name, set. Age string get. Name() { string tmp_name; cout << "Enter name: "; cin >> tmp_name; return tmp_name; } void set. Age(Person* f_person) { cout << "Enter age: "; cin >> f_person->age; }

print void 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; i++; } } void print(int oldest, double avg_age) { cout << "The oldest person is: " << oldest << ". " << endl; cout << "The average is: " << avg_age << ". " << endl; }

calc void 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 }
- Slides: 9