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

Prelab5 String+Operators

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Prelab5 String+Operators

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

CS 100 Computational Problem Solving

Prelab 5: Strings and Operators


CS 100 - Fall 24

1. Strings
1.1 Objectives

➔ Become familiar with string declaration, initialization, and manipulation using the standard
library in C++.
➔ Understand basic string functions like concatenation, input handling, and common errors.

1.2 Pre Lab Reading

In C++, strings are part of the Standard Library and can be manipulated using built-in functions.
Below are the most common string operations.

1.2.1 String Declaration and Initialization

You can declare strings using std::string. Uninitialized strings are empty by default.

Example:

1.2.2 String Constructors

There are multiple ways to create strings:

● Fill Constructor: Initializes a string with multiple copies of a character.

● Substring Constructor: Initializes a string from a substring of another string.


CS 100 Computational Problem Solving

1.2.3 String Concatenation

You can concatenate strings using the + operator.

1.2.4 String Input

Use cin to read strings, but it only reads up to the first space. To read an entire line, use
getline().

However, mixing cin and getline() can cause issues due to how each function handles the
newline character.

● cin: Reads input until it encounters a space or newline but leaves the newline in the
buffer.
● getline(): Reads input until a newline character (\n) is encountered, which may
cause it to read an empty line if there's leftover input from a previous cin.

To avoid this issue when switching between cin and getline(), use cin.ignore() to
discard the leftover newline character:
CS 100 Computational Problem Solving

1.2.5 String Functions


Length: Use length() to get the number of characters in a string.

Substring: Use substr() to extract a part of a string. You can specify both the starting
position and the length of the substring.

● Extracting from a Specific Position to the End: If you specify the starting position
only, the substring will include all characters from that position to the end of the string.

● Extracting the Entire String: If you omit both parameters, you get a copy of the entire
string. Not much of a substring!

● Position Beyond String Length: If the starting position exceeds the length of the string,
an empty string is returned.
CS 100 Computational Problem Solving

1.2.6 Common Errors


Concatenating literal strings directly is not allowed.

1.3 Practice

1.3.1: String Declaration and Initialization

1. Declare firstName, lastName, and fullName.


2. Initialize firstName with "John" and lastName with "Doe".

3. Combine them to create fullName.


4. Print fullName along with the lengths of firstName, lastName and

fullName.
5. Extract the lastName from fullName.
CS 100 Computational Problem Solving

1.3.2: Handling Mixed Input

1. Ask the user to input a number and store it using cin.


2. Ask the user to input their full name using getline().
3. Print both the number and the full name.
4. Discuss how cin and getline() handle input differently and why cin.ignore()
is needed. Try to run the code without using cin.ignore().
CS 100 Computational Problem Solving

1.4 Summary
String Operations
CS 100 Computational Problem Solving

2. Operators
2.1 Objectives

➔ Understand the different types of operators in C++ and their use.


➔ Learn about operator precedence and associativity.

2.2 Pre lab Reading

Operators perform operations on variables. Below is an overview of common operator types in


C++.

2.2.1 Arithmetic Operators

Arithmetic operators allow you to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus (remainder).

2.2.2 Increment and Decrement Operators

Increment and decrement operators increase or decrease a value by one. The prefix form changes
the value before the operation, while the postfix form changes it afterward.
CS 100 Computational Problem Solving

2.2.3 Assignment Operators

Assignment operators are used to assign values to variables, but they can also perform arithmetic
while assigning the result back to the variable.

2.2.4 Relational Operators

Relational operators compare two values and return a boolean value (true or false). They are
commonly used in conditional statements.

List of Relational Operators:

● == : Equal to
● != : Not equal to
● > : Greater than
● < : Less than
● >= : Greater than or equal to
● <= : Less than or equal to

2.2.5 Logical Operators

Logical operators are used to combine multiple conditions.

● && (AND) – Returns true if both operands are true.


● || (OR) – Returns true if at least one operand is true.
● ! (NOT) – Reverses the boolean value.
CS 100 Computational Problem Solving

2.2.6 Bitwise Operators

Bitwise operators operate on the binary representation of numbers.

Common Bitwise Operators:

1. AND (&): Sets each bit to 1 if both bits are 1.


2. OR (|): Sets each bit to 1 if at least one of the bits is 1.
3. XOR (^): Sets each bit to 1 if only one of the bits is 1 (but not both).
4. NOT (~): Inverts all the bits (flips 0 to 1 and 1 to 0).
5. Left Shift (<<): Shifts the bits of the number to the left, filling with 0s on the right.

6. Right Shift (>>): Shifts the bits of the number to the right, discarding bits shifted off and
filling with 0s on the left.

2.2.7 Conditional (Ternary) Operator

The ternary operator is a shorthand for if-else statements. The condition is evaluated first, and if
it returns true, the first expression is executed, and if it returns false, the second expression is
executed. The syntax of the ternary operator is as follows:
CS 100 Computational Problem Solving

2.2.8 Unary Operators

Unary operators act on a single operand. Examples include unary plus (+), minus (-), increment
(++), and decrement (--).

2.2.9 Sizeof Operator

The sizeof operator returns the size (in bytes) of a data type or variable.

2.3 Operator Precedence and Associativity

Operators in C++ follow a specific precedence that determines the order in which operations are
performed. For example, multiplication and division have higher precedence than addition and
subtraction.

Associativity defines the direction in which an expression is evaluated when operators have the
same precedence (left-to-right or right-to-left).

2.4 Punctuators in C++

Punctuators such as parentheses (), braces {}, semicolons ;, and brackets [] play a significant role
in grouping and terminating expressions or functions.

Example:

● Parentheses are used for function calls: func().


● Braces are used to define the body of loops or functions: {}.
CS 100 Computational Problem Solving

2.5 Practical Examples and Exercises

1. Arithmetic Operations
Write a program that performs addition, subtraction, multiplication, division, and
modulus on two integers.
2. Logical and Relational Operators
Write a program that compares two integers using relational and logical operators, then
outputs the result.
3. Bitwise Operations
Write a program that uses bitwise shifting to multiply and divide a number by powers of
2.

Practice Question

Task 1:

1. Declare three integers: p, q, and r.


2. Prompt the user to enter values for p, q, and r.
3. Perform a series of operations:
○ Calculate the sum of p and q.
○ Calculate the product of p and r.
○ Check if the sum of p and q is greater than the left shift of r by 1.
○ Calculate the bitwise AND and OR of p and q.
○ Create a final expression that combines these results to determine if the product is
greater than the bitwise AND result.
4. Print the results of all calculations and the final condition.
CS 100 Computational Problem Solving

Task 2: Multiple Increment/Decrement Operators:

● Declare three integers: a, b, and c.


● Initialize them with values: a = 5, b = 10, and c = 15.
● Perform the following series of operations in one line of code using both prefix and
postfix increment/decrement operators.

int result = ++a + b-- + --c + a++;

● Print the final values of a, b, and c after the operation, along with the result.
CS 100 Computational Problem Solving

Explanation:

● ++a increments a to 6 and uses 6 in the expression.


● b-- uses b (which is 10) in the expression, then decrements b to 9.
● --c decrements c to 14 and uses 14 in the expression.
● a++ uses a (which is still 6 at this point) in the expression, then increments a to 7
after the expression.

Task 3: Pre/Post Increment with Logical AND:

● Declare two integers: x and y.


● Initialize them with values: x = 2 and y = 4.
CS 100 Computational Problem Solving

● Write the following expression that combines pre-increment and post-increment with the
logical AND (&&) operator.

bool condition = (++x > 2) && (y++ < 5);

● Print the final values of x and y along with the result of the condition.

Explanation:

● ++x increments x to 3 and checks if x > 2 (which is true).


● y++ uses y (which is 4) in the comparison y < 5 (which is true), then increments
y to 5 after the check.

Since both conditions (++x > 2 and y++ < 5) are true, the overall result of the condition is
true.
CS 100 Computational Problem Solving

2.6 Common Mistakes and Best Practices

● Be careful not to confuse logical (&&, ||) and bitwise (&, |) operators.
● Use parentheses to clarify complex expressions and avoid unintended precedence issues.
● Avoid overusing the ternary operator, as it can reduce code readability in complex
cases.

You might also like