0% found this document useful (0 votes)
0 views

cp assignment 1.0

The document provides a comprehensive overview of C++ expressions, including literals, variables, and operator precedence. It includes examples of valid expressions, the effects of unary and binary operators, and sample C++ programs demonstrating arithmetic operations with integers and floating-point numbers. Additionally, it explains the output of various expressions and the use of comments in C++.

Uploaded by

engr.m.taimoor
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

cp assignment 1.0

The document provides a comprehensive overview of C++ expressions, including literals, variables, and operator precedence. It includes examples of valid expressions, the effects of unary and binary operators, and sample C++ programs demonstrating arithmetic operations with integers and floating-point numbers. Additionally, it explains the output of various expressions and the use of comments in C++.

Uploaded by

engr.m.taimoor
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

1. Is the literal 4 an expression in C++?

➤ Yes, the literal 4 is an expression in C++. In C++, a literal is a constant value that is typed
directly into the code. The value 4 is an integer literal, and it means the value 4. It requires no
variables or computations to be valid—it is already an entire expression in itself.

Example:
int a = 4; // Here, 4 is a literal to assign value to variable 'a'

2. Is the variable x a valid C++ expression?


➤ Yes, the variable x is a valid C++ expression if it has already been declared. A variable is
employed to hold data in a program. If you declare x as follows:
int x = 10;
Then simply writing x is a legal expression because it is an indication of the value held in that
variable (in this example, 10). Therefore, x can be utilized in other statements or expressions.

Example:
int y = x + 5; // 'x' is part of this expression
If you attempt to use x without first declaring it, the compiler will report an error .

3. Is x + 4 a C++ valid expression?


➤ Yes, x + 4 is a valid C++ expression if the variable x has already been declared.
This expression adds the value of the variable x and the value 4. The + sign is the addition
operator, and it operates on numbers.

Example:
int x = 3;
int y = x + 4; // y will now have the value 7
If x is not declared, then it will produce a compiler error.
4. What is the effect of applying the unary + operator to a numeric
expression?
➤ The unary + operator doesn't modify the value of a numeric expression. It merely returns the
value as it is.

Example:
int a = +5; // Equivalent to simply writing int a = 5;
It is primarily applied for clarity, or in lengthy expressions, but it doesn't particularly do much on
its own.

5. Arrange the following binary operators from high to low precedence: +, -, /,


%, = ?

➤ Operator precedence informs us which operation is performed first when there are no
parentheses.

Following is the list from top to bottom precedence:

* (multiplication)

/ (division)

% (modulus - returns remainder)

+ (addition)

- (subtraction)

= (assignment)
Thus, the correct sequence is:

*, /, %, +, -, =

Example:
int result = 5 + 3 * 2;
Although + is encountered first when going left to right, * is of greater precedence, and so
multiplication occurs first:

3 * 2 = 6, then 5 + 6 = 11.

6. Write aC++programthatreceives two integer values from the user. The


program then should print the sum (addition), difference (subtraction),
product (multiplication), quotient (division), and remainder after division
(modulus). Your program must use only integers.
A sample program run would look like (the user enters the 10 and the 2 after
the colons, and the program prints the rest):
Please enter the first number: 10
Please enter the second number: 2
10 + 2 = 12
10- 2 = 8
10 * 2 = 20
10 / 2 = 5
10 % 2 = 0
Can you explain the results it produces for all of these operations?

#include <iostream>
using namespace std;

int main()
{
int num1, num2;
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
cout << num1 << " % " << num2 << " = " << num1 % num2 << endl;
}
Sample Output:
When the user enters 10 and 2, the program prints:

Please enter the first number: 10


Please enter the second number: 2
10 + 2 = 12
10 - 2 = 8
10 * 2 = 20
10 / 2 = 5
10 % 2 = 0
Explanation of the Results:
10 + 2 = 12
➤ This adds the two numbers together.

10 - 2 = 8
➤ This subtracts 2 from 10.

10 * 2 = 20
➤ This multiplies 10 by 2.

10 / 2 = 5
➤ This divides 10 by 2. Since both are integers, the result is an integer (no decimal part).

10 % 2 = 0
➤ This gives the remainder when 10 is divided by 2. Since 10 is exactly divisible by 2, the
remainder is 0.

7. Write a C++ program that receives two double-precision floating-point values from the
user. The program then should print the sum (addition), difference (subtraction), product
(multiplication), and quotient (division). Your program should use only integers.
A sample program run would look like (the user enters the 10 and the 2.5 after the colons,
and the program prints the rest):
Please enter the first number: 10
Please enter the second number: 2.5
10 + 2.5 = 12.5
10- 2.5 = 7.5
10 * 2.5 = 25
10 / 2.5 = 4
Can you explain the results it produces for all these operations? What happens if you
attempt to compute the remainder after division (modulus) with double-precision floating-
point values?
➤ C++ Program
#include <iostream>
using namespace std;
int main()
{
double num1, num2;
cout << "Please enter the first number: ";
cin >> num1;
cout << "Please enter the second number: ";
cin >> num2;
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
}
Sample Output:
Please enter the first number: 10
Please enter the second number: 2.5
10 + 2.5 = 12.5
10 - 2.5 = 7.5
10 * 2.5 = 25
10 / 2.5 = 4

Explanation of the Results:


1. 10 + 2.5 = 12.5
➤ Adds the two numbers.
2. 10 - 2.5 = 7.5
➤ Subtracts 2.5 from 10.
3. 10 * 2.5 = 25
➤ Multiplies 10 by 2.5.
4. 10 / 2.5 = 4
➤ Divides 10 by 2.5 and returns a floating-point value.

What happens if you use `%` (modulus) with double values?

➤ The modulus operator `%` works only with integers in C++.


If you try to use it with `double` values, like this:
cout << 10.0 % 2.5 << endl; // Invalid
You will get a “compiler error” like:

Error : invalid operands of types ‘double’ and ‘double’ to binary ‘operator%’


Alternative:
If you want the “remainder with floating-point numbers”, you can use the “fmod()” function
from the `<cmath>` library:
#include <cmath>
cout << fmod(10.0, 2.5); // Output: 0.

8. Given the following declaration: int x = 2;


Indicate what each of the following C++ statements would print.
(a) std::cout << "x"<< '\n';
(b) std::cout << 'x'<< '\n';
(c) std::cout << x << '\n';
(d) std::cout << "x + 1"<< '\n';
(e) std::cout << 'x'+ 1 << '\n';
(f) std::cout << x + 1 << '\n';

➤ We have given that:


Int x = 2;
(a) std::cout << "x" << ;

It will output "x" followed by a newline (\n). The quotes around "x" mean it's a string, so it will
simply output the character x as part of the string.
Output:
x
(b) std::cout << 'x' << ;

It will output the character 'x' (not the string, but single character) followed by a newline (\n).
Output:
x
(c) std::cout << x << ;

Because x is defined as int x = 2;, this will output the value of x, which is 2, followed by a
newline(\n).
Output:
2

(d) std::cout << "x + 1" << ;


This will output the string "x + 1" as is, with the plus sign and digit 1, followed by a newline(\n).
Output:
x+1
(e) std::cout << 'x' + 1 << ;

In this situation, 'x' is considered a character, and in C++, characters are represented by integer
values as per their ASCII code. 'x' ASCII value is 120. So, 'x' + 1 is 120 + 1 = 121. Number 121
will be printed and followed by a newline(\n).
Output:
121
(f) std::cout << x + 1 << ;

This will increment 1 in the value of x, which is 2. So, it will print 2 + 1 = 3 and then a newline(\
n).
Output:
3
So, the Outputs are as follows:
(a) x
(b) x
(c) 2
(d) x + 1
(e) 121
(f) 3

9. Sort the following types in order from narrowest to widest: int, double,
float, long, char.
➤ The list of types listed from narrowest to widest (smallest to largest in terms of how much
data they can hold):

 char – Holds a single character (typically 1 byte).

 int – Holds whole numbers (typically 4 bytes).

 long – Holds larger whole numbers (typically 4 or 8 bytes, depending on the machine).

 float – Holds decimal numbers with single precision (typically 4 bytes).

 double – Maintains decimal numbers with double precision (normally 8 bytes).

Final Order:
char < int < long < float < double.

10. Given the following declarations:


int i1 = 2, i2 = 5, i3 =-3;
double d1 = 2.0, d2 = 5.0, d3 =-0.5;
Evaluate each of the following C++ expressions.
(a) i1 + i2
(b) i1 / i2
(c) i2 / i1
(d) i1 * i3
(e) d1 + d2
(f) d1 / d2
(g) d2 / d1
(h) d3 * d1
(i) d1 + i2
(j) i1 / d2
(k) d2 / i1
(l) i2 / d1
(m) i1/i2*d1
(n) d1*i1/i2
(o) d1/d2*i1
(p) i1*d1/d2
(q) i2/i1*d1
(r) d1*i2/i1
(s) d2/d1*i1
(t) i1*d2/d1

➤ We have Given:
int i1 = 2, i2 = 5, i3 = -3;
double d1 = 2.0, d2 = 5.0, d3 = -0.5;
(a) i1 + i2
2+5=7
Answer: 7

(b) i1 / i2
2 ÷ 5 = 0 (since both are integers, it gives whole number only)
Answer: 0
(c) i2 / i1
5 ÷ 2 = 2 (integer division)
Answer: 2

(d) i1 * i3
2 × (-3) = -6
Answer: -6

(e) d1 + d2
2.0 + 5.0 = 7.0
Answer: 7.0

(f) d1 / d2
2.0 ÷ 5.0 = 0.4
Answer: 0.4

(g) d2 / d1
5.0 ÷ 2.0 = 2.5
Answer: 2.5

(h) d3 * d1
-0.5 × 2.0 = -1.0
Answer: -1.0

(i) d1 + i2
2.0 + 5 = 7.0 (int is converted to double)
Answer: 7.0
(j) i1 / d2
2 ÷ 5.0 = 0.4 (int is converted to double)
Answer: 0.4

(k) d2 / i1
5.0 ÷ 2 = 2.5
Answer: 2.5

(l) i2 / d1
5 ÷ 2.0 = 2.5
Answer: 2.5

(m) i1 / i2 * d1
(2 ÷ 5) × 2.0 = 0 × 2.0 = 0.0
Answer: 0.0

(n) d1 * i1 / i2
(2.0 × 2) ÷ 5 = 4.0 ÷ 5 = 0.8
Answer: 0.8

(o) d1 / d2 * i1
(2.0 ÷ 5.0) × 2 = 0.4 × 2 = 0.8
Answer: 0.8

(p) i1 * d1 / d2
(2 × 2.0) ÷ 5.0 = 4.0 ÷ 5.0 = 0.8
Answer: 0.8
(q) i2 / i1 * d1
(5 ÷ 2) × 2.0 = 2 × 2.0 = 4.0
Answer: 4.0

(r) d1 * i2 / i1
(2.0 × 5) ÷ 2 = 10.0 ÷ 2 = 5.0
Answer: 5.0

(s) d2 / d1 * i1
(5.0 ÷ 2.0) × 2 = 2.5 × 2 = 5.0
Answer: 5.0

(t) i1 * d2 / d1
(2 × 5.0) ÷ 2.0 = 10.0 ÷ 2.0 = 5.0
Answer: 5.0

11. What is printed by the following statement:


std::cout << /* 5 */ 3 << '\n';

➤ The line /* 5 */ is a comment. It is never executed when the program is run by the computer.
Only the digit 3 is really printed.
'\' and 'n' take the cursor to the next line (print a new line).
So, the output is:
3

12. Given the following declarations:


int i1 = 2, i2 = 5, i3 =-3;
double d1 = 2.0, d2 = 5.0, d3 =-0.5;
Evaluate each of the following C++ expressions.
(a) i1 + (i2 * i3)
(b) i1 * (i2 + i3)
(c) i1 / (i2 + i3)
(d) i1 / i2 + i3
(e) 3 + 4 + 5 / 3
(f) (3 + 4 + 5) / 3
(g) d1 + (d2 * d3)
(h) d1 + d2 * d3
(i) d1 / d2- d3
(j) d1 / (d2- d3)
(k) d1 + d2 + d3 / 3
(l) (d1 + d2 + d3) / 3
(m) d1 + d2 + (d3 / 3)
(n) 3 * (d1 + d2) * (d1- d3)

➤ We have given:
int i1 = 2, i2 = 5, i3 = -3;
double d1 = 2.0, d2 = 5.0, d3 = -0.5;
(a) i1 + (i2 * i3)
i2 * i3 = 5 × (-3) = -15
i1 + (-15) = 2 - 15 = -13
output: -13

(b) i1 * (i2 + i3)


i2 + i3 = 5 + (-3) = 2
i1 × 2 = 2 × 2 = 4
output: 4

(c) i1 / (i2 + i3)


i2 + i3 = 5 + (-3) = 2
i1 ÷ 2 = 2 ÷ 2 = 1
output: 1

(d) i1 / i2 + i3
i1 / i2 = 2 ÷ 5 = 0 (integer division)
0 + (-3) = -3
output: -3

(e) 3 + 4 + 5 / 3
5 / 3 = 1 (integer division)
3+4+1=8
output: 8

(f) (3 + 4 + 5) / 3
3 + 4 + 5 = 12
12 ÷ 3 = 4
output: 4

(g) d1 + (d2 * d3)


d2 × d3 = 5.0 × (-0.5) = -2.5
d1 + (-2.5) = 2.0 - 2.5 = -0.5
output: -0.5
(h) d1 + d2 * d3
d2 × d3 = 5.0 × (-0.5) = -2.5
d1 + (-2.5) = 2.0 - 2.5 = -0.5
output: -0.5

(i) d1 / d2 - d3
d1 / d2 = 2.0 ÷ 5.0 = 0.4
0.4 - (-0.5) = 0.4 + 0.5 = 0.9
output: 0.9

(j) d1 / (d2 - d3)


d2 - d3 = 5.0 - (-0.5) = 5.5
2.0 ÷ 5.5 = 0.3636.
output: 0.3636

(k) d1 + d2 + d3 / 3
d3 / 3 = -0.5 ÷ 3 = -0.1667
d1 + d2 = 2.0 + 5.0 = 7.0
7.0 + (-0.1667) = 6.8333
output: 6.8333

(l) (d1 + d2 + d3) / 3


d1 + d2 + d3 = 2.0 + 5.0 + (-0.5) = 6.5
6.5 ÷ 3 = 2.1667
output: 2.1667

(m) d1 + d2 + (d3 / 3)
d3 ÷ 3 = -0.5 ÷ 3 = -0.1667
d1 + d2 = 2.0 + 5.0 = 7.0
7.0 + (-0.1667) = 6.8333
output: 6.8333

(n) 3 * (d1 + d2) * (d1 - d3)


d1 + d2 = 2.0 + 5.0 = 7.0
d1 - d3 = 2.0 - (-0.5) = 2.0 + 0.5 = 2.5
3 × 7.0 × 2.5 = 21.0 × 2.5 = 52.5
output: 52.5

13. How are single-line comments and block comments different ?

➤ Single-line comments use // and just comment out a single line.


Example:
// This is a single-line comment

Block comments begin with /* and end with */. They may span several lines.
Example:
/* This is a
block comment */
Easy Difference:
 Single-line comments are brief and occur on one line.
 Block comments may span multiple lines.

14. Can block comments be nested?


➤ No, block comments cannot be nested in C++.

If you attempt to nest one block comment within another, it will result in an error.

Example (this is incorrect):


/* Start of comment
/* Nested comment */
End of comment */
Simply use block comments judiciously and avoid nesting one within another.

15. Which is better, too many comments or too few comments?

➤ Having too many comments is better than having too few, but ideal is to have the correct
amount.
 Too few comments make it difficult to comprehend the code.
 Having too many comments can cause the code to be cluttered and more difficult to read
if the comments themselves are not helpful.

16. What is the purpose of comments?

➤ The reason for comments is to describe the code to readers.


 Comments assist programmers in knowing what the code does and why it was written
like that.
 They make the code more readable, debuggable, and maintainable later.
 Comments are not processed by the computer, so they don't impact how the program
executes.
17. The programs in Listing 3.4 (variable.cpp), Listing 4.4
(reformattedvariable.cpp), and Listing 4.5 (reformattedvariable2.cpp)
compile to the same machine code and behave exactly the same. What makes
one of the programs clearly better than the others?

➤ Even if they all do the same thing, the more neatly and clearly written one is better.
A superior program has:
 Good spacing and indentation (proper formatting)
 Good comments
 Readable variable names
 Clearly structured
These factors make the code:
 Simpler to read
 Simpler to comprehend
 Simpler to debug or enhance in the future
The optimal program is one which is easiest to read and to work with for people — rather than
merely one which operates correctly.

18. Why is human readability such an important consideration?

➤ Readability by humans matters because other humans (or yourself in the future) must
comprehend the code.
 Code isn't written for computers alone — it's written so that humans can read, grasp, and
maintain it.
 Simple code assists in:
 Faster error detection and correction
 Changes or enhancements without difficulty
 Cooperation in a team
Time-saving and confusion avoidance — that's why readability truly matters.
19. Consider the following program which contains some errors. You may
assume that the comments within the program accurately describe the
program’s intended behavior.
#include <iostream>
int main()
{
int n1, n2, d1; // Get two numbers from the user
cin << n1 << n2; // Compute sum of the two numbers
std::cout << n1 + n2 << '\n'; // Compute average of the two numbers
std::cout << n1+n2/2 << '\n'; // Assign some variables
d1 = d2 = 0; // Compute a quotient
std::cout << n1/d1 << '\n'; // Compute a product
n1*n2 = d1; // Print result
std::cout << d1 << '\n';
}
// 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8
For each line listed in the comments, indicate whether or not a compile-time,
run-time, or logic error is present. Not all lines contain an error.

➤ First we written the program, with line numbers added for clarity:
#include <iostream> // Line 1
int main() { // Line 2
int n1, n2, d1; // Line 3
// Get two numbers from the user
cin << n1 << n2; // Line 4
// Compute sum of the two numbers
std::cout << n1 + n2 << '\n'; // Line 5
// Compute average of the two numbers
std::cout << n1 + n2 / 2 << '\n'; // Line 6
// Assign some variables
d1 = d2 = 0; // Line 7
// Compute a quotient
std::cout << n1 / d1 << '\n'; // Line 8
// Compute a product
n1 * n2 = d1; // Line 9
// Print result
std::cout << d1 << '\n'; // Line 10
}

Error analysis:
Line 1
#include <iostream>
No error
That line is correct.
Line 2
int main(void){
No error
This is the correct start to the main function.
Line 3
int n1, n2, d1;
No error
Three integer variables declared correctly.
Line 4
cin << n1 << n2;
Compile-time error
Should be std::cin >> n1 >> n2; (wrong direction of input operator, missing std::)
Line 5
std::cout << n1 + n2 << '\n';
No error
Correctly prints the sum of n1 and n2.
Line 6
std::cout << n1 + n2 / 2 << '\n';
Logic error
Because of operator precedence, it does n2 / 2 first, then adds n1. If the intent is to obtain the
average:
std::cout << (n1 + n2) / 2 << '\n';
Line 7
d1 = d2 = 0;
Compile-time error
d2 has not been declared anywhere. This causes a compile-time error.
Line 8
std::cout << n1 / d1 << '\n';
Run-time error
This is a run-time error due to the division by zero (as d1 = 0 above).
Line 9
n1 * n2 = d1;
Compile-time error
You cannot assign a value to an expression (n1 * n2). The assignment should be reversed. So it
should be:
d1 = n1 * n2;
Line 10
std::cout << d1 << '\n';
No error
This line is well stated if d1 was assigned correctly earlier.
Final Answer Finalization:

Line Type of Error Reason


1 No error Correct include statement
2 No error Correct main function
3 No error Correct variable declaration
4 Compile-time error Wrong input operator and missing std::
5 No error Correct output
6 Logic error Incorrect average calculation
7 Compile-time error d2 is not declared
8 Run-time error Division by zero
9 Compile-time error Assignment applied incorrectly
10 No error Correct output (if d1 is valid)

20. What distinguishes a compiler warning from a compiler error? Should


you be concerned about warnings? Why or why not?

➤ Answer
Compiler Error:
A compiler error is something that is incorrect in your code, and the program will not run unless
you get it fixed. Suppose you omit a semicolon or type an incorrect command; that's an error.
Compiler Warning:
A compiler warning is that your code can have a problem, but the program will run anyway. It's
not a serious mistake, but the machine is giving you a hint, saying, "Hey, something could go
wrong here."
Yes, you should pay attention to warnings, as they may help you discover minor issues before
they become major ones. Warnings can indicate things such as unused variables or code that may
not function as you intend.

21. What are the advantages to enhancing the warning reporting capabilities
of the compiler?

➤ Enhancing the manner in which a compiler issues warnings is useful because:

1. Finds issues early – Improved warnings can enable you to detect errors before they
become larger ones.

2. Makes your program safer – Warnings can highlight dangerous code that could lead to
bugs or crashes down the road.

3. Assists you in coding better – The compiler can inform you of best practices by
informing you of worse ones.

4. Saves time – Finding problems early saves you time debugging later.

5. Improves teamwork – Well-organized, warning-free code is easier for others to read and
comprehend.
22. Write the shortest way to express each of the following statements.
(a) x = x + 1;
(b) x = x / 2;
(c) x = x- 1;
(d) x = x + y;
(e) x = x- (y + 7);
(f) x = 2*x;
(g) number_of_closed_cases = number_of_closed_cases + 2*ncc;

➤ Answer
(a) x = x + 1; → x++;
You're adding 1 onto x.
The x++ does exactly the same thing – it's short for "add 1 to x".

(b) x = x / 2; → x /= 2;
You're dividing x by 2 and storing the result back in x.
The /= 2 is short for "divide x by 2 and store back in x".

(c) x = x - 1; → x--;
That's the same as subtracting 1 from x.
The shortcut x-- is shorthand for "decrease x by 1."

(d) x = x + y; → x += y;
You're adding y to x.
The += is shorthand for "add y to x and store it back in x".
(e) x = x - (y + 7); → x -= (y + 7);
You're subtracting (y + 7) from x.
The -= shorthand stands for "subtract this entire expression from x and store it".

(f) x = 2 * x; → x *= 2;
You're multiplying x by 2.
The *= is shorthand for "multiply x by 2 and store it back in x".

(g) number_of_closed_cases = number_of_closed_cases + 2 * ncc;


→ number_of_closed_cases += 2 * ncc;
You're adding (2 times ncc) to number_of_closed_cases.
The += is also used here – it's an abbreviation of "add and save.".

23. What is printed by the following code fragment?

int x1 = 2, y1, x2 = 2, y2;

y1 = ++x1;

y2 = x2++;

std::cout << x1 << " " << x2 << '\n';

std::cout << y1 << " " << y2 << '\n';

Whydoes the output appear as it does?


➤ Answer:

First we write code with comments:

int x1 = 2, y1, x2 = 2, y2;

y1 = ++x1; // pre-increment

y2 = x2++; // post-increment

std::cout << x1 << " " << x2 << '\n';

std::cout << y1 << " " << y2 << '\n';

Now,

Line 1:

int x1 = 2, y1, x2 = 2, y2;

x1 = 2, x2 = 2, y1 and y2 are not set yet.

Line 2:

y1 = ++x1;

++x1 is pre-increment, which means that x1 is incremented before being accessed.

x1 is now set to 3, and y1 is set to 3.

Line 3:

y2 = x2++;

x2++ is post-increment, hence x2 is accessed first before being incremented.

y2 is now assigned 2, and then x2 is 3.

Output:

std::cout << x1 << " " << x2 << '\n';

outputs: 3 3
std::cout << y1 << " " << y2 << '\n';

outputs: 3 2

Final Output:

33

32

Why does it print that?

Pre-increment (++x1) changes the value before using it → x1 and y1 both are 3.

Post-increment (x2++) uses the value first, then changes it → y2 receives 2, but x2 is 3
afterwards.

That's why the output is:

33

32

24. Consider the following program that attempts to compute the


circumference of a circle given the radius entered by the user. Given a circle’s
radius, r, the circle’s circumference, C is given by the formula: C=2 r

#include <iostream>

int main()

double C, r;

const double PI = 3.14159; // Formula for the area of a circle given its radius

C = 2*PI*r; // Get the radius from the user

cout >> "Please enter the circle's radius: ";


cin << r; // Print the circumference

std::cout << "Circumference is " << C << '\n';

(a) The compiler issues a warning. What is the warning?

(b) The program does not produce the intended result. Why?

(c) How can it be repaired so that it not only eliminates the warning but also
removes the logic error?

➤ Answer:

The program with errors is as follows:

#include <iostream>

int main()

double C, r;

const double PI = 3.14159;

C = 2*PI*r; // Error: using r before getting input

cout >> "Please enter the circle's radius: "; // Error in syntax

cin << r; // Error in syntax

std::cout << "Circumference is " << C << '\n';

(a) Answer:

The compiler will give a warning or error because:

Using variable 'r' before the user will enter a value for it. Thus, C = 2 * PI * r; is using
uninitialized variable.
Moreover, cout >> and cin << are written wrong. It should be cout << and cin >>.

(b) Answer

The reason is the wrong result since:

The program calculates the circumference without asking the radius, and thus, r has no value
when it is used.

Also, because of the wrong syntax (cout >> instead of cout <<), it will not even compile fine.

(c) Answer

The corrected program is as follows:

#include <iostream>

using namespace std;

int main()

double C, r;

const double PI = 3.14159;

cout << "Please enter the circle's radius: ";

cin >> r;

C = 2 * PI * r;

cout << "Circumference is " << C << '\n';

The changes made:

 Changed cout >> to cout <<


 Changed cin << to cin >>
 Moved the line C = 2 * PI * r; after getting the radius from the user.
25. In mathematics, the midpoint between the two points (x1 y1) and (x2 y2) is
computed by the formula

(x1 +x2/2 , y1 +y2/2)

Write a C++ program that receives two mathematical points from the user
and computes and prints their midpoint.

Asample run of the program produces

Please enter the first point: (0,0)

Please enter the second point: (1,1)

The midpoint of (0,0) and (1,1) is (0.5,0.5)

The user literally enters "(0,0)" and "(1,1)" with the parentheses and commas
as shown. To see how to do this, suppose you want to allow a user to enter the
point (239), assigning the x component of the point to a variable named x and
the y component to a variable named y. You can add the following code
fragment to your program to achieve the desired effect:

Food Calories
Bean burrito 357
Salad w/dressing 185
Milkshake 388

Table 4.7: Calorie content of several fast food items

double x, y;

char left_paren, comma, right_paren;

std::cin >> left_paren >> x >> comma >> y >> right_paren;

If the user literally types (2.3,9), the std::cin statement will assign the
( character to the variable left_paren. It next will assign 2.3 to the variable x.
It assigns the , character to the variable named comma, the value 9 to the y
variable, and the ) character to the right_paren variable. The left_paren,
comma, and right_paren variables are just placeholders for the user’s input
and are not used elsewhere within the program. In reality, the user can type in
other characters in place of the parentheses and comma as long as the
numbers are in the proper location relative to the characters; for example, the
user can type *2.3:9#, and the program will interpret the input as the point
(239).

➤ Answer:

We have to write a C++ program that takes two points from the user,

for example:

(0,0) and (1,1),

calculates a midpoint between those two points, and prints the result.

In this, we will see how the user types the points into parentheses and separates them using a
comma, like (2.3,9). Here we will cover how to read such inputs using cin in C++.

Midpoint Formula in Mathematics:

To find a midpoint between two points:

If we have two points:

First point: (x₁, y₁)

Second point: (x₂, y₂)

The midpoint is:

( 𝑥1+𝑥2/2, 𝑦1+𝑦2/2)

Example:

If the User Enters:

First point: (0, 0)

Second point: (1, 1)

The midpoint would be:

(0+1/2, 0+1/2)=(0.5, 0.5)


How does Input Work:

We can read a point like (2.3,9) with this line:

cin >> left_paren >> x >> comma >> y >> right_paren;

Here:

x gets 2.3

y gets 9

Thus, other characters ( ( , ) ) are captured in char variables, just to allow format.

C++ Program Code:

#include <iostream>

using namespace std;

int main()

double x1, y1, x2, y2; // To store the x and y values of both points

char left_paren, comma, right_paren; // To store the symbols from input

// Ask the user for the first point

cout << "Please enter the first point: ";

cin >> left_paren >> x1 >> comma >> y1 >> right_paren;

// Ask the user for the second point

cout << "Please enter the second point: ";

cin >> left_paren >> x2 >> comma >> y2 >> right_paren;

// Calculate the midpoint

double mid_x = (x1 + x2) / 2;

double mid_y = (y1 + y2) / 2;


// Show the result

cout << "The midpoint of (" << x1 << "," << y1 << ") and (" << x2 << "," << y2 << ") is ("

<< mid_x << "," << mid_y << ")" << endl;

Output Example:

Please enter the first point: (0,0)

Please enter the second point: (1,1)

The midpoint of (0,0) and (1,1) is (0.5,0.5)

26. Table 4.7 lists the Calorie contents of several foods. Running or walking
burns off about 100 Calories per mile. Write a C++ program that requests
three values from the user: the number of bean burritos, salads, and shakes
consumed (in that order). The program should then display the number of
miles that must be run or walked to burn off the Calories represented in that
food. The program should run as follows (the user types in the 3 2 1): Number
of bean burritos, bowls of salad, and milkshakes eaten? 3 2 1 You ingested
1829 Calories You will have to run 18.29 miles to expend that much energy
Observe that the result is a floating-point value, so you should use floating-
point arithmetic to com pute the answers for this problem

➤ Answer:

We have to written a program that:

1. Asks the user how many bean burritos, salads, and milkshakes they ate.
2. Calculates the total calories from those items.
3. Figures out how many miles the person needs to run or walk to burn off those calories.

Calories per item from Table 4.7:


Food Calories
Bean burrito 357
Food Calories
Salad w/ dressing 185
Milkshake 388

Calories burned per mile:

 Running or walking burns 100 calories per mile.

How to calculate:

If the user eats:

 3 burritos
 2 salads
 1 milkshake

We calculate total calories like this:

Total Calories = (3 × 357) + (2 × 185) + (1 × 388) = 1829

Miles = 1829 / 100 = 18.29 miles

C++ Program:
#include <iostream>
using namespace std;
int main()
{
int burritos, salads, shakes;

// Ask for input


cout << "Number of bean burritos, bowls of salad, and milkshakes eaten? ";
cin >> burritos >> salads >> shakes;

// Calories per item


const int CAL_BURRITO = 357;
const int CAL_SALAD = 185;
const int CAL_SHAKE = 388;

// Calculate total calories


int totalCalories = (burritos * CAL_BURRITO) + (salads * CAL_SALAD) + (shakes *
CAL_SHAKE);

// Calculate miles (use floating point division)


double miles = totalCalories / 100.0;

// Display results
cout << "You ingested " << totalCalories << " Calories" << endl;
cout << "You will have to run " << miles << " miles to expend that much energy" << endl;

Example Run:
Number of bean burritos, bowls of salad, and milkshakes eaten? 3 2 1
You ingested 1829 Calories
You will have to run.

You might also like