Docsity

C++ Programming Practice Exercises: Variables, Operators, Loops, and Debugging, Study notes of Computer Science

Toggle sidebar
bg1
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 5annualReceiptsNY;
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
1. ❌ False - Reserved words cannot be used as variable names.
2. ❌ False - The main function must be named main(), not
Main().
3. ❌ False - The char data type stores a single character, not
multiple characters.
4. ❌ False - A syntactically correct program can still have logical
errors.
5. ❌ False - The cin >> operator does not read whitespace, tabs,
or newline characters unless explicitly handled.
Q7. Compute the value of expressions.
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

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

  1. ❌ False - Reserved words cannot be used as variable names.
  2. ❌ False - The main function must be named main(), not Main().
  3. ❌ False - The char data type stores a single character, not multiple characters.
  4. ❌ False - A syntactically correct program can still have logical errors.
  5. ❌ 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

  1. x += 5; → x = 9 + 5 = 14
  2. x *= y; → x = 9 * 4 = 36
  3. x %= 2; → x = 9 % 2 = 1
  4. 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

  1. ❌ True - Identifiers cannot start with a digit.
  2. ❌ True - cin.get(XXX); requires a variable name.
  3. ❌ False - The char data type stores 1 byte , not 4 bytes.
  4. ❌ False - A program may have runtime errors even if it is syntactically correct.
  5. ❌ 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.
  1. -42 + 50 % 17
    • 50 % 17 = 16, so -42 + 16 = -
    • ❌ Result: -
  2. 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:

  1. cin >> X; → Reads 999
  2. cin.ignore(500, '\n'); → Ignores rest of the first line ( 111 444 )
  3. cin >> Y >> Z; → Reads 666 into Y , 555 into Z ❌ Final value of Z : Z = 555

Q8. Header files needed for functions

  1. #include → Required forcout
  2. #include → Required forsqrt()
  3. #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:

  1. Infinite loop : a > 0 never changes, so the loop runs forever.
  2. Variable num is redeclared in every iteration, which is inefficient.
  3. 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:

  1. The condition n != 15 skips 14 , causing an incorrect loop termination.
  2. 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