SlideShare a Scribd company logo
//Lab Assignment #6, part 3: Time Conversion
//Program Name: lab6Part3
//Purpose of the program: converts time from military format to
civilian format
//Authors: Wei Zhou and Shouwen Wang
//Date: 02/19/2016
#include<iostream>
#include <string>
using namespace std;
// get input time
int enterTime(int totalTime, int& hrVal, int& minVal)
{
cout << "please enter a military time(a value between 0000 and
2359) : ";
cin >> totalTime;
while (totalTime > 2359 || totalTime < 0) {
cout << "Error: you entered an invalid time. Try again." <<
endl;
cout << "please enter a military time(a value between 0000 and
2359) : ";
cin >> totalTime;
}
return totalTime;
}
//perform conversion
int ConvHrMin(int totalTime, int& hrVal, int& minVal) {
if (totalTime <= 1200) {
hrVal = totalTime / 100;
minVal = totalTime % 100;
}
else {
hrVal = totalTime / 100 - 12;
minVal = totalTime % 100;
}
return hrVal, minVal;
}
//display results
void finalOutput(){
int totalTime = 0;
int hrVal;
int minVal;
string morning;
string noon;
morning = "AM";
noon = "PM";
totalTime = enterTime(totalTime, hrVal, minVal);
hrVal = ConvHrMin(totalTime, hrVal, minVal);
minVal = ConvHrMin(totalTime, hrVal, minVal);
if (totalTime <= 1200) {
cout << "Time in civilian format£º " << hrVal << ':' << minVal
<< " " << morning << endl;
}
else {
cout << "Time in civilian format£º " << hrVal << ':' << minVal
<< " " << noon << endl;
}
}
int main()
{
cout << "Time Converter" << endl;
cout << "--------------" << endl;
finalOutput();
cout << endl;
return 0;
}
//Lab Assignment #7: Vectors
//Program Name: lab7part1
//Purpose of the program: working with vectors
//Authors: Wei Zhou
//Date: 03/03/2016
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
using namespace std;
//enter the number of boxes sold for each type of cookie
void numberSell(vector<string> cookienames, vector<int>
&amount) {
int numberSales;
for (int i = 0; i < cookienames.size(); ++i)
{
cout << "Please enter the total sales for " << cookienames[i] <<
": ";
cin >> numberSales;
while (numberSales < 0) {
cout << "Error: total sales cannot be a negative number." <<
endl;
cout << "Please enter the total sales for " << cookienames[i] <<
": ";
cin >> numberSales;
}
amount.push_back(numberSales);
}
cout << endl;
}
//calculate total sales
int totalSales(vector<int> amount) {
int total = 0;
for (int i = 0; i < amount.size(); ++i)
{
total += amount[i];
}
return total;
}
//find the lowest selling cookie
string findBest(vector<string> cookienames, vector<int>
amount) {
int highest = amount[0], exponent = 0;
for (int i = 1; i<amount.size(); ++i)
{
if (amount[i] >= highest)
{
highest = amount[i];
exponent = i;
}
}
return cookienames[exponent];
}
//find the highest selling cookie
string findWorst(vector<string> cookienames, vector<int>
amount) {
int lowest = amount[0], exponent = 0;
for (int i = 1; i<amount.size(); ++i)
{
if (amount[i] <= lowest)
{
lowest = amount[i];
exponent = i;
}
}
return cookienames[exponent];
}
//calculate percentages of sales
vector<double> findPercentage(vector<int> amount, int total) {
double percentage;
vector<double> line;
for (int i = 0; i < amount.size(); ++i)
{
percentage = amount[i] * 100 / total;
line.push_back(percentage);
}
return line;
}
//display report
void finalResult(vector<string> cookienames, vector<int>
amount, int total, vector<double> percentage, string best, string
worst) {
cout << left << setw(30) << "Type of Cookie" << setw(25) <<
"Boxes Sold" << "Percentage" << endl;
cout << "---------------------------------------------------------------"
<< endl;
for (int i = 0; i < cookienames.size(); ++i)
{
cout << fixed << setprecision(2);
cout << left << setw(30) << cookienames[i] << setw(25) <<
amount[i] << setw(9) << percentage[i] << "%" << endl;
}
cout << endl;
cout << "Total number of boxes sold this month: " << total <<
endl;
cout << left << setw(45) << "Best seller cookie: " << best <<
endl;
cout << left << setw(45) << "Worst seller cookie: " << worst <<
endl;
cout << endl;
}
int main()
{
cout << "Cookie sales tracking program" << endl;
cout << "-------------------------------" << endl;
//declare and initialize vectors as needed
vector<string> cookienames = { "Thin Mints", "Tagalongs",
"Shortbread", "Lemonades", "Caramel deLites", "Do-si-dos",
"Thanks-A-Lot",
"Rah-Rah Raisins", "Toffee-tastic", "Cranberry Citrus Crisps",
"Trios", "Savannah Smiles" };
void numberSell(vector<string> cookienames, vector<int>&
amount);
int totalSales(vector<int> amount);
string findBest(vector<string> cookienames, vector<int>
amount);
string findWorst(vector<string> cookienames, vector<int>
amount);
vector<double> findPercentage(vector<int> amount, int total);
void finalResult(vector<string> cookienames, vector<int>
amount, int total, vector<double> percentage, string best, string
worst);
vector<int> amount;
int total;
string best, worst;
vector<double> percentage;
numberSell(cookienames, amount);
total = totalSales(amount);
worst = findWorst(cookienames, amount);
best = findBest(cookienames, amount);
percentage = findPercentage(amount, total);
finalResult(cookienames, amount, total, percentage, best,
worst);
Chapter 8
Strings
Random Numbers
Enumerated Types
The string Type
The string data type
To hold text data, such as a person's name or e-mail address,
C++ uses the string type.
The string type is kept in its own library:
#include <string>
A string variable is created just like any other variable:
string variableName;
A string variable may be initialized upon declaration in the
usual fashion.
Input and output of strings is just like any other variable type.
Examples
Declaring and initializing a string variable:
string today = "Tuesday"; // initialization
string tomorrow; //an empty string ""
Input and Output:
cout << "I think today is " << today << endl;
cout << "What day do you think it is tomorrow? ";
cin >> tomorrow;
cout << "OK, so tomorrow is " << tomorrow << endl;
Reading text with multiple words
To read in text that contains spaces we use the getline():
getline (InputSource, destinationVariable);
getline() command will read in all information until it
encounters an end of line.
Note that using getline() after using >> can cause problems.
We can fix these problems using the method cin.ignore().
Example
cout << "Please enter your age: ";
int age;
cin >> age;
cout << "Please enter your full name: ";
cin.ignore();
string fullName;
getline (cin, fullName);
cout << "Thank you, " << fullName << ". ";
cout << "Your are " << age << “ years old.";
Assignment and concatenation
The = sign is used for assignment, just as with other variables.
That is, the value of the expression on the right of the = is
assigned to the variable on the left.
The + operator concatenates two strings
That is, it appends one string to the end of another.
Example
string day = "Tuesday";
cout << "Today is " << day << "." << endl;
string date = "March 8";
cout << "Today is " << date << "." << endl;
date = day + ", " + date;
cout << "Today is " << date << "." << endl;
The segment of code about will output:
Today is Tuesday.
Today is March 8.
Today is Tuesday, March 8.
The index system
A string is a collection of characters.
Each character inside a string has an index indicating its
location inside the string.
The first character in the string has index zero. The last
character has an index one less than the size of the string.
The subscript operator
In order to access a character inside a string we can use the
subscript operator [] and a valid index value.
Example:
string course = "CS 143";
char firstLetter = course[0]; //C
char lastChar = course[5]; // 3
Comparing Strings
The relational operators can be used to compare strings.
Example:
string name1 = "Mary";
string name2 = "Mark";
if ( name1 == name2 )
cout << "The names are the same" ;
else if ( name1 < name2 )
cout << "In alphabetical order: "
<< name1 << " " << name2 ;
else
cout << "In alphabetical order: "
<< name2 << " " << name1 ;
11
How does string comparison work?
In memory characters are stored using numeric codes.
The most commonly used code is ASCII: http://asciiset.com/
Each letter (a-z, A-Z), digit (0-9), and other characters have a
code associated with them:
‘A’ – ‘Z’: codes 65 – 90
‘a’ – ‘z’: codes 97 – 122
‘0’ – ‘9’ : codes 48 – 57
When the relational operators compare two strings:
They compare the strings character-by-character
They actually compare the codes for the characters
12
Example
If one of the strings in a comparison is shorter than the other
one, only the corresponding characters are compared.
If the corresponding characters are identical, the shorter string
is consider less than the longer string
Mary > Mark because: y > k
or in other words: 121 > 107
121
107
114
97
77
114
97
77
ASCII Codes
String Methods
The string type comes with a collection of very useful methods.
Remember that in order to invoke a method your must use the
dot notation.
Some methods return values and some don’t
Some methods have parameters and some don’t
returnValue = stringObject.methodName(arguments);
length() and size()
Both of these methods return the number of characters in the
string.
The count will include blank space and special characters if the
string contains these.
The type of the returned value is int.
Example
string course = "CS 143";
cout << "The string " << course << " has "
<< course.size()
<< " characters (including blanks). " ;
cout << "That means " << course.length() - 1
<< " letters.";
The at() method
Another way to access the characters in a string is the at(index)
method.
This method takes as its input a valid index value
This method returns the character (char) at the given index
value.
Example:
string course = "CS 143";
char firstLetter = course.at(0); //C
char lastChar = course.at(course.size() -1); // 3
The clear() and empty() methods
The clear() method removes all the elements in a string (and
resets its size to zero).
The empty() method returns true if the string is empty, false
otherwise.
Example:
string course = "CS 143";
course.clear(); //now course is an empty string ""
if ( course.empty() )
cout << "There are 0 characters in the string";
push_back()and append() methods
push_back(newChar): appends the char newChar to the end of
the string.
append(secondStr): appends a copy of the string secondString.
Example:
string course = "CS 143";
course.append(" C++"); //course is now: CS 143 C++
course.push_back('!'); //course is now: CS 143 C++!
The replace() method
replace(index, num, subString) replaces num characters starting
at index with a copy of the string subString.
Example:
string course = "CS 143";
course.replace(3, 3, "171"); //course is now: CS 171
erase(), insert()and resize() methods
erase(index, n) deletes n characters of the string, starting at
index.
insert(index, subStr) inserts the string subStr starting at index.
resize(newSize) resizes the string to have newSize characters.
If decrease, drops extra characters.
If increase, sets new characters to null ('0', ASCII value 0).
Example:
string course = "CS 143";
course.erase(2, 1); //course is now: CS143
course.insert(2, "---"); //course is now: CS---143
course.resize(2); //course is now: CS
Searching a string
You can use the find() method to search for a substring in a
string.
There are two ways you can use the find() method:
find(item)
find(item, startPoint)
Item: the substring we are looking for
startPoint: an index where to start the search
This method returns the index of the first occurrence if item in
the string (if found). Otherwise it returns -1
Searching a string
The rfind() method works similar to find() except that it starts
the search from the end/back of the string and searches
backwards through the string to the beginning/front.
rfind stands for reverse find.
Example: find()
string course = "CS 143";
int location, secondS;
location = course.find("143"); //location = 3
location = course.find("171"); //location = -1
location = course.find("S"); //location = 1
secondS = course.find("S",location + 1); //secondS = -1
Example: rfind()
string course = "CS 143";
int location, secondS;
location = course.rfind("143"); //location = 3
location = course.rfind("171"); //location = -1
location = course.rfind("S"); //location = 1
secondS = course.rfind("S",location - 1);//secondS = -1
Obtaining substrings
The subsrt() method allows you to obtain a substring from a
string.
subsrt(index, howMany);
Index: the index of the first character to obtain
howMany: how many characters to obtain
This method returns a string.
Example
string course = "CS 143";
int blankPos;
blankPos = course.find(" "); // blankPos = 2
string subject, number;
subject = course.substr(0, blankPos); //get 2 chars
int qty = course.size() – blankPos - 1; //qty = 3
number = course.substr(blankPos + 1, qty); //get 3 chars
Character operations
The ctype library provides access to several functions for
working with characters
To access the functions you must use the directive:
#include <ctype>
FunctionDescriptionExampleisalpha(character)Returns true if
character is a letter (a-z or A-Z)isalpha('A') // true
isalpha('7') // falseisdigit(character)Returns true if character is a
digit (0-9)isdigit('A') // false
isdigit('7’) // trueisspace(character)Returns true if character is a
whitespaceisspace(' ') // true
isspace('n') // true
isspace('x') // falsetoupper(character)Returns a uppercase
version of the charactertoupper('a') //
Atolower(character)Returns a lowercase version of the
charactertolower('A') // a
Random Numbers
Random Numbers
Random number: an unpredictable number
-random numbers but close
enough
To generate random numbers we need functions and features
from the cstdlib header file
The rand() function:
Returns a random number between 0 and RAND_MAX
RAND_MAX is an integer constant defined in cstdlib
RAND_MAX = 32767
Random Numbers
In order to generate a random number within a given range
[upper, lower] we will use this formula:
int n = (upper–lower+1)*(rand()/(RAND_MAX+1.0))+lower;
Example: Generate random numbers between 1 and 6 (to
simulate rolling a die for example)
int n = (6 – 1 + 1) * ( rand()/(RAND_MAX+1.0) ) + 1;
int n = ( 6 ) * ( rand()/(RAND_MAX+1.0) ) + 1;
int n = 6 * [0, 0.999] + 1 ;
Note: for the example we are testing the edge cases
More Examples
[10, 20]
int n = (11) * (rand() / (RAND_MAX + 1.0)) + 10 ;
int n = 11 * [0, 0.999] + 10 ;
[-10, 15]
int n = (15–(-10)+1)*(rand()/(RAND_MAX+1.0))+(-10);
int n = 26 * [0, 0.999] - 10 ;
int n = 26 * 0 – -10
int n = 26 * (0.999) – –
Reproducible/Irreproducible Sequences
rand() uses an internal formula to produce random numbers
That formula has a value, called the seed, which is used to
produce the first random number.
The next random number is generated based on the first random
number.
The next random number is generated based on the previous
random number.
Consequence: for a given seed, the sequence of random
numbers is always the same.
Changing the seed
The srand(int) function allows us to change the value of the
seed.
But the value of the seed should be changed each time we run
the program.
We will use the help of the time() function from the ctime
library:
time(0) returns the number of seconds that have passed since
January 1, 1970 0:0:0 GMT and the machine’s current time.
int seed = static cast<int>( time(0) ) ;
srand(seed)
Example
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
int main ()
{
int seed = static_cast<int>( time( 0 ));
srand( seed );
cout << "Here is a sequence of 5 random numbers: ";
for (int i = 1; i <= 5 ; i++)
cout << rand() << " " ;
return 0;
}
Enumerated Types
Enumerated types
The enum command allows us to create simple new data types
Types created with enum have a limited set of values (or
names).
These values are really nothing more than const ints, so it's
common practice to write them all in caps.
Once the new type is created, it behaves (more or less) like any
other type.
You create variables of that type and assign it values from the
list.
Declaring Enumerated Types
The generic format of enum is:
enum TypeName {value1, value2, value3, ... };
Examples:
enum Direction {NORTH, SOUTH, EAST, WEST};
enum Color {RED, BLUE, YELLOW, BLACK, WHITE};
enum Season {FALL, WINTER, SPRING, SUMMER};
Note that each value is an identifier, not a string.
By convention an enumerated type is named with the first letter
of each word capitalized and a value of an enumerated type is
named like a constant with all uppercase letters.
Declaring variables
Once a type is defined, you can declare a variable of that type:
Season current;
The variable forward can hold one of the values defined in the
enumerated type.
current = WINTER;
As with any other type, you can declare and initialize a variable
in one statement:
Season current = WINTER;
Enumerated values
Enumerated values are stored as integers in memory.
By default the values correspond to 0, 1, 2….., in order of their
appearance in the list.
Example:
enum Season {FALL, WINTER, SPRING, SUMMER};
FALL corresponds to the integer value 0, WINTER to 1,
SPRING to 2, and SUMMER to 3.
Enumerated values
You can explicitly assign an enumerated value with any integer
value.
Example:
enum Season {FALL = 20, WINTER = 30,
SPRING = 40, SUMMER = 50};
If you assign integer values for some values in the enumerated
type declaration, the other values will receive default values.
Example:
enum Season {FALL, WINTER, SPRING = 40, SUMMER};
FALL corresponds to the integer value 0, WINTER to 1,
SPRING to 40, and SUMMER to 41.
Manipulating enumerated types
One popular way of manipulating a variable of an enumerated
type is with the switch statement.
Example:
switch (current)
{
case FALL:
//process FALL
break;
case WINTER:
//process WINTER
break;
…etc…
}
What the new type can do
Simple Assignment
Season current = WINTER ;
current = SPRING ;
Season next = current ;
Simple Comparison (== and !=)
if (forward == sunrise)
cout << "You watch an inspiring sunrise." << endl;
What the new type can do, cont.
Used in functions as parameters and return values.
Season next_season (season current)
{
switch (current)
{
case FALL:
return WINTER;
case WINTER:
return SPRING;
case SPRING:
return SUMMER;
case SUMMER:
return FALL;
}
}
What the new type cannot do
Other math operators do not make sense:
Season current = WINTER;
current = current * 10 ;
Comparison based on inequality (<, <=, >. >=) works, but is
often meaningless:
Season next = SPRING ;
if (current >= next )
Produce meaningful output using <<:
cout << "This is the " << current << " season";
//This line produces output such as "This is the 0 season"
Helper functions
One way to work around the issue with output operator is to use
a helper function
string season_name (Season s)
{
switch (s)
{
case FALL:
return "Fall";
case WINTER:
return "Winter";
case SPRING:
return "Spring";
case SUMMER:
return "Summer";
}
}
cout << "This is the " << season_name(current) << " season";
CS 143 Final Exam
Date:Tuesday March 15, 2016
Time:3:30 PM – 5:30 PM
Room:Disque 103
Bring:
your Drexel student ID
If you do not bring your Drexel ID I will not accept your exam.
Pen/pencil/eraser
Study guide available in Learn
Problets available to study for the final
Assignments for this week
Lab 9 is due at the end of the lab session or by Friday 11:59 PM
at the latest.
Hard deadline: you and your partner will not be able to submit
after the deadline.
Lab must be submitted via Bb Learn. Submissions via email will
not be accepted or graded
Submit the source code as a cpp file. No other formats will be
graded.
CodeLab assignment # 9:
Due on Tuesday, March 15 by 11:59 PM
Submit your proof of completion via Bb Learn
Hard deadline: your answers will not be recorded after the
deadline.
zyBook Chapter 7: Participation and Challenge Activities
Due on Monday March 15 by 11:59 PM
Hard deadline: late submissions will not be graded
CS 143 Laboratory Exercise 9
Purpose:
The purpose of this lab is to gain practical experience with
strings, random number, and
enumerated types.
Contents:
I. Startup
II. Course Evaluation
III. String and Character manipulation
IV. Random Numbers and enumerated types
I. Startup:
You will work with your lab partner to find the solutions to the
proposed problems. At the
end of the lab session your group should submit the code your
write today via Drexel Learn.
Only one submission per group is required. Make sure you and
your partner agree on who
will be responsible for submitting your lab assignment for this
week.
Note: It is important that both partners participate in the
programming process for
the entire assignment. One student shouldn't hog the machine,
or bully the others into
doing things a certain way. Try to act professional when
working with your partners - treat
them with the respect of knowledgeable co-workers on a job.
II. Course Evaluation:
Please take a few minutes to complete the College of Computing
and Informatics course
evaluation form. The form is available at:
https://cci.drexel.goaefis.net/index.cfm
Each student must complete the course evaluation form before
starting the lab exercise.
NOTE: The completion of the course evaluation form is part of
you grade for this lab, so
please make sure you show the lab instructor that you completed
the evaluation form. We
will make a list of the students who complete the evaluation so
they can receive full
credit for the lab.
III. String and Character manipulation:
Start up a new project for today’s lab. If you are working on
one of the classroom
laptops, it’s recommended that you save your project in the
Desktop.
Add the following header comment at the top of the file:
//Lab Assignment #9, Characters and Strings manipulation
//Program Name:
//Purpose of the program:
//Authors: Your and your partner’s names
//Date: write today’s date
Write a program that will check a new password and make sure
it’s valid. The program
will start by asking the user to enter his/her full name (as one
string that is, the full name
must be store in one string variable), and then his/her login ID
(also a string variable).
Then the program as the user to enter a new password and
validates it. Here is the criteria
for valid passwords:
following four categories:
– Z).
– z).
– 9).
-alphabetic characters (for example: @ # $ % ^ & * - + =
|  { ] ? / etc.).
by the last name initial)
If the password entered by the user meets the all criteria the
program let’s the user know
that the password has been changed. If the password entered
does not meet at least one of
the criteria, the program issues an error message and ask the
user to try again (as many
time as needed unti lthe user provides a valid password).
You should consider writing functions to solve this problem,
othewise you may end up
with a very long main function.
Here is a typical sample run for the program:
IV. Random Numbers and enumerated types:
Remove the current cpp file from the project, following these
steps:
1) In the
Solution
Explorer, find the Source Files folder and then your cpp file.
2) Right-click on the name of your cpp file. You will see a
menu pop-up. Pick the
Remove option. You will see a confirmation window. Click on
the Remove button.
3) Now add a New Item, by right-clicking the Source File folder
and then Add New
Item
4) At Add New Item dialog box select C++ File (.cpp)). Give
this file a name and then
click on the Add button.
Your source code must include the following header comment at
the top of the file:
//Lab Assignment #9, Random Numbers and enumerated types
//Program Name:
//Purpose of the program:
//Authors: Your and your partner’s names
//Date: write today’s date
For this part of the lab we are going to implement a simple
guessing game that the user
can play against the computer. Start by creating an enumerated
type to represent fruits
(have at least 10 fruits of your choice listed). Generate a
random number between 0 and
9 – this number will be used to access a “random” fruit from the
list. This will be the
computer choice. The program will ask the user to guess the
name of the fruit the
computer has picked. The user then enters a guess. If the user
is right he/she wins.
Otherwise the computer wins. The user can play as many times
as he/she wants. Once
the user decides to quit the game, display the tally, that is, the
number of times the
computer won and the number of times the player won.
This program must be implemented using enumerated types.
You must write at least two
functions: One to handle the input of a fruit as an enumerated
type; and one to handle the
display of a fruit name. Here is a typical sample run for the
program:
Submitting your lab work
For today’s lab your group must submit the .cpp files for the
programs you wrote
today. Please make sure you upload and submit your files via
Drexel Learn by the
end of the lab session, or by Friday at 11:59 PM at the latest.
Submissions via email will
not be graded.
For the programs: Do not copy and paste you code in a Word
file (or any other type of
document). Only cpp files will be read and graded.

More Related Content

PPT
Chapter 3 Expressions and Inteactivity
PPTX
Library functions in c++
PPTX
3 (3)Arrays and Strings for 11,12,college.pptx
PDF
CBSE Question Paper Computer Science with C++ 2011
PPTX
Arrays & Strings.pptx
PDF
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
PPTX
CPP Homework Help
Chapter 3 Expressions and Inteactivity
Library functions in c++
3 (3)Arrays and Strings for 11,12,college.pptx
CBSE Question Paper Computer Science with C++ 2011
Arrays & Strings.pptx
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
CPP Homework Help

Similar to Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx (20)

PPT
Strings
PPT
02a fundamental c++ types, arithmetic
PPTX
Lecture 9_Classes.pptx
PDF
05 c++-strings
PDF
Acm aleppo cpc training ninth session
PPT
C++ Strings.ppt
PDF
c++ referesher 1.pdf
PPTX
Array and string in C++_093547 analysis.pptx
PDF
Chapter 3 - Characters and Strings - Student.pdf
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
PPTX
The string class
PPTX
Chapter1.pptx
PDF
C++ practical
PPT
Strings
PPT
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
PPTX
lec 2.pptx
PDF
Computer science-2010-cbse-question-paper
PDF
Strinng Classes in c++
PPTX
Cs1123 9 strings
PPT
Lecture#9 Arrays in c++
Strings
02a fundamental c++ types, arithmetic
Lecture 9_Classes.pptx
05 c++-strings
Acm aleppo cpc training ninth session
C++ Strings.ppt
c++ referesher 1.pdf
Array and string in C++_093547 analysis.pptx
Chapter 3 - Characters and Strings - Student.pdf
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
The string class
Chapter1.pptx
C++ practical
Strings
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
lec 2.pptx
Computer science-2010-cbse-question-paper
Strinng Classes in c++
Cs1123 9 strings
Lecture#9 Arrays in c++
Ad

More from smile790243 (20)

DOCX
PART B Please response to these two original posts below. Wh.docx
DOCX
Part C Developing Your Design SolutionThe Production Cycle.docx
DOCX
PART A You will create a media piece based around the theme of a.docx
DOCX
Part 4. Implications to Nursing Practice & Implication to Patien.docx
DOCX
PART AHepatitis C is a chronic liver infection that can be e.docx
DOCX
Part A post your answer to the following question1. How m.docx
DOCX
PART BPlease response to these two original posts below..docx
DOCX
Part A (50 Points)Various men and women throughout history .docx
DOCX
Part A1. K2. D3. N4. C5. A6. O7. F8. Q9. H10..docx
DOCX
Part A Develop an original age-appropriate activity for your .docx
DOCX
Part 3 Social Situations2. Identify multicultural challenges th.docx
DOCX
Part A (1000 words) Annotated Bibliography - Create an annota.docx
DOCX
Part 6 Disseminating Results Create a 5-minute, 5- to 6-sli.docx
DOCX
Part 3 Social Situations • Proposal paper which identifies multicul.docx
DOCX
Part 3 Social Situations 2. Identify multicultural challenges that .docx
DOCX
Part 2The client is a 32-year-old Hispanic American male who c.docx
DOCX
Part 2For this section of the template, focus on gathering deta.docx
DOCX
Part 2 Observation Summary and Analysis • Summary paper of observat.docx
DOCX
Part 2 Observation Summary and Analysis 1. Review and implement any.docx
DOCX
Part 2Data collectionfrom your change study initiative,.docx
PART B Please response to these two original posts below. Wh.docx
Part C Developing Your Design SolutionThe Production Cycle.docx
PART A You will create a media piece based around the theme of a.docx
Part 4. Implications to Nursing Practice & Implication to Patien.docx
PART AHepatitis C is a chronic liver infection that can be e.docx
Part A post your answer to the following question1. How m.docx
PART BPlease response to these two original posts below..docx
Part A (50 Points)Various men and women throughout history .docx
Part A1. K2. D3. N4. C5. A6. O7. F8. Q9. H10..docx
Part A Develop an original age-appropriate activity for your .docx
Part 3 Social Situations2. Identify multicultural challenges th.docx
Part A (1000 words) Annotated Bibliography - Create an annota.docx
Part 6 Disseminating Results Create a 5-minute, 5- to 6-sli.docx
Part 3 Social Situations • Proposal paper which identifies multicul.docx
Part 3 Social Situations 2. Identify multicultural challenges that .docx
Part 2The client is a 32-year-old Hispanic American male who c.docx
Part 2For this section of the template, focus on gathering deta.docx
Part 2 Observation Summary and Analysis • Summary paper of observat.docx
Part 2 Observation Summary and Analysis 1. Review and implement any.docx
Part 2Data collectionfrom your change study initiative,.docx
Ad

Recently uploaded (20)

PPTX
Institutional Correction lecture only . . .
PDF
Basic Mud Logging Guide for educational purpose
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
master seminar digital applications in india
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Insiders guide to clinical Medicine.pdf
Institutional Correction lecture only . . .
Basic Mud Logging Guide for educational purpose
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Classroom Observation Tools for Teachers
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
STATICS OF THE RIGID BODIES Hibbelers.pdf
master seminar digital applications in india
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Cell Structure & Organelles in detailed.
Abdominal Access Techniques with Prof. Dr. R K Mishra
Sports Quiz easy sports quiz sports quiz
human mycosis Human fungal infections are called human mycosis..pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Supply Chain Operations Speaking Notes -ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Anesthesia in Laparoscopic Surgery in India
Insiders guide to clinical Medicine.pdf

Lab Assignment #6, part 3 Time ConversionProgram Name lab.docx

  • 1. //Lab Assignment #6, part 3: Time Conversion //Program Name: lab6Part3 //Purpose of the program: converts time from military format to civilian format //Authors: Wei Zhou and Shouwen Wang //Date: 02/19/2016 #include<iostream> #include <string> using namespace std; // get input time int enterTime(int totalTime, int& hrVal, int& minVal) { cout << "please enter a military time(a value between 0000 and 2359) : "; cin >> totalTime;
  • 2. while (totalTime > 2359 || totalTime < 0) { cout << "Error: you entered an invalid time. Try again." << endl; cout << "please enter a military time(a value between 0000 and 2359) : "; cin >> totalTime; } return totalTime; } //perform conversion int ConvHrMin(int totalTime, int& hrVal, int& minVal) { if (totalTime <= 1200) { hrVal = totalTime / 100; minVal = totalTime % 100; } else {
  • 3. hrVal = totalTime / 100 - 12; minVal = totalTime % 100; } return hrVal, minVal; } //display results void finalOutput(){ int totalTime = 0; int hrVal; int minVal; string morning; string noon; morning = "AM";
  • 4. noon = "PM"; totalTime = enterTime(totalTime, hrVal, minVal); hrVal = ConvHrMin(totalTime, hrVal, minVal); minVal = ConvHrMin(totalTime, hrVal, minVal); if (totalTime <= 1200) { cout << "Time in civilian format£º " << hrVal << ':' << minVal << " " << morning << endl; } else { cout << "Time in civilian format£º " << hrVal << ':' << minVal << " " << noon << endl; } } int main() {
  • 5. cout << "Time Converter" << endl; cout << "--------------" << endl; finalOutput(); cout << endl; return 0; } //Lab Assignment #7: Vectors //Program Name: lab7part1 //Purpose of the program: working with vectors //Authors: Wei Zhou //Date: 03/03/2016 #include<iostream>
  • 6. #include<iomanip> #include<vector> #include<string> using namespace std; //enter the number of boxes sold for each type of cookie void numberSell(vector<string> cookienames, vector<int> &amount) { int numberSales; for (int i = 0; i < cookienames.size(); ++i) { cout << "Please enter the total sales for " << cookienames[i] << ": "; cin >> numberSales; while (numberSales < 0) {
  • 7. cout << "Error: total sales cannot be a negative number." << endl; cout << "Please enter the total sales for " << cookienames[i] << ": "; cin >> numberSales; } amount.push_back(numberSales); } cout << endl; } //calculate total sales int totalSales(vector<int> amount) { int total = 0; for (int i = 0; i < amount.size(); ++i) { total += amount[i]; }
  • 8. return total; } //find the lowest selling cookie string findBest(vector<string> cookienames, vector<int> amount) { int highest = amount[0], exponent = 0; for (int i = 1; i<amount.size(); ++i) { if (amount[i] >= highest) { highest = amount[i]; exponent = i; } } return cookienames[exponent]; } //find the highest selling cookie
  • 9. string findWorst(vector<string> cookienames, vector<int> amount) { int lowest = amount[0], exponent = 0; for (int i = 1; i<amount.size(); ++i) { if (amount[i] <= lowest) { lowest = amount[i]; exponent = i; } } return cookienames[exponent]; } //calculate percentages of sales vector<double> findPercentage(vector<int> amount, int total) { double percentage; vector<double> line;
  • 10. for (int i = 0; i < amount.size(); ++i) { percentage = amount[i] * 100 / total; line.push_back(percentage); } return line; } //display report void finalResult(vector<string> cookienames, vector<int> amount, int total, vector<double> percentage, string best, string worst) { cout << left << setw(30) << "Type of Cookie" << setw(25) << "Boxes Sold" << "Percentage" << endl; cout << "---------------------------------------------------------------" << endl; for (int i = 0; i < cookienames.size(); ++i) {
  • 11. cout << fixed << setprecision(2); cout << left << setw(30) << cookienames[i] << setw(25) << amount[i] << setw(9) << percentage[i] << "%" << endl; } cout << endl; cout << "Total number of boxes sold this month: " << total << endl; cout << left << setw(45) << "Best seller cookie: " << best << endl; cout << left << setw(45) << "Worst seller cookie: " << worst << endl; cout << endl; } int main() { cout << "Cookie sales tracking program" << endl; cout << "-------------------------------" << endl;
  • 12. //declare and initialize vectors as needed vector<string> cookienames = { "Thin Mints", "Tagalongs", "Shortbread", "Lemonades", "Caramel deLites", "Do-si-dos", "Thanks-A-Lot", "Rah-Rah Raisins", "Toffee-tastic", "Cranberry Citrus Crisps", "Trios", "Savannah Smiles" }; void numberSell(vector<string> cookienames, vector<int>& amount); int totalSales(vector<int> amount); string findBest(vector<string> cookienames, vector<int> amount); string findWorst(vector<string> cookienames, vector<int> amount); vector<double> findPercentage(vector<int> amount, int total);
  • 13. void finalResult(vector<string> cookienames, vector<int> amount, int total, vector<double> percentage, string best, string worst); vector<int> amount; int total; string best, worst; vector<double> percentage; numberSell(cookienames, amount); total = totalSales(amount); worst = findWorst(cookienames, amount); best = findBest(cookienames, amount); percentage = findPercentage(amount, total); finalResult(cookienames, amount, total, percentage, best, worst); Chapter 8 Strings Random Numbers
  • 14. Enumerated Types The string Type The string data type To hold text data, such as a person's name or e-mail address, C++ uses the string type. The string type is kept in its own library: #include <string> A string variable is created just like any other variable: string variableName; A string variable may be initialized upon declaration in the usual fashion. Input and output of strings is just like any other variable type. Examples Declaring and initializing a string variable: string today = "Tuesday"; // initialization string tomorrow; //an empty string "" Input and Output: cout << "I think today is " << today << endl; cout << "What day do you think it is tomorrow? ";
  • 15. cin >> tomorrow; cout << "OK, so tomorrow is " << tomorrow << endl; Reading text with multiple words To read in text that contains spaces we use the getline(): getline (InputSource, destinationVariable); getline() command will read in all information until it encounters an end of line. Note that using getline() after using >> can cause problems. We can fix these problems using the method cin.ignore(). Example cout << "Please enter your age: "; int age; cin >> age; cout << "Please enter your full name: "; cin.ignore(); string fullName; getline (cin, fullName); cout << "Thank you, " << fullName << ". "; cout << "Your are " << age << “ years old."; Assignment and concatenation The = sign is used for assignment, just as with other variables. That is, the value of the expression on the right of the = is assigned to the variable on the left.
  • 16. The + operator concatenates two strings That is, it appends one string to the end of another. Example string day = "Tuesday"; cout << "Today is " << day << "." << endl; string date = "March 8"; cout << "Today is " << date << "." << endl; date = day + ", " + date; cout << "Today is " << date << "." << endl; The segment of code about will output: Today is Tuesday. Today is March 8. Today is Tuesday, March 8. The index system A string is a collection of characters. Each character inside a string has an index indicating its location inside the string. The first character in the string has index zero. The last character has an index one less than the size of the string. The subscript operator In order to access a character inside a string we can use the
  • 17. subscript operator [] and a valid index value. Example: string course = "CS 143"; char firstLetter = course[0]; //C char lastChar = course[5]; // 3 Comparing Strings The relational operators can be used to compare strings. Example: string name1 = "Mary"; string name2 = "Mark"; if ( name1 == name2 ) cout << "The names are the same" ; else if ( name1 < name2 ) cout << "In alphabetical order: " << name1 << " " << name2 ; else cout << "In alphabetical order: " << name2 << " " << name1 ; 11 How does string comparison work? In memory characters are stored using numeric codes. The most commonly used code is ASCII: http://asciiset.com/ Each letter (a-z, A-Z), digit (0-9), and other characters have a code associated with them:
  • 18. ‘A’ – ‘Z’: codes 65 – 90 ‘a’ – ‘z’: codes 97 – 122 ‘0’ – ‘9’ : codes 48 – 57 When the relational operators compare two strings: They compare the strings character-by-character They actually compare the codes for the characters 12 Example If one of the strings in a comparison is shorter than the other one, only the corresponding characters are compared. If the corresponding characters are identical, the shorter string is consider less than the longer string Mary > Mark because: y > k or in other words: 121 > 107 121 107 114 97 77 114 97 77 ASCII Codes String Methods The string type comes with a collection of very useful methods.
  • 19. Remember that in order to invoke a method your must use the dot notation. Some methods return values and some don’t Some methods have parameters and some don’t returnValue = stringObject.methodName(arguments); length() and size() Both of these methods return the number of characters in the string. The count will include blank space and special characters if the string contains these. The type of the returned value is int. Example string course = "CS 143"; cout << "The string " << course << " has " << course.size() << " characters (including blanks). " ; cout << "That means " << course.length() - 1 << " letters."; The at() method Another way to access the characters in a string is the at(index) method. This method takes as its input a valid index value This method returns the character (char) at the given index value. Example: string course = "CS 143"; char firstLetter = course.at(0); //C char lastChar = course.at(course.size() -1); // 3
  • 20. The clear() and empty() methods The clear() method removes all the elements in a string (and resets its size to zero). The empty() method returns true if the string is empty, false otherwise. Example: string course = "CS 143"; course.clear(); //now course is an empty string "" if ( course.empty() ) cout << "There are 0 characters in the string"; push_back()and append() methods push_back(newChar): appends the char newChar to the end of the string. append(secondStr): appends a copy of the string secondString. Example: string course = "CS 143"; course.append(" C++"); //course is now: CS 143 C++ course.push_back('!'); //course is now: CS 143 C++! The replace() method replace(index, num, subString) replaces num characters starting at index with a copy of the string subString. Example: string course = "CS 143"; course.replace(3, 3, "171"); //course is now: CS 171
  • 21. erase(), insert()and resize() methods erase(index, n) deletes n characters of the string, starting at index. insert(index, subStr) inserts the string subStr starting at index. resize(newSize) resizes the string to have newSize characters. If decrease, drops extra characters. If increase, sets new characters to null ('0', ASCII value 0). Example: string course = "CS 143"; course.erase(2, 1); //course is now: CS143 course.insert(2, "---"); //course is now: CS---143 course.resize(2); //course is now: CS Searching a string You can use the find() method to search for a substring in a string. There are two ways you can use the find() method: find(item) find(item, startPoint) Item: the substring we are looking for startPoint: an index where to start the search This method returns the index of the first occurrence if item in the string (if found). Otherwise it returns -1 Searching a string The rfind() method works similar to find() except that it starts the search from the end/back of the string and searches backwards through the string to the beginning/front. rfind stands for reverse find.
  • 22. Example: find() string course = "CS 143"; int location, secondS; location = course.find("143"); //location = 3 location = course.find("171"); //location = -1 location = course.find("S"); //location = 1 secondS = course.find("S",location + 1); //secondS = -1 Example: rfind() string course = "CS 143"; int location, secondS; location = course.rfind("143"); //location = 3 location = course.rfind("171"); //location = -1 location = course.rfind("S"); //location = 1 secondS = course.rfind("S",location - 1);//secondS = -1 Obtaining substrings The subsrt() method allows you to obtain a substring from a string. subsrt(index, howMany); Index: the index of the first character to obtain howMany: how many characters to obtain This method returns a string.
  • 23. Example string course = "CS 143"; int blankPos; blankPos = course.find(" "); // blankPos = 2 string subject, number; subject = course.substr(0, blankPos); //get 2 chars int qty = course.size() – blankPos - 1; //qty = 3 number = course.substr(blankPos + 1, qty); //get 3 chars Character operations The ctype library provides access to several functions for working with characters To access the functions you must use the directive: #include <ctype> FunctionDescriptionExampleisalpha(character)Returns true if character is a letter (a-z or A-Z)isalpha('A') // true isalpha('7') // falseisdigit(character)Returns true if character is a digit (0-9)isdigit('A') // false isdigit('7’) // trueisspace(character)Returns true if character is a whitespaceisspace(' ') // true isspace('n') // true isspace('x') // falsetoupper(character)Returns a uppercase version of the charactertoupper('a') // Atolower(character)Returns a lowercase version of the charactertolower('A') // a Random Numbers
  • 24. Random Numbers Random number: an unpredictable number -random numbers but close enough To generate random numbers we need functions and features from the cstdlib header file The rand() function: Returns a random number between 0 and RAND_MAX RAND_MAX is an integer constant defined in cstdlib RAND_MAX = 32767 Random Numbers In order to generate a random number within a given range [upper, lower] we will use this formula: int n = (upper–lower+1)*(rand()/(RAND_MAX+1.0))+lower; Example: Generate random numbers between 1 and 6 (to simulate rolling a die for example) int n = (6 – 1 + 1) * ( rand()/(RAND_MAX+1.0) ) + 1; int n = ( 6 ) * ( rand()/(RAND_MAX+1.0) ) + 1; int n = 6 * [0, 0.999] + 1 ; Note: for the example we are testing the edge cases
  • 25. More Examples [10, 20] int n = (11) * (rand() / (RAND_MAX + 1.0)) + 10 ; int n = 11 * [0, 0.999] + 10 ; [-10, 15] int n = (15–(-10)+1)*(rand()/(RAND_MAX+1.0))+(-10); int n = 26 * [0, 0.999] - 10 ; int n = 26 * 0 – -10 int n = 26 * (0.999) – – Reproducible/Irreproducible Sequences rand() uses an internal formula to produce random numbers That formula has a value, called the seed, which is used to produce the first random number. The next random number is generated based on the first random number. The next random number is generated based on the previous random number. Consequence: for a given seed, the sequence of random numbers is always the same. Changing the seed The srand(int) function allows us to change the value of the seed. But the value of the seed should be changed each time we run the program. We will use the help of the time() function from the ctime
  • 26. library: time(0) returns the number of seconds that have passed since January 1, 1970 0:0:0 GMT and the machine’s current time. int seed = static cast<int>( time(0) ) ; srand(seed) Example #include <ctime> #include <cstdlib> #include <iostream> using namespace std; int main () { int seed = static_cast<int>( time( 0 )); srand( seed ); cout << "Here is a sequence of 5 random numbers: "; for (int i = 1; i <= 5 ; i++) cout << rand() << " " ; return 0; } Enumerated Types
  • 27. Enumerated types The enum command allows us to create simple new data types Types created with enum have a limited set of values (or names). These values are really nothing more than const ints, so it's common practice to write them all in caps. Once the new type is created, it behaves (more or less) like any other type. You create variables of that type and assign it values from the list. Declaring Enumerated Types The generic format of enum is: enum TypeName {value1, value2, value3, ... }; Examples: enum Direction {NORTH, SOUTH, EAST, WEST}; enum Color {RED, BLUE, YELLOW, BLACK, WHITE}; enum Season {FALL, WINTER, SPRING, SUMMER}; Note that each value is an identifier, not a string. By convention an enumerated type is named with the first letter of each word capitalized and a value of an enumerated type is named like a constant with all uppercase letters. Declaring variables Once a type is defined, you can declare a variable of that type: Season current; The variable forward can hold one of the values defined in the enumerated type. current = WINTER;
  • 28. As with any other type, you can declare and initialize a variable in one statement: Season current = WINTER; Enumerated values Enumerated values are stored as integers in memory. By default the values correspond to 0, 1, 2….., in order of their appearance in the list. Example: enum Season {FALL, WINTER, SPRING, SUMMER}; FALL corresponds to the integer value 0, WINTER to 1, SPRING to 2, and SUMMER to 3. Enumerated values You can explicitly assign an enumerated value with any integer value. Example: enum Season {FALL = 20, WINTER = 30, SPRING = 40, SUMMER = 50}; If you assign integer values for some values in the enumerated type declaration, the other values will receive default values. Example: enum Season {FALL, WINTER, SPRING = 40, SUMMER}; FALL corresponds to the integer value 0, WINTER to 1, SPRING to 40, and SUMMER to 41.
  • 29. Manipulating enumerated types One popular way of manipulating a variable of an enumerated type is with the switch statement. Example: switch (current) { case FALL: //process FALL break; case WINTER: //process WINTER break; …etc… } What the new type can do Simple Assignment Season current = WINTER ; current = SPRING ; Season next = current ; Simple Comparison (== and !=) if (forward == sunrise) cout << "You watch an inspiring sunrise." << endl; What the new type can do, cont.
  • 30. Used in functions as parameters and return values. Season next_season (season current) { switch (current) { case FALL: return WINTER; case WINTER: return SPRING; case SPRING: return SUMMER; case SUMMER: return FALL; } } What the new type cannot do Other math operators do not make sense: Season current = WINTER; current = current * 10 ; Comparison based on inequality (<, <=, >. >=) works, but is often meaningless: Season next = SPRING ; if (current >= next ) Produce meaningful output using <<: cout << "This is the " << current << " season"; //This line produces output such as "This is the 0 season"
  • 31. Helper functions One way to work around the issue with output operator is to use a helper function string season_name (Season s) { switch (s) { case FALL: return "Fall"; case WINTER: return "Winter"; case SPRING: return "Spring"; case SUMMER: return "Summer"; } } cout << "This is the " << season_name(current) << " season"; CS 143 Final Exam Date:Tuesday March 15, 2016 Time:3:30 PM – 5:30 PM Room:Disque 103 Bring: your Drexel student ID If you do not bring your Drexel ID I will not accept your exam. Pen/pencil/eraser Study guide available in Learn Problets available to study for the final
  • 32. Assignments for this week Lab 9 is due at the end of the lab session or by Friday 11:59 PM at the latest. Hard deadline: you and your partner will not be able to submit after the deadline. Lab must be submitted via Bb Learn. Submissions via email will not be accepted or graded Submit the source code as a cpp file. No other formats will be graded. CodeLab assignment # 9: Due on Tuesday, March 15 by 11:59 PM Submit your proof of completion via Bb Learn Hard deadline: your answers will not be recorded after the deadline. zyBook Chapter 7: Participation and Challenge Activities Due on Monday March 15 by 11:59 PM Hard deadline: late submissions will not be graded CS 143 Laboratory Exercise 9 Purpose: The purpose of this lab is to gain practical experience with strings, random number, and enumerated types. Contents:
  • 33. I. Startup II. Course Evaluation III. String and Character manipulation IV. Random Numbers and enumerated types I. Startup: You will work with your lab partner to find the solutions to the proposed problems. At the end of the lab session your group should submit the code your write today via Drexel Learn. Only one submission per group is required. Make sure you and your partner agree on who will be responsible for submitting your lab assignment for this week. Note: It is important that both partners participate in the programming process for the entire assignment. One student shouldn't hog the machine, or bully the others into doing things a certain way. Try to act professional when working with your partners - treat them with the respect of knowledgeable co-workers on a job. II. Course Evaluation: Please take a few minutes to complete the College of Computing and Informatics course evaluation form. The form is available at: https://cci.drexel.goaefis.net/index.cfm Each student must complete the course evaluation form before
  • 34. starting the lab exercise. NOTE: The completion of the course evaluation form is part of you grade for this lab, so please make sure you show the lab instructor that you completed the evaluation form. We will make a list of the students who complete the evaluation so they can receive full credit for the lab. III. String and Character manipulation: Start up a new project for today’s lab. If you are working on one of the classroom laptops, it’s recommended that you save your project in the Desktop. Add the following header comment at the top of the file: //Lab Assignment #9, Characters and Strings manipulation //Program Name: //Purpose of the program: //Authors: Your and your partner’s names //Date: write today’s date Write a program that will check a new password and make sure it’s valid. The program will start by asking the user to enter his/her full name (as one string that is, the full name must be store in one string variable), and then his/her login ID (also a string variable). Then the program as the user to enter a new password and
  • 35. validates it. Here is the criteria for valid passwords: following four categories: – Z). – z). – 9). -alphabetic characters (for example: @ # $ % ^ & * - + = | { ] ? / etc.). by the last name initial) If the password entered by the user meets the all criteria the program let’s the user know that the password has been changed. If the password entered does not meet at least one of the criteria, the program issues an error message and ask the user to try again (as many time as needed unti lthe user provides a valid password). You should consider writing functions to solve this problem, othewise you may end up
  • 36. with a very long main function. Here is a typical sample run for the program: IV. Random Numbers and enumerated types: Remove the current cpp file from the project, following these steps: 1) In the Solution Explorer, find the Source Files folder and then your cpp file. 2) Right-click on the name of your cpp file. You will see a menu pop-up. Pick the Remove option. You will see a confirmation window. Click on the Remove button. 3) Now add a New Item, by right-clicking the Source File folder and then Add New Item
  • 37. 4) At Add New Item dialog box select C++ File (.cpp)). Give this file a name and then click on the Add button. Your source code must include the following header comment at the top of the file: //Lab Assignment #9, Random Numbers and enumerated types //Program Name: //Purpose of the program: //Authors: Your and your partner’s names //Date: write today’s date For this part of the lab we are going to implement a simple guessing game that the user can play against the computer. Start by creating an enumerated type to represent fruits (have at least 10 fruits of your choice listed). Generate a random number between 0 and 9 – this number will be used to access a “random” fruit from the list. This will be the computer choice. The program will ask the user to guess the name of the fruit the
  • 38. computer has picked. The user then enters a guess. If the user is right he/she wins. Otherwise the computer wins. The user can play as many times as he/she wants. Once the user decides to quit the game, display the tally, that is, the number of times the computer won and the number of times the player won. This program must be implemented using enumerated types. You must write at least two functions: One to handle the input of a fruit as an enumerated type; and one to handle the display of a fruit name. Here is a typical sample run for the program: Submitting your lab work For today’s lab your group must submit the .cpp files for the programs you wrote today. Please make sure you upload and submit your files via
  • 39. Drexel Learn by the end of the lab session, or by Friday at 11:59 PM at the latest. Submissions via email will not be graded. For the programs: Do not copy and paste you code in a Word file (or any other type of document). Only cpp files will be read and graded.