Download C++ Programming Practice Exercises: Variables, Operators, Loops, and Debugging and more Study notes Computer Science in PDF only on Docsity!
Practice #1 - Detailed Solutions
Q1. Declare an int variable named count, and a char
variable named letter.
In C++, variables are declared using their data type followed by their name. Solution: int count; // Declares an integer variable named count char letter; // Declares a character variable named letter
Q2. Assign values to variables.
a) Assign the value 10 to the int variable x. int x = 10 ; b) Assign the character โGโ to the char variable y. char y = 'G';
Q3. Fix the incorrect syntax in a variable declaration.
The given code: double 5 annualReceiptsNY; is incorrect because variable names cannot start with a number. Corrected version: double annualReceiptsNY5;
Q4. Identify valid and invalid identifiers.
Variable names must start with a letter or underscore and cannot contain special characters except underscores.
- a) item#1 - โ Invalid (# is not allowed)
- b) SqFt - โ Valid
- c) bin-2 - โ Invalid (- is not allowed)
- d) PAY_DAY - โ Valid
- e) num5 - โ Valid
Q5. Write three output statements.
To print three separate lines, we use cout and endl. Solution: cout << "The moon" << endl; cout << "Is" << endl; cout << "blue." << endl;
Q6. True/False Statements
- โ False - Reserved words cannot be used as variable names.
- โ False - The main function must be named main(), not Main().
- โ False - The char data type stores a single character, not multiple characters.
- โ False - A syntactically correct program can still have logical errors.
- โ False - The cin >> operator does not read whitespace, tabs, or newline characters unless explicitly handled.
Q7. Compute the value of expressions.
Given: int result; a) result = 7 / 3 + 2 ;
- Integer division truncates decimal part โ 7 / 3 = 2
- 2 + 2 = 4
- โ Result: 4 b) result = 2 + 7 * 5 ;
- Multiplication has higher precedence โ 7 * 5 = 35
- 2 + 35 = 37
- โ Result: 37 c) result = 17 + ( 21 % 6 ) * 2 ;
- 21 % 6 = 3 (Modulus operation)
- 3 * 2 = 6
- 17 + 6 = 23
- โ Result: 23 d) result = static_cast(4.5 + 2.6 * 0.5);
- 2.6 * 0.5 = 1.
- 4.5 + 1.3 = 5.
- static_cast(5.8) = 5 (Casts to integer)
- โ Result: 5
Q8. Compute new values for x.
Given: x = 9, y = 4
- x += 5; โ x = 9 + 5 = 14
- x *= y; โ x = 9 * 4 = 36
- x %= 2; โ x = 9 % 2 = 1
- x += x * y; โ x = 9 + (9 * 4) = 45
Q9. Fix errors in the program.
The given program has multiple errors:
- Main() should be main()
- Missing data type for number1 and number
- Incorrect use of >> for output (should be <<)
- Missing return 0; Fixed version: #include using namespace std; int main() { int number1, number2, product; cout << "Enter a number: ";
Practice #2 - Detailed Solutions
Q1. Compute variable values after input.
a) Given input: 25 13 7 Executed as: cin >> int1 >> int2 >> int3; โ Solution: int1 = 25, int2 = 13, int3 = 7 b) Given input: 24.5 A 32 Executed as: cin >> var1 >> ch1 >> var2;
- var1 is int, so 24.5 truncates to 24
- ch1 = 'A'
- var2 = 32 โ Solution: var1 = 24, ch1 = 'A', var2 = 32
Q2. The newline character.
- A. You generate a newline character from the keyboard by pressing Enter.
- B. You generate a newline character in program output using: cout << "\n"; // Prints newline
OR
cout << endl; // Prints newline
Q3. Input statement for storing characters
Solution: char ch1, ch2, ch3; cin >> ch1; // Reads 'A' cin.get(ch2); // Reads the first blank space cin.get(ch3); // Reads the second blank space
Q4. True/False Questions
- โ True - Identifiers cannot start with a digit.
- โ True - cin.get(XXX); requires a variable name.
- โ False - The char data type stores 1 byte , not 4 bytes.
- โ False - A program may have runtime errors even if it is syntactically correct.
- โ True - The modulus operator % only works with integers.
Q5. C++ expressions.
Given Algebraic Expressions โConvert to C++:
Solution: y = pow(x, 5 );
Solution: c = pow(m, 4 ) / (pow(p, 7 ) * pow(q, 5 ));
Solution: x = (a + 15 ) / ( 4 * b);
Q6. Evaluate expressions.
Given Expressions:
- 5.0 + sqrt(5 * 5 โ 4 * 6 ) / 2.
- Evaluates to: -5.
- -42 + 50 % 17
- 50 % 17 = 16, so -42 + 16 = -
- โ Result: -
- 13 % 3 * 6 - 7
- (1 * 6) - 7 = -
- โ Result: -
Q7. Determining the value of variable Z from input
Given input: 999 111 444 666 555 777 333 888 222 Given code: cin >> X; cin.ignore( 500 , '\n'); cin >> Y >> Z; โ Step-by-step execution:
- cin >> X; โ Reads 999
- cin.ignore(500, '\n'); โ Ignores rest of the first line ( 111 444 )
- cin >> Y >> Z; โ Reads 666 into Y , 555 into Z โ Final value of Z : Z = 555
Q8. Header files needed for functions
- #include โ Required forcout
- #include โ Required forsqrt()
- #include โ Required forsetw()
Q9. Fixing incorrect if-else statement
Given code: cout << "Enter n: "; cin >> n; If (n < 0 ) cout << "That is negative. Try again." << endl; cin >> n; else if cout << "Value of n = " << n << endl; โ Fixed version: cout << "Enter n: "; cin >> n; if (n < 0 ) { cout << "That is negative. Try again." << endl; cin >> n; } else {
Practice #3 - Detailed Solutions
Q1. Find and explain errors in the given code.
Given code: int a = 1 ; while (a > 0 ) { int num = 5 ; cout << num << endl; } cout << a << endl; Errors:
- Infinite loop : a > 0 never changes, so the loop runs forever.
- Variable num is redeclared in every iteration, which is inefficient.
- The cout << a; statement is unreachable because of the infinite loop. Fixed version: int a = 1 ; while (a > 0 ) { int num = 5 ; cout << num << endl; a--; // Breaking the infinite loop } cout << a << endl;
Q2. Debugging a loop for even numbers between 1 and 15
Given code: int n = 2 ; while (n != 15 ) { n = n + 2 ; cout << n << " "; } Errors:
- The condition n != 15 skips 14 , causing an incorrect loop termination.
- The first number printed is 4 , skipping 2 (the intended starting point). Output of Incorrect Code: 4 6 8 10 12 14 16 16 is outside the expected range. Fixed Code: int n = 2 ; while (n <= 14 ) { cout << n << " "; n += 2 ; // Increment by 2 } โ Output: 2 4 6 8 10 12 14
Q3. Analyzing a loop with user input
Given input: 25 10 6 - 1 Given code: int number, sum = 0 ; cin >> number; while (number != -1) {
cin >> number; sum = sum + number; } cout << sum << endl; Error:
- The first value is ignored because sum = sum + number happens after reading the next number.
- The -1 value is incorrectly added to the sum before loop termination. Corrected Code: int number, sum = 0 ; cin >> number; while (number != -1) { sum = sum + number; // Fix: Sum the number BEFORE reading the next input cin >> number; } cout << sum << endl; โ Correct Output: 41 // (25 + 10 + 6)
Q4. Convert a for-loop to a while-loop
Given for-loop: for (int i = 20 ; i > 10 ; i--) { cout << i * i; } Equivalent while-loop: int i = 20 ; while (i > 10 ) { cout << i * i; i--; }
Q5. Convert a while-loop to a do-while loop
Given while-loop: int x = 1 ; while (x > 0 ) { cout << "Enter a number: "; cin >> x; } Equivalent do-while loop: int x; do { cout << "Enter a number: "; cin >> x; } while (x > 0 ); โ Why?
- A do-while loop ensures at least one execution , unlike a while loop.
Q6. Write a for-loop for countdown 10 to 1
Solution: for (int i = 10 ; i >= 1 ; i--) { cout << i; if (i > 1 ) cout << ", "; } cout << endl; โ Output: 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1