CSCI121 - Module 1, Module 2, Module 3 Study Guide

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is the output produced by the following (when embedded in a correct program with x declared to be of type int)? x = 10; do { cout << x << endl; x = x - 3; } while (x > 0);

10, 7, 4, 1

What is the output produced by the following (when embedded in a correct program with x declared to be of type int)? x = 10; while (x > 0) { cout << x << endl; x = x - 3; }

10, 7, 4, 1

what is the first step you should take when creating a program?

Be certain that the task to be accomplished by the program is completely and precisely specified

What is the value of the following expression? (true && (4/3 || !(6)))

True

What would be the output if the assignment we changed to the following? int extra = -37; if (extra < 0) cout << "small"; else if (extra == 0) cout << "medium"; else cout << "large";

small

The code that a programmer writes is called ___ code

source

What is the advantage of the C++11 integer data types over the old data types?

specifies exact size in bits

NOTE: in mathematics, division by zero is undefined. So, in C++, division by zero is always an error. Given a int variable named callsReceived and another int variable named operatorsOnCall write the necessary code to read values into callsReceived and operatorsOnCall and print out the number of calls received per operator (integer division with truncation will do). HOWEVER: if any value read in is not valid input, just print the message "INVALID".

{ cin >> callsReceived; cin >> operatorsOnCall; if ((operatorsOnCall > 0) && (callsReceived >= 0)) { cout << callsReceived / operatorsOnCall; } else { cout << "INVALID\n"; } }

Write a statement that prints Hello World to the screen.

{ cout << "Hello World"; return 0; }

if-else statement is known as

selection.

Given the following code fragment, what is the final value of y? int x, y; x = -1; y = 0; while(x<=3) { y+=2; x+=1; }

10

What is the value of x after the following code executes? int x=10; if( ++x >10) { x =13; }

13

Which of the following is correct?

#include <iostream>

Write the include directive needed to allow use of the various I/O operators such as cout and cin.

#include <iostream> using namespace std;

Write a complete program that prints Hello World to the screen.

#include <iostream> using namespace std; int main( ) { cout << "Hellow World"; return 0; }

Write a program that contains statements that output the value of five or six variables that have been declared., but not initialized. Compile and run the program

#include <iostream> using namespace std; int main( ) { int first, second, third, fourth, fifth; cout << first << " " << second << " " << third << " " << fourth << " " << fifth << endl; return 0; }

Write a complete C++ program that asks the user for a number of gallons and then outputs the equivalent number of liters. There are 3.78533 liters in a gallon. Use a declared constant. Since this is just an exercise, you need not have any comments in your program.

#include <iostream> using namespace std; int main() { const double LITERS_PER_GALLON = 3.78533; double gallons, liters; cout << "Enter number of gallons then return: \n"; cin >> gallons; liters = LITERS_PER_GALLON * gallons; cout << There are " << liters << " in " << gallons << " gallons.\n"; return 0; }

Write a complete C++ program that writes the phrase "Hello world" to the screen. The program does nothing else.

#include <iostream> using namespace std; int main() { cout << "Hello world\n"; return 0; }

Write a short program that declares and initializes double variables one, two, three, four, and five to the values 1.000, 1.414, 1.732, 2.000, and 2.236, respectively. Then write output statements to generate the following legend and table. Use the tab escape sequence \t to line up the columns. A tab works like a mechanical stop on a typewriter and causes output to begin in a next column, usually a multiple of eight spaces away. Thte output should be N Square Root 1 1.000 2 1.414 3 1.732 4 2.000 5 2.236

#include <iostream> using namespace std; int main() { double one(1.000), two(1.414), three(1.732), four(2.000), five(2.236); cout << "\tN\tSquare Root\n"; << "\t1\t" << one << endl <<"\t2\t" << two << endl << "\t3\t" << three << endl << "\t4\t" << four << endl << "\t5\t" << five << endl; return 0; }

Write a complete C++ program that outputs the numbers 1 to 20, one per line. The program does nothing else.

#include <iostream> using namespace std; int main() { int n = 1; while (n<=20) { cout << n << endl; n++; } return 0; }

Write a complete C++ program that reads in two whole numbers and outputs their sum. Be sure to prompt for input, echo input, and label all output

#include <iostream> using namespace std; int main() { int n1, n2, sum; cout << "Enter two whole numbers\n"; cin >> n1 + n2; sum = n1 + n2; cout << "The sum of " << n1 << " and " << n2 << " is " << sum << endl; return 0; }

Write a complete program that reads two whole numbers into two variables of type int and then outputs both the whole-number part and the remainder when the first number is divided by the second. This can be done using the operators / and %.

#include <iostream> using namespace std; int main() { int number1, number2; cout << "Enter two whole numbers: "; cin >> number1 >> number2; cout << number1 << " divided by " << number2 << " equals " << (number1/number2) << " and a remainder is " << (number1%number2) << endl; return 0; }

Write a literal representing the character whose ASCII value is 65.

'A'

The character escape sequence to represent a single quote is:

'\

Consider a quadratic expression, say x2 − x − 2 Describing where this quadratic is positive (that is, greater than 0), involves describing a set of numbers that are either less than the smaller root (which is −1) or greater than the larger root (which is +2). Write a C++ Boolean expression that is true when this formula has positive values.

( (x < -1) | | (x > 2) )

Consider the quadratic expression x2 − 4x + 3 Describing where this quadratic is negative involves describing a set of numbers that are simultaneously greater than the smaller root (+1) and less than the larger root (+3). Write a C++ Boolean expression that is true when the value of this quadratic is negative.

( (x > 1) && (x < 3) )

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

(12 + 40) / 2

Assume that c is a char variable that has been declared and already given a value. Write an expression whose value is true if and only if c is what is called a whitespace character (that is a space or a tab or a newline-- none of which result in ink being printed on paper).

(c == ' ' || c == '\t' || c == '\n')

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 floor-space area of this room. DO NOT use the pow function.

(small + large) * (small + large)

Which of the following boolean expressions tests to see if x is between 2 and 15 (including 2 and 15)?

(x >=2 && x <=15)

Which of the following are equivalent to (!(x<15 && y>=3))?

(x>=15 || y<3)

Which of the following symbols has the highest precedence?

--

What is the output produced by the following (when embedded in a correct program with x declared to be of type int)? x = -42; do { cout << x << endl; x = x - 3; } while (x > 0);

-42 (since the Boolean expression isn't checked til AFTER bc of the do-while statement)

What is the output of the following program lines when embedded in a correct program that declares number to be of type int? number = (1/3) * 3; cout << (1/3) * 3 is equal to " << number;

0

What is the output of the following program lines (when embedded in a correct program that declares month, day, year, and date to be of type string)? month = "03"; day = "04"; year = "06"; date = month + day + year; cout << date << endl;

030406

What is the second line of output in following code fragment? int x = 1; cout << x << endl; { cout << x << endl; int x = 2; cout << x << endl; } cout << x << endl;

1

Though we urge you not to program using this style, we are providing an exercise that uses nested blocks to help you understand the scope rules. Give the output that this code fragment would produce if embedded in an otherwise complete, correct program. { int x = 1; cout << x << endl; { cout << x << endl; int x = 2; cout << x << endl; { cout << x << endl; int x = 3; cout << x << endl; } cout << x << endl; } cout << x << endl; }

1 1 2 2 3 2 1

What is the output of the following? int n = 1; do cout << n << " "; while (++n <= 3);

1 2 3

What is the output of the following? int n = 1; do cout << n << " "; while (n++ <= 3);

1 2 3 4

What is the third line of the output? int x = 1; cout << x << endl; { x++; cout << x << endl; int x = 10: x++; cout << x << endl; x++; } cout << x << endl

11

What is the value of x after the following code executes? int x = 10; if( ++ x > 10) { x = 13; }

13

How many times is "Hello" printed to the screen for(int i = 0; i < 14; i++) cout << "Hello" << endl;

14

What is the value of x after the following statements? double x;x = 2.0;x *= 3.0 + 5.0;x -= 2.0;

14.0

How many times is "Hello" printed to the screen for(int i = 0; i <= 14; i++) cout << "Hello" << endl;

15

Consider this code: "int v = 20; --v; cout << v++;". What value is printed, what value is v left with?

19 is printed, v ends up with 20

What is the output of the following? int count = 3; while (--count > 0) cout << count << " ";

2 1

What is the output of the following? int count = 3; while (count-- > 0) cout << count << " ";

2 1 0

Given the following declaration and output statement, assume that this has been embedded in a correct program and is run. What is the output? enum Direction { N=5, S=7, E=1, W }; // ... cout << W << " " << E << " " << S << " " N << endl;

2, 1, 7, 5

What is the output of the following? for (double sample = 2; sample > 0; sample = sample - 0.5) cout << sample << " ";

2, 1.5, 1, .5

What is the output of the following? for (int count = 1; count < 5; count++) cout << (2 * count) << " ";

2, 4, 6, 8

Given the following code fragment and the input value of 2.0, what output is generated?float tax;float total;

2.0

In college algebra we see numeric intervals given as 2 < x < 3 In C++ this interval does not have the meaning you may expect. Explain and give the correct C++ Boolean expression that specifies that x lies between 2 and 3.

2<x<3

What is the value of x after the following statements?int x;x = 15/4;

3

Convert each of the following mathematical formulas to a C++ expression 3x, 3x + y, x + y/7, (3x + y)/(z+2)

3 * x, (3 * x) + y, (x+y)/7, ( (3 * x) + y)/(z + 2)

Given the following declaration and output statement, assume that this has been embedded in a correct program and is run. What is the output? enum Direction { N, S, E, W }; // .... cout << W << " " << E << " " << S << " " << N << endl;

3, 2, 1, 0

What is the value of x after the following statements?float x;x = 15%4;

3.0

Which of the following value cannot be assigned to x if we have the following declaration statement? int x;

3.14

Another way to write the value 3452211903 is

3.452211903e09

What is the value of x after the following statements?double x;x = 15/4.0;

3.75

What is the output of the following code fragment? int i = 3; switch(i) { case 0:i = 15;break; case 1:i = 25;break; case 2:i = 35;break; case 3:i = 40; break; default:i = 0; break; } cout << i <<endl;

30

What is the value of x after the following statements?int x, y, z;y = 10;z = 3;x = y * z + 3;

33

What is the output of the following? int n = 5; while (--n > 0) { if (n == 2) exit(0); cout << n << " "; } cout << "End of Loop.";

4, 3

What is the output of the following? int n = 5; while ( --n > 0) { if (n==2) break; cout << n << " "; } cout << "End of Loop.";

4, 3, End of Loop

What output is produced by the following code, when embedded in a complete program? int number = 22; { int number = 42; cout << number << " "; } cout << number;

42 22

Given the following code, what is the final value of i? int i; for(i=0;i<=4;i+++) { cout<<i<<endl; }

5

What is the final value of i in following code fragment? int i = 0; while(i < 5){ i++; }

5

Given the following code, what is the final value of index? int index; for (index = 0; index <= 5; index++) cout << index << endl;

6

Given the following enumerated data type definition, what is the value of SAT?enum myType{SUN,MON,TUE,WED,THUR,FRI,SAT,NumDays};

6

What is the final value of i in following code fragment? int i = 0; do{ i++; } while (i <=5);

6

Given the following code, what is the final value of i + j? int i, j; for(i=0;i<4;i++) { for(j=0;j<3;j++) { if(i==2) break; } }

7

Given the following enumerated data type definition, what is the value of SAT?enum myType{SUN=3,MON=1,TUE=3,WED,THUR,FRI,SAT,NumDays};

7

Which of the following is NOT a legal identifier?

7thheaven

Which of the following is NOT a valid identifier?

7up

What punctuation signifies the end of a C++ statement?

;

Which of the following is NOT an operator?

;

What is the role of a compiler?

A compiler translates a high-level language program into a machine-language program.

What is the most important difference between a while statement and a do-while statement?

A do-while statement ALWAYS executes at least once, a while statement may have conditions that may not allow it to execute the statement

Who was the programmer for Charles Babbage's analytical engine?

Ada Lovelace

Which of the following is not true?

An algorithm allows ambiguity.

What is an operating system?

An operating system is a program, or several cooperating programs, but is best thought of as the user's chief servant.

What purpose does the operating system serve?

An operating system's purpose is to allocate the computer's resources to different tasks the computer must accomplish.

What is the value of x after the following statements?int x;x = x + 30;

x has no values

. What would be the output in Self-Test Exercise 15 if the first line were changed to the following?int first_choice = 4

Bon appetit

A ________ expression is an expression that can be thought of as being true or false.

Boolean

If the following statement were used in a C++ program, what would it cause to be written on the screen? cout << "C++ is easy to understand.";

C++ is easy to understand

Find out whether linking is done automatically by the compiler you use for this course.

CLion, no it's not automatic :(

The hardware part of the computer that controls and executes programs is called the ________.

CPU

When a program runs on a computer, the part of the computer that carries out the instructions is called the

CPU

. What would be the output in Self-Test Exercise 15 if the first line were changed to the following?int first_choice = 2;

Chocolate ice cream Onion ice cream

The integer 0 is considered true.

F

The opposite of (x >3 && x < 10) is (x < 3 && x > 10).

F

A break statement can be used to break out of multiple nested loops.

False

A break statement in a switch stops your program.

False

All nested if-else statements can be converted into switch statements.

False

An algorithm is always written in C++.

False

C++ is a low-level language.

False

Determine the value of these Boolean expressions? Assume count = 0 and limit = 10. (limit < 0) && ((limit /count) > 7)

False

If x has the value of 3, y has the value of -2, and w is 10, is the following condition true or false?if( x < 2 && w < y)

False

There are 8 bytes in one bit.

False

Variable names may begin with a number.

False

What is the output of the following cout statements embedded in these if-else statements? You are to assume that these are embedded in a complete correct program. Explain your answer. a. if(0) cout << "0 is true"; else cout << "0 is false"; cout << endl; b. if(1) cout << "1 is true"; else cout << "1 is false"; cout << endl; c. if(-1) cout << "-1 is true"; else cout << "-1 is false"; cout << endl;

False (0 converts to false) True True nonzero quantities values convert to true

Which of these is not a programming language?

HTML

What is the output of the following?for (int n = 10; n > 0; n = n-2){cout << "Hello ";cout << n << endl;}

Hello 10 Hello 8 Hello 6 Hello 4 Hello 2

What does the following print to the screen?cout << "Hello Students/n";

Hello Students\n

What is the output produced by the following (when embedded in a correct program with x declared to be of type int)? x = 10; while (x > 0) { cout << x << endl; x = x + 3; }

Infinite loop 10, 13, 16, 19,...

What are the five main components of a computer?

Input Devices, Output Devices, Processer (CPU), Main Memory, Secondary Memory

What does a break statement do? Where is it legal to put a break statement?

Is used to exit loop statements and end switch statements. It is legal to put a break statement in loops.

What best defines a "programming language"?

It allows us to express an algorithm.

What is an off-by-one loop error?

Loops that iterate the loop body one too many or one too few times are said to have an off-by-one error.

What is the difference between a machine-language program and a high-level language program?

Machine-Language Program: Low-level language consiting of 0s and 1s that the computer can directly execute. High-Level Language: Written in more english-like format and is translated by a compiler into a machine-lamguage program that the computer can directly understand and execute

Which of the following is NOT an expression?

PI=3.14159;The semicolon makes this a complete statement, not an expression.

Which of the following IS a statement?

NOT cin >> x because it's missing a semicolon!!! double pi = 3.0;

What output would be produced in the previous exercise if the > sign were replaced with <?

No output since the while Boolean expression wouldn't be satisfied

Does the following sequence produce division by zero? j = -1; if ((j>0) && (1/(j+1) >10)) cout << i << endl;

No. Because the Boolean expression j > 0 is false before the compiler even gets to the other parts after &&.

What is the output of the following code fragment? { int x = 13; cout << x <<","; } cout << x << endl;

Nothing, there is a syntax error

What is the output of the following code fragment? { int x=13; cout << x <<","; } cout << x << endl;

Nothing, there is a syntax error.

You have a fence that is to bee 100 meters long. Your fence posts are to be placed every 10 feet. How many fence posts do you need? Why is the presence of this problem in a programming book not as silly as it might seem? What problem that programmers have does this question address?

Off-by-one errors abound in problem solving, not just writing loops. Typical reasoning from those who do not think carefully is10 posts = 100 feet of fence/10 feet between postsThis of course will leave the last 10 feet of fence without a post. You need 11 posts to provide 10 between-the-post 10-foot intervals to get 100 feet of fence.

What would be the output in Self-Test Exercise 15 if the first line were changed to the following?int first_choice = 3;

Onion Ice cream

An algorithm is approximately the same thing as a recipe, but some kind of steps that would be allowed in a recipe are not allowed in an algorithm. which steps in the following recipe would be allowed in an algorithm?

Place 2 teaspoons of sugar in mixing bowl allowed Add 1 egg to mixing bowl Add 1 cup of milk to mixing bowl add 1 ounce of rum, if you are not driving add vanilla extract to taste (vague) beat until smooth (vague) pour into pretty glass (vague) sprinkle with nutmeg (vague)

The program design process can be divided into two main phases. What are they?

Problem solving phase implementation phase

RAM stands for

Random Access Memory

What output will be produced by the following code, when embedded in a complete program? int first_choice = 1; switch (first_choice + 1) { case 1: cout << "Roast beef\n"; break; case 2: cout << "Roast worms\n"; break; case 3: cout << "Chocolate ice cream\n"; case 4: cout << "Onion ice cream\n"; break; default: cout << "Bon appetit!\n"; }

Roast worms

If a programming language does not use short-circuit evaluation, what is the output of the following code fragment if the value of myInt is 0? int other=3, myInt; if(myInt !=0 && other % myInt !=0) cout << "other is odd\n"; else cout << "other is even\n";

Run-time error, No output

Flash drives, CDs, external disks are all examples of ___ STORAGE (MEMORY ) DEVICES

SECONDARY

What output would be produced by the following two lines (when embedded in a complete and correct program)? //cout << "Hello from"; cout << "Self-Test Exercise";

Self-Test Exercise

What output will be produced by the following code, when embedded in a complete program? int x = SOME_CONSTANT; cout << "Start\n"; if (x < 100) cout << "First Output. \n"; else if (x > 100) cout << "Second Output. \n"; else cout << x << endl; cout << "End\n"; SOME_CONSTANT is a constant of type int. Assume that neither "First Output" nor "Second Output" is output. So, you know the value of x is output.

Start 100 End

What output will be produced by the following code, when embedded in a complete program? int x = 2; cout << "Start\n"; if (x <= 3) if (x != 0) cout << "Hello from the second if. \n"; else cout << "Hello from the else.\n"; cout << "End\n"; cout << "Start again\n"; if (x > 3) if (x != 0) cout << "Hello from the second if. \n"; else cout << "Hello from the else.\n"; cout << "End again\n";

Start Hello from the second if End Start again End again

What would be the output? int x = 200; cout << "Start\n"; if (x < 100) cout << "First Output. \n"; else if (x > 100) cout << "Second Output. \n"; else cout << "Third Output. \n"; cout << "End\n";

Start Second OUput End

What output will be produced by the following code, when embedded in a complete program? int x = 200; cout << "Start\n"; if (x < 100) cout << "First Output. \n"; else if (x > 10) cout << "Second Output. \n"; else cout << "Third Output. \n"; cout << "End\n";

Start Second Output End

What kinds of errors are discovered by the compiler?

Syntax errors

What are the three main kinds of program errors?

Syntax errors, logic errors, run-time errors

Given the following code fragment, what is the output? int x=5; if( x > 5) cout << "x is bigger than 5. "; cout <<"That is all. "; cout << "Goodbye\n";

That is all. Goodbye

What would be the data for a program that assigns letter grades to students in a class?

The grades for each student on each test and assignment

What is a source program? What is an object program?

The high-level language program that is input to a compiler is called the source program. The translated machine-language program that is output by the compiler is called the object program.

What is linking?

The object code for your C++ program must be combined with the object code for routines (such as input and output routines) that your program uses. This process of combining object code is called linking. For simple programs, this linking may be done for you automatically.

Predict the output of the following nested loops: int n, m; for (n = 1; n <= 10; n++) for (m = 10; m >= 1; m--) cout << n << " times " << m << " = " << n * m << endl;

The output is too long to reproduce here. The pattern is as follows: 1 time 10 = 10 1 times 9 = 9 ... 1 times 1 = 1 2 times 10 = 20 2 times 9 = 18 ... 2 times 1 = 2 3 times 10 = 30 ....

What is the output of this loop? Identify the connection between the value of n and the value of the variable log.int n = 1024;int log = 0;for (int i = 1; i < n; i = i * 2)log++;cout << n << " " << log << endl;

The output is: 1024 1. The ';' after the for is probably a pitfall error.

What is the output of this loop? Identify the connection between the value of n and the value of the variable log.int n = 1024;int log = 0;for (int i = 1; i < n; i = i * 2)log++;cout << n << " " << log << endl;

The output is: 1024 10.The second number is the base 2 log of the first number.

Replace the underlines with the words in parentheses that follow: The ____ solves the ____ of a ____ by expressing an ____ in a ____ to make a ____ that can run on a ____. ( algorithm, computer, problems, program, programmer, programming language, user ) NOTE: do not just put in the replacement words, put in the WHOLE sentence with the underlines replaced.

The programmer solves the problems of a user by expressing an algorithm in a programming language to make a program that can run on a computer.

What would be the data for a program to add two numbers?

The two numbers to be added

explain why the problem-solving phase should not be slighted

The two-phase process is much more reliable, and produces a correctly working program faster!

What is the output of the following code?cout << "This is a \\" << endl;

This is a \

What is the output of this loop? Comment on the code.int n = 1024;int log = 0;for (int i = 0; i < n; i = i * 2)log++;cout << n << " " << log << endl;

This is an infinite loop. Consider the update expression i = i * 2. It cannot change i because its initial value is 0, so it leaves i at its initial value, 0.

The body of a do-while loop always executes at least once.

True

What does it mean to trace a variable? How do you trace a variable

Tracing a variable means watching a program variable change value while the program is running. This can be done with special debugging facilities or by inserting temporary output statements in the program.

All switch statements can be converted into nested if-else statements.

True

In the following code fragment, x has the value of 3.int x = 3;

True

It is legal to declare more than one variable in a single statement.

True

It is legal to make function calls inside a switch statement.

True

The body of a while loop may never execute.

True

For each of the following situations, tell which type of loop (while, do-while, or for) would work best: a. Summing a series, such as 1/2 + 1/3 + 1/4 + 1/5 + ... + 1/10. b. Reading in the list of exam score for one student. c. Reading in the number of days of sick leave taken by employees in a department. d. Testing a function to see how it performs for different values of its arguments.

a. A for loop b. A while loop c. A while loop d. A do-while loop

Given the following code fragment, and an input value of 5, what is the output?int x; if(x<3) { cout << "small\n"; } else { if(x<4) { cout << "medium\n"; } else { if(x<6) { cout << "large\n"; } else { cout << "giant\n"; } } }

large

Name the operating system that runs on the computer you use to prepare programs for this course.

Windows Operating System

Write a loop that will read in a list of even numbers (such as 2, 24, 8, 6) and compute the total of the numbers on the list. The list is ended with a sentinel value. Among other things, you must decide what would be a good sentinel value to use.

You can use any odd number as a sentinel value. int sum = 0, next; cout << "Enter a list of even number. Place an odd number at the end of the list.\n"; cin >> next; while ( (next % 2) == 0) { sum = sum + next; cin >> next; }

The character escape sequence to represent a double quote is:

\"

The character escape sequence to represent a backslash is:

\\

The character escape sequence to force the cursor to go to the next line is:

\n

What is the meaning of \n as used in the following statement (which appears in Display 1.8)? cout << "Enter the number of peas in a pod:\n";

\n tells the computer to start a new line in the output so that the next item output will be on the next line

The character escape sequence to force the cursor to advance forward to the next tab setting is:

\t

A bit is

a binary digit, like 0 or 1.

Given the following fragment that purports to convert from degreesCelsius to degrees Fahrenheit, answer the following questions: double c = 20; double f; f = (9/5) * c + 32.0; a. What value is assigned to f? b. Explain what is actually happening, and what the programmer likelywanted. c. Rewrite the code as the programmer intended.

a) 52.0 b) 9/5 has int value 1; since numerator and denominator are both int, integer division is done; the fractional part is discarded. f = (1.8 * c) +32.0; c) f = (9.0/5.0) * c + 32.0

What, if anything, is wrong with the following #include directives? a) #include <iostream > b) #include < iostream> c) #iclude <iostream>

a) space after iostream b)space before iostream c) this is right

Determine the value, true or false, of each of the following Boolean expressions, assuming that the value of the variable count is 0 and the value of the variable limit is 10. Give you answer as one of the values true or false. a. (count == 0) && (limit < 20) b. count == 0 && limit < 20 c. (limit > 20) || (count < 5) d. !(count == 12) e. (count == 1) && (x < y) f. (count < 10) || (x < y) g. !( ((count < 10) || (x < y)) && (count >= 0) ) h. ((limit/count) > 7) || (limit < 20) i. (limit < 20) || ((limit/count) > 7) j. ((limit/count) > 7) && (limit < 0) k. (limit < 0) && ((limit/count) > 7) l. (5 && 7) + (!6)

a. true b. true c. true d. true e. false f. true g. false h. produces an error i. true j. produces an error k. false l. 1 or true 5, 6, 7 evaluate to true because they are nonzero. so, 5 && 7 is true, !6 is false so we get 1 + 0 = 1 or "true" as integers that value 0 are false and 1 are true.

Which of the following is NOT an operator?

add

An operating system

allocates resources like memory to programs that are running.

#include <iostream> is

an include directive.

At each step of its operation, the input to a Central Processing Unit is

an instruction.

cout << "How many items would you want?\n";

an output statement.

What is the output of the following program lines, when embedded in a correct program that declares all variables to be of type char? a = 'b'; b = 'c'; c = a; cout << a << b << c << 'c';

bcbb

Declare a variable isACustomer, suitable for representing a true or false value.

bool isACustomer;

Name two kinds of statements in C++ that alter the order in which actions are performed. Give some examples.

branching statements (if and if-else statements), iteration statements (while and do-while statements), and function call statements.

A mistake in a computer program is called a ________.

bug

Assume that c is a char variable that has been declared and already given a value. Write an expression whose value is true if and only if c is a tab character.

c == '\t'

Which of the following statements is NOT legal?

char ch="cc";

The stream that is used for input from the keyboard is called ________.

cin

Write an if/else statement that adds 1 to the variable minors if the variable age is less than 18, adds 1 to the variable adults if age is 18 through 64, and adds 1 to the variable seniors if age is 65 or older.

cin >> age; if (age < 18) minors = minors + 1; else if ((age >= 18) && (age <=64)) adults = adults + 1; else if (age >= 65) seniors = seniors + 1;

Assume that an int variable age has been declared and already given a value and assume that a char variable choice has been declared as well. Assume further that the user has just been presented with the following menu: S: hangar steak, red potatoes, asparagus T: whole trout, long rice, brussel sprouts B: cheddar cheeseburger, steak fries, cole slaw (Yes, this menu really IS a menu!) Write some code that reads a single character (S or T or B) into choice. Then the code prints out a recommended accompanying drink as follows: If the value of age is 21 or lower, the recommendation is "vegetable juice" for steak, "cranberry juice" for trout, and "soda" for the burger. Otherwise, the recommendations are "cabernet", "chardonnay", and "IPA" for steak, trout, and burger respectively. Regardless of the value of age, your code should print "invalid menu selection" if the character read into choice was not S or T or B.

cin >> choice; if (choice == 'S') { if (age <= 21) cout << "vegetable juice"; else // branch missing? cout << "cabernet"; } else if (choice == 'T') { if (age <= 21) cout << "cranberry juice"; else // branch missing? cout << "chardonnay"; } else if (choice == 'B') { if (age <= 21) cout << "soda"; else // branch missing? cout << "IPA"; } else cout << "invalid menu selection";

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;

Which of the following lines correctly reads a value from the keyboard and stores it in the variable named myFloat?

cin >> myFloat;

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 << "Greetings, " << name << "!!!\n";

An error in a program that involves a violation of language rules will be detected at

compile time

Declare an int constant MonthsInDecade whose value is the value of the constant MonthsInYear (already declared) multiplied by 10.

const int MonthsInDecade(MonthsInYear * 10);

Which of the following will move the cursor to new line after print out the message?

cout << "Hello World!\n";

Give an input statement that will fill the variable the_number (of type int) with a number typed in at the keyboard. Precede the input statement with a prompt statement asking the user to enter a whole number.

cout << "Please enter a whole number \n" << "and press return when finished: \n"; cin >> the_number;

Give an output statement that will produce the following message on the screen: The answer to the question of Life, the Universe, and Everything is 42.

cout << "The answer to the question of\n" << Life, the Universe, and Everything is 42.\n";

Which of the following is not a statement?

cout << "hello world " << endl (bc it's missing a semicolon!!)

Given an integer variable count, write a statement that writes the value of count to standard output.

cout << count

Give an output statement that produces the new-line character and a tab character.

cout << endl << "\t";

Given a floating-point variable fraction, write a statement that writes the value of fraction to standard output. Do not write anything else to standard output -- just the value of fraction.

cout << fraction;

Which of the following lines correctly write the value of the variable named myFloat to screen?

cout << myFloat;

Two variables, num and cost have been declared and given values: num is an integer and cost is a double. Write a single statement that outputs num and cost to standard output. Print both values (num first, then cost), separated by a space on a single line that is terminated with a newline character. Do not output any thing else.

cout << num << " " << cost;

What statements should you include in your program to ensure that, when a number of type double is output, it will be output in ordinary notation with three digits after the decimal point?

cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3);

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.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); cout << x;

What is the output of the following code fragment if x is 15? if(x < 20){ if(x < 10) cout << "less than 10 "; else cout << "large\n"; }

large

Which of the following is NOT part of the Software Life Cycle?

data entry

Given a char variable c that has already been declared, write some code that repeatedly reads a value from standard input into c until at last a 'Y' or 'y' or 'N' or 'n' has been entered.

do { cin >> c; } while (!(c == 'Y' || c == 'y' || c == 'N' || c == 'n'));

You need to write a loop that will keep reading and adding integers to a sum, until the sum reaches or exceeds 21. The numbers are all less than 20 and the sum is initially 0. Which is the preferred loop construct to use?

do-while loop

Write a statement that declares a double variable named dosage.

double dosage;

Give a C++ statement that will increase the value of the variable length by 8.3. The variable length is of type double.

double length = length + 8.3;

Write an expression that computes the difference of the variables endingTime and startingTime.

endingTime - startingTime

If x has the value of 3, y has the value of -2, and w is 10, is the following condition true or false? if( x < 2 && w < y)

false

Given an char variable last that has been initialized to a lowercase letter, write a loop that displays all possible combinations of two letters in the range 'a' through last. The combinations should be displayed in ascending alphabetical order: For example, if last was initialized to 'c' the output should be aa ab ac ba bb bc ca cb cc

for (char outterChar='a'; outterChar <=last; outterChar++){for (char innerChar='a'; innerChar <=last; innerChar++){cout << outterChar << innerChar << "\n";}}

Given an int variable i that has already been declared, write a for loop that prints the integers 0 through 39, separated by spaces. Use no variables other than i.

for (i = 0; i <= 39; i++) cout << i << endl;

Assume the int variables i and result, have been declared but not initialized. Write a for loop header -- i.e. something of the form for ( . . . ) for the following loop body: result = result * i; When the loop terminates, result should hold the product of the odd numbers between 10 and 20. NOTE: just write the for loop header; do not write the loop body itself.

for (i = 11, result = 1; i < 20; i+=2)

Write a loop that reads positive integers from standard input, printing out those values that are even, separating them with spaces, and that terminates when it reads an integer that is not positive. Declare any variables that are needed.

int count, sum; sum = 0; cin >> count; while (count > 0) { if (((count%2) == 0) && (count > 0)) sum += count; cin >> count; } cout << sum;

Assume that the int variables i, j and n have been declared, and n has been initialized. Write code that causes a "triangle" of asterisks to be output to the screen, i.e., n lines should be printed out, the first consisting of a single asterisk, the second consisting of two asterisks, the third consisting of three, etc. The last line should consist of n asterisks. Thus, for example, if n has value 3, the output of your code should be (scroll down if necessary): * ** ***

for (i = 1; i <= n; i++){ for (j = 1; j <= i; j++) cout << "*"; cout << "\n"; }

Write a loop that will write the word Hello to the screen ten times.

for (int count = 1; count <= 10; count++) cout << "Hello\n";

Rewrite the following loops as for loops. a. int i = 1; while (i <= 10) { if (i < 5 && i != 2) cout << 'X'; i++; } b. int i = 1; while (i <= 10) { cout << 'X'; i = i + 3; } c. long m = 100; do { cout << 'X'; m = m + 100; } while (m < 1000);

for (int i = 1, i <= 10, i++ ) i < 5 && i != 2 cout << 'X'; for (int i = 1, i <= 10, i = i + 3) cout << 'X'; cout << 'X'; for (long m = 200, m < 1000, m = m + 100) cout << 'X';

Write a for loop that prints in ascending order all the positive multiples of 5 that are less than 175, separated by spaces.

for (int x = 5; x < 175; x = x+=5) cout << x << " " << endl;

Write a for loop that prints all the even integers from 80 through 20 inclusive, separated by spaces.

for (int x = 80; x >= 20; x = x-=2) cout << x << " \n";

Given an int variable k that has already been declared, use a for loop to print a single line consisting of 97 asterisks. Use no variables other than k.

for (k = 1; k <= 97; k++) cout << "*";

Write a for loop that computes the following sum: 5+10+15+20+...+485+490+495+500. The sum should be placed in a variable sum that has already been declared and initialized to 0. In addition, there is another variable, num that has also been declared. You must not use any other variables.

for (num = 5; num <= 500; num+=5) sum = sum + num;

You have a variable, n, with a non-negative value, and need to write a loop that will keep print n blank lines. What loop construct should you use?

for loop

You need to write a loop that will repeat exactly 125 times. Which is the preferred loop construct to use?

for loop

Given two integer variables matricAge and gradAge, write a statement that gives gradAge a value that is 4 more than the value of matricAge.

gradAge = 4 + matricAge;

Write an if-else statement that outputs the word Passed provided thevalue of the variable exam is greater than or equal to 60 and the value of the variable programs_done is greater than or equal to 10. Otherwise, the if-else statement outputs the word Failed. The variables exam and programs_done are both of type int.

if ( (exam >= 60) && (program >= 10)) cout << "Passed\n"; else cout << "Failed\n";

Clunker Motors Inc. is recalling all vehicles from model years 1995-1998 and 2004-2006. Given a variable modelYear write a statement that prints the message "RECALL" to standard output if the value of modelYear falls within those two ranges.

if ( (modelYear > 1994 && modelYear < 1999) || (modelYear > 2003 && modelYear < 2007)) cout << "RECALL";

Write an if-else statement that outputs the word Warning provided that either the value of the variable temperature is greater than or equal to 100, or the value of the variable pressure is greater than or equal to 200, or both. Otherwise, the if-else statement outputs the word OK. The variables temperature and pressure are both of type int.

if ( (temp >= 100) | | (temp = 200) ) cout << "Warning\n"; else cout << "OK\n";

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002. Given an int variable modelYear and a string modelName write a statement that prints the message "RECALL" to standard output if the values of modelYear and modelName match the recall details.

if ((modelYear >= 1999) && (modelYear <= 2002) && (modelName == "Extravagant")) cout << "RECALL\n";

Clunker Motors Inc. is recalling all vehicles in its Extravagant line from model years 1999-2002 as well all vehicles in its Guzzler line from model years 2004-2007. Given an int variable modelYear and a string modelName write a statement that prints the message "RECALL" to standard output if the values of modelYear and modelName match the recall details.

if ((modelYear >= 1999) && (modelYear <= 2002) && (modelName == "Extravagant")) cout << "RECALL\n"; else if ((modelYear >= 2004) && (modelYear <= 2007) && (modelName == "Guzzler")) cout << "RECALL\n";

Assume that the variables gpa, deansList and studentName, have been declared and initialized. Write a statement that both adds 1 to deansList and prints studentName to standard out if gpa exceeds 3.5.

if (gpa > 3.5) { deansList = deansList + 1; cout << studentName; }

Assume that isIsosceles is a bool variable, and that the variables isoCount, triangleCount, and polygonCount have all been declared and initialized. Write a statement that adds 1 to each of these count variables (isoCount, triangleCount, and polygonCount) if isIsosceles is true.

if (isIsosceles == true) { isoCount = isoCount + 1; triangleCount = triangleCount + 1; polygonCount = polygonCount + 1; }

Write a loop that reads positive integers from standard input, printing out those values that are greater than 100, and that terminates when it reads an integer that is not positive. The values should be separated by single blank spaces. Declare any variables that are needed.

int count; do { cin >> count; if (count > 100) cout << count << " "; } while (count > 0);

Declare an integer variable named degreesCelsius.

int degreeCelsius;

Division by zero when the program is executing is an example of a

run-time error

Online Book Merchants offers premium customers 1 free book with every purchase of 5 or more books and offers 2 free books with every purchase of 8 or more books. It offers regular customers 1 free book with every purchase of 7 or more books, and offers 2 free books with every purchase of 12 or more books. Write a statement that assigns freeBooks the appropriate value based on the values of the bool variable isPremiumCustomer and the int variable nbooksPurchased.

if (isPremiumCustomer) { if ((nbooksPurchased > 4) && (nbooksPurchased < 8)) freeBooks = 1; else if (nbooksPurchased >= 8) freeBooks = 2; else freeBooks = 0; } else { if ((nbooksPurchased > 6) && (nbooksPurchased < 12)) freeBooks = 1; else if (nbooksPurchased >= 12) freeBooks = 2; else freeBooks = 0; }

Write a multiway if-else statement that classifies the value of an int variable n into one of the following categories and writes out an appropriate message: n < 0 or 0 <= n <= 100 or n > 100

if (n <0) cout << n << " is less than zero" << endl; else if ((0 <= n) || (n <= 100)) cout << n << " is between zero and 100" << endl; else if (n > 100) cout << n << " is greater than 100" << endl;

Suppose savings and expenses are variables of type double that have been given values. Write an if-else statement that outputs the word Solvent, decreases the value of savings by the value of expenses, and sets the value of expenses to 0, provided that savings is at least as large as expenses. If, however, savings is less than expenses, the if-else statement simply outputs the word Bankrupt, and does not change the value of any variables.

if (savings >= expenses) { savings = savings - expenses; expenses = 0; cout << "Solvent\n"; } else { cout << "Bankrupt\n";

Write an if-else statement that outputs the word High if the value of the variable score is greater than 100 and Low if the value of score is at most 100. The variable score is of type int.

if (score > 100) cout << "High"; else cout << "Low";

Write an if/else statement that compares the value of the variables soldYesterday and soldToday, and based upon that comparison assigns salesTrend the value -1 or 1.-1 represents the case where soldYesterday is greater than soldToday; 1 represents the case where soldYesterday is not greater than soldToday.

if (soldYesterday > soldToday) salesTrend = -1; else salesTrend = 1;

Write a statement that increments (adds 1 to) one and only one of these five variables: reverseDrivers parkedDrivers slowDrivers safeDrivers speeders. The variable speed determines which of the five is incremented as follows: The statement increments reverseDrivers if speed is less than 0, increments parkedDrivers if speed is less than 1, increments slowDrivers if speed is less than 40, increments safeDrivers if speed is less than or equal to 65, and otherwise increments speeders.

if (speed < 0) reverseDrivers = reverseDrivers + 1; else if (speed < 1) parkedDrivers = parkedDrivers + 1; else if (speed < 40) slowDrivers = slowDrivers + 1; else if (speed <= 65) safeDrivers = safeDrivers + 1; else if (speed > 65) speeders = speeders + 1;

Write a conditional that assigns true to the variable fever if the variable temperature is greater than 98.6.

if (temperature > 98.6) fever = true;

Write an if/else statement that assigns true to the variable fever if the variable temperature is greater than 98.6; otherwise it assigns false to fever.

if (temperature > 98.6) fever = true; else fever = false;

The following if-else statement will compile and run without any problems.However, it is not laid out in a way that is consistent with the other if-else statements we have used in our programs. Rewrite it so that the layout (indenting and line breaks) matches the style we used in this chapter. if (x < 0) {x = 7; cout << "x is now positive.";} else {x = -7; cout << "x is now negative.";}

if (x < 0) { x = 7; cout << "x is now positive."; } else { x = -7; cout << "x is now negative.";

Write a statement that terminates the current loop when the value of the int variables x. and y.are equal

if (x == y) break; else

Given the following code fragment, which of the following expressions is always TRUE?int x;cin >> x;

if( x = 1)

What is the output of the following code fragment? int x=0; while (x < 5) cout << x << endl; x ++; cout << x << endl;

infinite loop

<< is called the stream ________ operator.

insertion

Write a statement that declares and initializes two integer variables. Call the first one age and initialize it to 15, and call the second one weight and initialize it to 90.

int age(15), weight(90);

Give the declaration for two variables called "count" and "distance". "count" is of type "int" and is initialized to zero. "distance" is of type double and is initialized to 1.5.

int count = 0; double distance = 1.5;

Consider this code: "int s = 20; int t = s++ + --s;". What are the values of s and t?

s is 20 and t cannot be determined

Write statements to declare and initialize two variables: one, named element_number can hold any of the integer values 1 through 118; the other, named atomic_weight can hold the atomic weight of the given element; atomic weights are values like 3.76.In the declaration, initialize the variables to the values for oxygen, which is element number 8 and has an atomic weight of 15.9994.

int element_number; double atomic_weight; element_number = 8; atomic_weight = 15.9994;

Give the declaration for two variables called feet and inches. Both variables are of type int and both are to be initialized to zero in the declaration. Use both initialization alternatives.

int feet = 0, inches = 0; int feet(0), inches(0);

Consider this data sequence: "3 11 5 5 5 2 4 6 6 7 3 -8". Any value that is the same as the immediately preceding value is considered a CONSECUTIVE DUPLICATE. In this example, there are three such consecutive duplicates: the 2nd and 3rd 5s and the second 6. Note that the last 3 is not a consecutive duplicate because it was preceded by a 7. Write some code that uses a loop to read such a sequence of non-negative integers, terminated by a negative number. When the code exits the loop it should print the number of consecutive duplicates encountered. In the above case, that value would be 3.

int firstNumber,secondNumber = -1, duplicates = 0; do { cin >> firstNumber; if ( secondNumber == -1) { secondNumber = firstNumber; } else { if ( secondNumber == firstNumber ) duplicates++; else secondNumber = firstNumber; } } while(firstNumber > 0 ); cout << duplicates;

Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read, the sum of all the odd integers read, a count of the number of even integers read, and a count of the number of odd integers read, all separated by exactly one space. Declare any variables that are needed.

int num=0; int sumeven=0; int sumodd=0; int evencount=0; int oddcount=0; do { cin >> num; if (num % 2 == 0 && num > 0) { evencount++; sumeven += num; } else if (num > 0) { oddcount++; sumodd += num; } } while (num > 0); cout<<sumeven; cout<<" "<<sumodd; cout<<" "<<evencount; cout<<" "<<oddcount;

Which of the following is NOT an expression?

int prime = 37 a declaration with an initialization has no VALUE and is not an expression

Give a C++ statement that will change the value of the variable product to its old value multiplied by the value of the variable n. The variables are all type int

int product = product * n;

Give a C++ statement that will change the value of the variable sum to the sum of the values in the variables n1 and n2. The variables are all of type int.

int sum = (n1 + n2);

Which comment below is the most helpful?

int volume; // size of trunk in cubic feet

Which of the following will have infinite loop?

int x = 0; while(x >= 0){ x++; }

Which of the following will have infinite loop?

int x = 5; while (x > 0);{ x--; }

Which of the following is a declaration statement?

int x;

Write a declaration of an int variable year and initialize it to 365.

int year; year = 365;

Each repetition of a loop body is called ________.

iteration

Each time a loop body executes is known as an ________.

iteration

Given an int variable n that has already been declared and initialized to a positive value, and another int variable j that has already been declared, use a do...while loop to print a single line consisting of n asterisks. Thus if n contains 5, five asterisks will be printed. Use no variables other than n and j.

j = 1; do { cout << "*"; j++; } while (j <= n);

Words that have a special meaning in a programming language are called

key words

What output will be produced by the following code, when embedded in a complete program?int extra = 2;if (extra < 0)cout << "small";else if (extra == 0)cout << "medium";elsecout << "large";What output will be produced by the following code, when embedded in a complete program? int extra = 2; if (extra < 0) cout << "small"; else if (extra == 0) cout << "medium"; else cout << "large";

large

The purpose of testing a program with different combinations of data is to expose run-time and

logic

suppose you write a program that is supposed to compute the interest on a bank account at a bank that computes interest on a daily basis, and suppose you incorrectly write your program so that it computes interest on an annual basis. what type of error

logic error

Declare a long integer variable named grossNationalProduct.

long int grossNationalProduct;

Every C++ program must contain a

main function

What would be the output if the assignment were changed to the following? int extra = 0; if (extra < 0) cout << "small"; else if (extra == 0) cout << "medium"; else cout << "large";

medium

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 = minutes_left - 10;

What is wrong with the following statement?cout << "Hello to everyone\n;

missing a "

Which is the best identifier for a variable to represent the amount of money your boss pays you each month?

monthlyPay

What is the meaning of the following statement (which appears in Display 1.8)? totalPeas = numberOfPods * peasPerPod

multiply the two numbers of the variables numberofPods and peasPerPod and to place the result in the variable named totalPeas

Computers that are interconnected are known as a ________.

network

Clunker Motors Inc. is recalling all vehicles from model years 2001-2006. A bool variable named norecall has been declared. Given an int variable modelYear write a statement that assigns true to norecall if the value of modelYear does NOT fall within the recall range and assigns false otherwise. Do not use an if statement in this exercise!

norecall = ( (modelYear < 2001) || (modelYear > 2006) ); <-- WATCH THE = or ==! = is assigning, == is equal to!!

What is the output of the following code fragment if x is 15? if(x>20){ if(x<10) cout << "less than 10"; else cout << "large"; }

nothing

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

num_items++;

Write an expression that evaluates to true if the value of the integer variable numberOfPrizes is divisible (with no remainder) by the integer variable numberOfParticipants. (Assume that numberOfParticipants is not zero.)

numberOfPrizes%numberOfParticipants == 0

Compilers translate the instructions written by the programmer into ___ code

object code

The output of the compiler is called

object code

A loop that iterates one too many or one too few times is said to be ________.

off-by-one error

When a program is not running, it is stored

on a disk

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

prefix + suffix

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

Write an expression that computes the remainder of the variable principal when divided by the variable divisor. (Assume both are type int.)

principal%divisor

A set of instructions that the computer will follow is called a ________.

program

Give good variable names for each of the following: a. A variable to hold the speed of an automobile b. A variable to hold the pay rate for an hourly employee c. A variable to hold the highest score in an exam

rate_car rate_hour top_score

Write a statement to find the remainder rem when num is divided by 5. (The variables have already been declared and num has already been initialized.)

rem = num%5;

Which of the following is NOT a valid identifier?

return

Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". There is a CONSECUTIVE REPETITION of length 3 (the three consecutive birds) and a CONSECUTIVE REPETITION of length 2 (the two reptiles). There are also several SINGLETONs of length 1 (a singleton fish, a singleton bird, a singleton mammal, and another singleton fish). Write some code that uses a loop to read in a sequence of words, terminated by the "xxxxx". The code assigns to t the number of CONSECUTIVE REPETITIONS that were read. (For example, in the above data sequence that value would be 2.) Assume that t has already been declared but not initialized. Assume that there will be at least one word before the terminating "xxxxx".

string currentWord= " "; string previousWord = " "; int currentState = 0; int lastState = -1; t = -1; while (currentWord != "xxxxx") { cin >> currentWord; if (currentWord != previousWord && currentWord != "xxxxx") currentState = 0; if (currentWord == previousWord && currentWord != "xxxxx") currentState = 1; if (currentState != lastState && lastState != 1) t++; previousWord = currentWord; lastState = currentState; } cout << t;

Write a loop that reads strings from standard input where the string is either "duck" or "goose". The loop terminates when "goose" is read in. After the loop, your code should print out the number of "duck" strings that were read.

string duck, goose, number; int count; count = 0; do { cin >> number; if (number < "goose") count++; } while (number < "goose"); cout << count;

Declare a string variable named empty and initialize it to the empty string.

string empty; empty = "";

In the Happy Valley School System, children are classified by age as follows: less than 2, ineligible 2, toddler 3-5, early childhood 6-7, young reader 8-10, elementary 11 and 12, middle 13, impossible 14-16, high school 17-18, scholar greater than 18, ineligible Given an int variable age, write a switch statement that prints out the appropriate label from the above list based on age.

switch (age) { case 0: case 1: cout << "ineligible\n"; break; case 2: cout << "toddler\n"; break; case 3: case 4: case 5: cout << "early childhood\n"; break; case 6: case 7: cout << "young reader\n"; break; case 8: case 9: case 10: cout << "elementary\n"; break; case 11: case 12: cout << "middle\n"; break; case 13: cout << "impossible\n"; break; case 14: case 15: case 16: cout << "high school\n"; break; case 17: case 18: cout << "scholar\n"; break; default: cout << "ineligible\n"; }

Write a switch statement that tests the value of the char variable response and performs the following actions: if response is y, the message Your request is being processed is printed if response is n, the message Thank you anyway for your consideration is printed if response is h, the message Sorry, no help is currently available is printed for any other value of response, the message Invalid entry; please try again is printed

switch (response) { case 'y': cout << "Your request is being processed" << endl; break; case 'n': cout << "Thank you anyway for your consideration" << endl; break; case 'h': cout << "Sorry, no help is currently available" << endl; break; default: cout << "Invalid entry; please try again" << endl; }

omitting the final brace } from a program produces an error

syntax

If you omit a punctuation symbol (such as a semicolon) from a program, an error is produced. What kind of error?

syntax error

The rules that govern the correct order and usage of the elements of a language are called the

syntax of the language

suppose your program has a situation about which the compiler reports a warning. what should you do about it?

take warning as if they had been reported as errors. ask instructor on how to handle

what is the meaning of this directive? #include <iostream>

tells the complier to fetch the file iostream. includes declarations of cin, cout, <<, >> operators for input and output. this enables correct linking of the object code from the library with the input and output statements in the program

What is the meaning of the following statement (which appears in Display 1.8)? cin >> peasPerPod;

tells the computer to read the next number that is typed in at the keyboard (inputted) and to send the number to the variable named peasPerPod

Given three already declared int variables, i, j, and temp, write some code that swaps the values in i and j. Use temp to hold the value of i and then assign j's value to i. The original value of i, which was saved in temp, can now be assigned to j.

temp = i; i = j; j = temp;

Given that two int variables, total and amount, have been declared, write a loop that reads integers into amount and adds all the non-negative values into total. The loop terminates when a value less than 0 is read into amount. Don't forget to initialize total to 0.

total = 0; do { cin >> amount; if (amount > 0) total += amount; } while (amount >= 0);

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a for loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total.

total = 0; for (k = 0; k <= n; k++) total += k * k * k;

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a while loop to compute the sum of the cubes of the first n counting numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total. Do NOT modify n.

total = 0; k = 0; while (k <= n) { total += k * k * k; k++; }

Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a do...while loop to compute the sum of the cubes of the first n whole numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 into total. Use no variables other than n, k, and total.

total = 0; k = 1; do { total += k * k * k; k++; } while (k <= n);

Write a statement that increments the value of the int variable total by the value of the int variable amount. That is, add the value of amount to total and assign the result to total.

total = total + amount;

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 = val%16;

A location in memory used for storing data and given a name in a computer program is called a ___ because the data in the location can be changed.

variable

Given an int variable k that has already been declared, use a while loop to print a single line consisting of 97 asterisks. Use no variables other than k.

while (k < 97) { cout << "*"; k++; }

What is the best loop type for the following problem? Testing a function to see how it performs with different values of its arguments

while loop

You need to write a loop that reads integers and adds them to a sum as long as they are positive. Once 0 or a negative value is read in your loop terminates. Which is the preferred loop construct to use?

while loop


Set pelajaran terkait

Psychology ch 11 practice questions

View Set

「語彙」アパートを探しています

View Set

Art Appreciation Ch. 17, 18, 19, 20

View Set

Final Exam - Computer Financial Record Keeping

View Set

Dominos Case Study - All topics - Ultimate

View Set

Executive Branch and Bureaucracy

View Set

Chapter 28: Mastering Physics, Test 4

View Set