Strings, Boolean expressions#
Strings#
#include <stdio.h>
#include <string.h>
#define STR_SIZE 100
auto firstName = "Ada";
auto lastName = "Lovelace";
char fullName[STR_SIZE];
// Multiline string with interpolation (Raw string literals)
auto table = R"(
+---+---+---+---+
| x | | x | |
| y | | | |
+---+---+---+---+
)";
int main() {
// Length of string
printf("First name length %lu\n", strlen(firstName));
// Comparing
if (strcmp(firstName, lastName) == 0)
puts("Same word");
else
puts("Different names");
// Simple concatenation
strcat(fullName, firstName);
strcat(fullName, " ");
strcat(fullName, lastName);
puts(fullName);
// More readable using a format string
sprintf(fullName, "%s %s", firstName, lastName);
puts(fullName);
puts(table);
}
Activity 16
Peek into string.h
in the standard library. Select function/s which can be useful for finding a string in an array of strings.
3 min
Boolean expressions#
The questions we had previously are in fact boolean expressions.
- Boolean expression
an expression that produces a Boolean value. Such a value is either true or false.
Examples#
// Simple boolean comparisons
bool isEqual = 5 == 5; // true
bool isNotEqual = 5 != 5; // false
bool isGreater = 10 > 5; // true
bool isLess = 5 < 10; // true
bool isGreaterThanEqual = 5 >= 5; // true
bool isLessThanEqual = 10 <= 5; // false
// Combination operators
bool andCondition = 5 > 3 && 10 < 20; // true (both must be true)
bool orCondition = 5 > 10 || 3 < 4; // true (enough if one is true)
bool notCondition = !(5 == 5); // false (negation)
int main() {
// Practical example: Check if a number is within a range
auto number = 7;
bool isInRange = number > 5 && number < 10; // true
}
We can use the Boolean expression on the right of the equal sign =
in the if
statement.
Activity 17
Which of the following are Boolean expressions and evaluate to false
, assuming the following initialization code? The statements in the choices do not affect others.
auto t = true;
auto f = false;
auto c = 3;
auto i = 9;
auto k = 11;
Choices:
t == f
t = f
i >= c && k > i
!t
k != 11
10 < c || c <= 20