cp assignment 1.0
cp assignment 1.0
➤ 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'
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 .
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.
➤ Operator precedence informs us which operation is performed first when there are no
parentheses.
* (multiplication)
/ (division)
+ (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.
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:
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
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
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):
long – Holds larger whole numbers (typically 4 or 8 bytes, depending on the machine).
Final Order:
char < int < long < float < double.
➤ 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
➤ 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
➤ 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
(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
(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
(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
(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
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.
If you attempt to nest one block comment within another, it will result in an error.
➤ 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.
➤ 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.
➤ 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:
➤ 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?
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".
y1 = ++x1;
y2 = x2++;
y1 = ++x1; // pre-increment
y2 = x2++; // post-increment
Now,
Line 1:
Line 2:
y1 = ++x1;
Line 3:
y2 = x2++;
Output:
outputs: 3 3
std::cout << y1 << " " << y2 << '\n';
outputs: 3 2
Final Output:
33
32
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.
33
32
#include <iostream>
int main()
double C, r;
const double PI = 3.14159; // Formula for the area of a circle given its radius
(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:
#include <iostream>
int main()
double C, r;
cout >> "Please enter the circle's radius: "; // Error in syntax
(a) Answer:
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 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
#include <iostream>
int main()
double C, r;
cin >> r;
C = 2 * PI * r;
Write a C++ program that receives two mathematical points from the user
and computes and prints their midpoint.
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
double x, y;
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:
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++.
( 𝑥1+𝑥2/2, 𝑦1+𝑦2/2)
Example:
Here:
x gets 2.3
y gets 9
Thus, other characters ( ( , ) ) are captured in char variables, just to allow format.
#include <iostream>
int main()
double x1, y1, x2, y2; // To store the x and y values of both points
cout << "The midpoint of (" << x1 << "," << y1 << ") and (" << x2 << "," << y2 << ") is ("
<< mid_x << "," << mid_y << ")" << endl;
Output Example:
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:
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.
How to calculate:
3 burritos
2 salads
1 milkshake
C++ Program:
#include <iostream>
using namespace std;
int main()
{
int burritos, salads, shakes;
// 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.