CH.3 Programming: The cin Object

¡Supera tus tareas y exámenes ahora con Quizwiz!

Given a string variable word, write a string expression that parenthesizes the value of word. So, if word contains "sadly", the value of the expression would be the string "(sadly)"

"(" + word + ")"

Given a string variable address, write a string expression consisting of the string "http://" concatenated with the variable's string value. So, if the value of the variable were "www.turingscraft.com", the value of the expression would be "http://www.turingscraft.com".

"http://" + address

Write the necessary preprocessor directive to enable the use of functions like sqrt and sin.

#include <cmath>

Write a complete program that -DECLARES an INTEGER VARIABLE, -reads a VALUE from the keyboard into that variable, and -writes to STANDARD OUTPUT the VARIABLE'S VALUE, twice the VALUE, and the square of the VALUE, separated by spaces. -Besides the numbers, nothing else should be written to STANDARD OUTPUT except for spaces separating the values.

#include <cmath> #include <iostream> using namespace std; int main() { int variable; cin >> variable; cout << variable << " " << (2 * variable) << " " << pow(variable,2) << endl; }

Write the necessary preprocessor directive to enable the use of the rand function.

#include <cstdlib>

Write the necessary preprocessor directive to enable the use of the time function.

#include <ctime>

Write the necessary preprocessor directive to enable the use of the stream manipulators like setw and setprecision.

#include <iomanip>

Write a complete program that -DECLARES an INTEGER variable, -reads a VALUE from the keyboard into that VARIABLE, and -writes to STANDARD OUTPUT the square of the variable's value. Besides the number, nothing else should be written to standard output.

#include <iostream> #include <cmath> using namespace std; int main() { int variable; cin >> variable; cout << pow ( variable, 2); }

Write a program that plays a word game with the user. The program should ask the user to enter the following: His or her name The name of a city His or her age The name of a college A profession A type of animal A pet's name After the user has entered these items, the program should display the following story, inserting the user's input into the appropriate locations: There once was a person named href="asfunction:_root.doTutor,7,CPP">NAME who lived in CITY. At the age of AGE, href="asfunction:_root.doTutor,7,CPP">NAME went to college at COLLEGE. href="asfunction:_root.doTutor,7,CPP">NAME graduated and went to work as a PROFESSION. Then, href="asfunction:_root.doTutor,7,CPP">NAME adopted a(n) ANIMAL named PETNAME. They both lived happily ever after!

// Chapter 3, Programming Challenge 22: Word Game #include <iostream> #include <string> using namespace std; int main() { string name; // To hold a name string city; // To hold a city string age; // To hold an age string college; // To hold a college string profession; // To hold a profession string animal; // To hold a type of animal string petName; // To hold the name of a pet // Get the name of the player. cout << "Enter name: "; getline(cin, name); // Get the name of a city. cout << "Enter city: "; getline(cin, city); // Get the age of the player. cout << "Enter age: "; cin >> age; cin.ignore(); // Get the name of a college. cout << "Enter college: "; getline(cin, college); // Get the name of a profession. cout << "Enter profession: "; getline(cin, profession); // Get the name of a type of animal. cout << "Enter animal: "; getline(cin, animal); // Get the name of a pet. cout << "Enter pet name: "; getline(cin, petName); // Display the story. cout << "\n\nThere once was a person named "<< name << " who lived in " << city << ".\n" << "At the age of " << age << ", " << name << " went to college at " << college << ".\n" << name << " graduated and went to work" << " as a " << profession << ".\n" << "Then, " << name << " adopted a(n) " << animal << " named " << petName << ".\n" << "They both lived happily ever after!\n\n"; return 0; }

The cin Object

-Standard input object -Like cout, requires iostream file -Used to read input from keyboard -Information retrieved from cin with >> -Input is stored in one or more variables

3.4 Average Rainfall Write a program that calculates the average rainfall for three months. The program should ask the user to enter the name of each month, such as June or July, and the amount of rain (in inches) that fell each month. The program should display a message similar to the following: The average rainfall for June, July, and August is 6.72 inches.

#include <iostream> #include <iomanip> using namespace std; int main() { double rain1, rain2, rain3; char month1[15], month2[15], month3[15]; cout << "Enter month: "; cin >> month1; cout << "Enter rainfall for " << month1 << ": "; cin >> rain1; cout << "Enter month: "; cin >> month2; cout << "Enter rainfall for " << month2 << ": "; cin >> rain2; cout << "Enter month: "; cin >> month3; cout << "Enter rainfall for " << month3 << ": "; cin >> rain3; cout << "The average rainfall for " << month1 << ", " << month2 << ", and " << month3 << " is " << setprecision(2) << showpoint << fixed << (rain1+rain2+rain3)/3.0 << " inches." << endl; return 0; }

In mathematics, the Nth harmonic number is defined to be 1 + 1/2 + 1/3 + 1/4 + ... + 1/N. So, the first harmonic number is 1, the second is 1.5, the third is 1.83333... and so on. Write an expression whose value is the 8th harmonic number.

(1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + 1.0/5.0 + 1.0/6.0 + 1.0/7.0 + 1.0/8.0)

Write an EXPRESSION that computes the average of the values 12 and 40.

(12+40)/2

Write an EXPRESSION that computes the average oft he variables exam1 and exam2 (both DECLARED and ASSIGNED values).

(exam1+exam2)/2

Each of the walls of a room with square dimensions has been built with two pieces of sheetrock, a smaller one and a larger one. The length of all the smaller ones is the same and is stored in the variable small. Similarly, the length of all the larger ones is the same and is stored in the variable large. Write a single expression whose value is the total area of this room. DO NOT use the pow function.

(large + small) * (large + small)

Area=s^2

(note there is no exponentiation operator): Area = pow(x, 2);

The dimensions (width and length) of room1 have been read into two variables: width1 and length1. The dimensions of room2 have been read into two other variables: width2 and length2. Write a single expression whose value is the total area of the two rooms.

(width1*length1) + (width2*length2)

The cin Object Gathers Multiple Values in Program 3-2 ( example)

// This program asks the user to enter the length and width of // a rectangle. It calculates the rectangle's area and displays // the value on the screen. #include <iostream> using namespace std; int main () { int length, width, area; cout << "This program calculates the area of a "; cout << "rectangle, \n"; cout << "Enter the length and width of the rectangle "; cout << "separated by a space. \n"; cin >> length >> width; area = length * width; cout << "The area of the rectangle is " << area << endl; return 0; }

Algebraic expression area=lw

Area = l * w;

Displaying a Prompt

A prompt is a message that instructs the user to enter data. You should always use cout to display a prompt before each cin statement. cout << "How tall is the room? "; cin >> height;

Coercion rules

Char, short, unsigned short automatically promoted to int When operating on values of different data types, the lower one is promoted to the type of the higher one When using the = operator, the type of expression on the right will be converted to the type of variable on the left

Mathematical expressions in cout

area = 2 * PI * radius; cout << "border is:" << 2* (1+w);

Overflow and Underflow

Occurs when assigning a vlue that is too large or too

When you mix apples with oranges: type conversion

When an operator's operands are of different data types, C++ will automatically convert them to the same data type. This can affect the results of mathematical expressions.

The cin Object: a) Can be used to input... b) Multiple values from keyboard... c) Order is important:...

a)...more than one value: cin >> height >> width; b)...must be separated by spaces. c)... first value entered goes to first variable, etc.

type coercion

automatic conversion of an operand to another data type

Given an integer variable bridgePlayers, write an statement that increases the value of that variable by 4.

bridgePlayers += 4;

Write the declaration of a char array named smallWord suitable for storing 4-letter words such as "love", "hope" and "care".

char smallWord[5];

Write a statement that reads 5 successive integers into these variables that have already been declared: x1 x2x3x4 x5. Then write a statement that prints each out on its own line so that they form a right-justified column with a 5-digit width. If any of the integers are 5-digits in size, then they will start at the very beginning of their lines. For example: |54213 | 8713 | 23 | 147 | 15

cin >> x1 >> x2 >> x3 >> x4 >> x5; cout.setf (ios::right, ios::adjustfield); cout << setw(5) << x1 << "\n" << setw(5) << x2 << "\n" << setw(5) << x3 << "\n" << setw(5) << x4 << "\n" << setw(5) << x5 << "\n";

A variable c of type char has been declared. Write the necessary code to read in the next character from standard input and store it in c, regardless of whether is a whitespace character.

cin.get(c);

Assume that a,b and c are char variables have been declared. Write some code that reads in the first character of the next line into a, the first character of the line after that into b and the first character of the line after that into c. Assume that the lines of input are under 100 characters long.

cin.ignore(100, '\n') >> a; cin.ignore(100, '\n') >> b; cin.ignore(100, '\n') >> c;

Assume that c is a char variable has been declared. Write some code that reads in the first character of the next line into c. Assume that the lines of input are under 100 characters long.

cin.ignore(100, '\n') >> c;

Given an int variable datum that has already been declared, write a statement that reads an integer value from standard input into this variable.

cin>>datum;

Write a STATEMENT that reads a word from standard input into firstWord. Assume that firstWord, has already been declared as an char array large enough to hold a 50-letter word.

cin>>firstWord;

Assume that name has been declared suitably for storing names (like "Misha", "Emily" and "Sofia") Write some code that reads a value into name then prints the message "Greetings, NAME" where NAME is replaced the value that was read into name. For example, if your code read in "Rachel" it would print out "Greetings, Rachel".

cin>>name; cout<<"Greetings, "<<name;

ASSUME that name has been DECLARED suitably for storing names (like "Amy", "Fritz" and "Moustafa") Write some code that reads a value into name then prints the message "Greetings, NAME!!!" where NAME is replaced the value that was read into name. For example, if your code read in "Hassan" it would print out "Greetings, Hassan!!!".

cin>>name; cout<<"Greetins, "<<name<<"!!!";

Assume that name and age have been declared suitably for storing names (like "Abdullah", "Alexandra" and "Zoe") and ages respectively. Write some code that reads in a name and an age and then prints the message "The age of NAME is AGE," where NAME and AGE are replaced by the values read in for the variables name and age. For example, if your code read in "Rohit" and 70 then it would print out "The age of Rohit is 70.".

cin>>name>>age; cout<<"The age of "<<name<<" is "<<age<<".";

Write a STATEMENT that reads a floating point (real) value from standard input into temperature. Assume that temperature, has already been declared as an double variable.

cin>>temperature;

Write a STATEMENT that reads an integer value from standard input into val. Assume that val has already been declared as an int variable.

cin>>val;

Write an EXPRESSION that attempts to read an integer from standard input and store it in an int variable, x, that has already been declared.

cin>>x;

Write an expression that attempts to read a double value from standard input and store it in an double variable, x, that has already been declared.

cin>>x;

promotion

convert to a higher type

demotion

convert to a lower type

Write a statement using the decrement operator to decrease the value of count (an already declared integer variable) by 1.

count--;

Assume that x is a double variable that has been given a value. Write a statement that prints it out with exactly three digits to the right of the decimal point no matter what how big or miniscule its value is.

cout << fixed << setprecision(3) << x;

Assume that m is an int variable that has been given a value. Write a statement that prints it out in a print field of 10 positions.

cout << m << setw(10);

Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Write a statement that prints the value of price in the form "X dollars and Y cents". So, if the value of price was 4321, your code would print "43 dollars and 21 cents". If the value was 501 it would print "5 dollars and 1 cents". If the value was 99 your code would print "0 dollars and 99 cents".

cout << price/100 << " dollars and " << price%100 << " cents" << endl;

Assume that x is a double variable that has been initialized. Write a statement that prints it out, guaranteed to have a decimal point, but without forcing scientific (also known as exponential or e-notation).

cout << showpoint << x;

Given two integer variables distance and speed, write an expression that divides distance by speed using floating point arithmetic, i.e. a fractional result should be produced.

distance * 1.0 / speed

Assume that children is an integer variable containing the number of children in a community and that families is an integer variable containing the number of families in the same community. Write an expression whose value is the average number of children per family.

float (children) / float (families)

Three classes of school children are selling tickets to the school play. The number of tickets sold by these classes, and the number of children in each of the classes have been read into these variables:tickets1, tickets2, tickets3 and class1, class2, class3. Write an expression for the average number of tickets sold per school child.

float(tickets1 + tickets2 + tickets3) / ( class1 + class2 + class3)

In mathematics, the Nth harmonic number is defined to be 1 + 1/2 + 1/3 + 1/4 + ... + 1/N. So, the first harmonic number is 1, the second is 1.5, the third is 1.83333... and so on. Assume that n is an integer variable whose value is some positive integer N. Assume also that hn is a double variable whose value is the Nth harmonic number. Write an expression whose value is the (N+1)th harmonic number.

hn + 1.0/(n+1)

In mathematics, the Nth harmonic number is defined to be 1 + 1/2 + 1/3 + 1/4 + ... + 1/N. So, the first harmonic number is 1, the second is 1.5, the third is 1.83333... and so on. Assume that n is an integer variable whose value is some integer N greater than 1. Assume also that hn is a double variable whose value is the Nth harmonic number. Write an expression whose value is the (N-1)th harmonic number.

hn - 1.0 /(n)

The cin Object: cin converts data to the type that matches the variable:

int height; cout << "How tall is the room? "; cin >> height;

Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Assuming the item is paid for with a minimum amount of change and just single dollars, write an expression for the amount of change (in cents) that would have to be paid.

price%100

Declare k, d, and s so that they can store an integer, a real number, and a small word (under 10 characters). Use these variables to first read an integer, a real number, and a small word and print them out in reverse order (ex; the word, the real, and the integer) all on the same line, separated by EXACTLY one space from each other. Then, on a second line, print them out in the original order (the integer, the real, and the word), separated again by exactly one space from each other.

int k; double d=5; char s[10]; cin>>k>>d>>s; cout<<s<<" "<<d<<" "<<k<<"\n"<<k<<" "<<d<<" "<<s;

Assume that price is an integer variable whose value is the price (in US currency) in cents of an item. Assuming the item is paid for with a minimum amount of change and just single dollars, write an expression for the number of single dollars that would have to be paid.

price/100

Given an integer variable profits, write a statement that increases the value of that variable by a factor of 10.

profits *= 10;

data type ranking

long double double float unsigned long long unsigned int int

m=y2-y1/x2-x1

m = (y2-y1) /(x2-x1);

Write a statement using a compound assignment operator to subtract 10 from minutes_left (an integer variable that has already been declared and initialized).

minutes_left -= 10;

Write a statement using the increment operator to increase the value of num_items (an already declared integer variable) by 1.

num_items++;

Write a statement using a compound assignment operator to multiply num_rabbits by 4, changing the value of num_rabbits (num_rabbits has already been declared and initialized).

num_rabbits *=4;

Write a statement using a compound assignment operator to cut the value of pay in half (pay is an integer variable that has already been declared and initialized).

pay /= 2;

Write an expression that concatenates the string variable suffix onto the end of the string variable prefix .

prefix + suffix

A wall has been built with two pieces of sheetrock, a smaller one and a larger one. The length of the smaller one is stored in the variable small. Similarly, the length of the larger one is stored in the variable large. Write a single expression whose value is the length of this wall.

small+large

The area of a square is stored in a double variable named area. Write an expression whose value is length of one side of the square.

sqrt (area)

If a right triangle has sides of length A, B and C and if C is the largest, then it is called the "hypotenuse" and its length is the square root of the sum of the squares of the lengths of the shorter sides (A and B). Assume that variables a and b have been declared as doubles and that a and b contain the lengths of the shorter sides of a right triangle: write an expression for the length of the hypotenuse.

sqrt((pow(a, 2)) + (pow(b,2)))

The area of a square is stored in a double variable named area. Write an expression whose value is length of the diagonal of the square.

sqrt(pow((sqrt(area)), 2) + pow((sqrt(area)) , 2))

The length of a rectangle is stored in a double variable named length, the width in one named width. Write an expression whose value is the length of the diagonal of the rectangle.

sqrt(pow(length, 2) + pow(width, 2))

Declare a string named line and write a statement that reads in the next line of standard input into this variable.

string line; getline(cin, line);

Write a statement using a compound assignment operator to change val to the remainder when val is divided by 16 (val has already been declared and initialized)

val %=16;

Write a statement using a compound assignment operator to add 5 to val (an integer variable that has already been declared and initialized).

val+=5;

order of operations

when there are more than one operator, PEMDAS


Conjuntos de estudio relacionados

Depreciation - Definition, Causes, Straight Line Method

View Set

Chapter 13 Government Test Review

View Set

OChem II - Ch. 12 and Spectroscopy

View Set

Chapter 18 - Disorders of blood flow and blood pressure

View Set