Rounding Decimal Values to Integers with a Simple Trick
double currentVal = 1.0;
currentVal += 2.6;
currentVal++;
currentVal * 5;
currentVal = (int)(currentVal + 0.5);
Walkthrough of the execution steps:
double currentVal = 1.0; // currentVal equals 1.0
currentVal += 2.6; // currentVal becomes 3.6
currentVal++; // currentVal increments to 4.6
currentVal * 5; // currentVal remains 4.6 (result is not stored)
currentVal = (int)(currentVal + 0.5); // currentVal is now 5
Adding 0.5 before casting to int is a practical trick for rounding decimal values to the nearest integer. For positive numbers, this ensures any fractional part of 0.5 or higher pushes the value to the next whole number, which is retained when the decimal portion is truncated during the cast.
Controlling Output Alignment with printf Format Specifiers
The minus sign (-) in a printf format specifier left-aligns the output, padding the right with spaces. By default, output is right-aligned, with spaces added to the left.
printf("%5d", 123); // Output: 123 (two leading spaces)
printf("%-5d", 123); // Output: 123 (two trailing spaces)
The Critical Role of Short-Circuit AND (&&) in Expressions
Consider this expression:
totalCount != 0 && totalSum / totalCount
The && operator uses short-circuit evaluation to prevent a division-by-zero error. If totalCount is 0, the left operand (totalCount != 0) is false, so the right operand (totalSum / totalCount) is never evaluated. This safely avoids an invalid operation that would crash the program.
Logical Expression for Leap Year Detection
A year is a leap year if it satisfies either of these conditions: A. Divisible by 4 but not by 100; B. Divisible by 400. The corresponding C expression to check for a leap year is:
(currentYear % 4 == 0 && currentYear % 100 != 0) || (currentYear % 400 == 0)
The || operator combines the two conditions, so the expression returns true if either condition A or B is met.
Functionality of a Space-Skipping Loop
What does this code accomplish?
char inputChar;
while ((inputChar = getchar()) == ' ') {
; // Empty loop body
}
This loop reads characters from standard input and discards all leading space characters. It continues reading until it encounters a non-space character, at which point the loop exits.
Behavior of a do-while Input Loop
Assuming a dynamic character array is defined prior to this code in the main() function, what is its purpose?
char userInput[100]; // Example dynamic array
do {
cout << "Enter a number, press Enter to continue: ";
cin >> userInput;
} while (getchar() != '\n');
The do-while loop ensures the user is prompted for input at least once. After reading the input with cin, getchar() checks for the newline character. If found, the loop repeats, allowing the user to enter another number after pressing Enter.
Infinite Loop Behavior
What happens when this program runs?
#include <stdio.h>
int main() {
while (1)
;
return 0;
}
The program enters an infinite loop. The condition 1 is always true, so the loop runs indefinitely. To terminate it, use Ctrl + C on Unix-like systems or end the process via Task Manager on Windows.
Loop Entry Condition for while (!condition)
In this code snippet:
// ...
while (!condition) {
// Loop body
}
// ...
The loop executes its body only when condition is 0 (false). Experienced C/C++ developers favor this concise form over while (condition == 0) for improved readability.
Key Difference Between do-while and while Loops
A do-while loop executes its body first, then checks the loop condition. In contrast, a while loop checks the condition before executing the body. This means the do-while loop's body will always run at least once, regardless of whether the initial condition is true or false.
Output Range of a signed char Loop
What values does this code print?
#include <stdio.h>
int main() {
signed char i = 0;
while (i <= 0) {
printf("%d ", i);
i = i - 1;
}
return 0;
}
The code prints all integers from 0 down to -128. A signed char has a range of -128 to 127. When i is -128, subtracting 1 causes an underflow, wrapping around to 127, which violates the loop condition i <= 0 and exits the loop.
Why getchar() Returns int Instead of char
The getchar() function returns an int rather than a char to properly handle the end-of-file (EOF) marker, typically defined as -1. Since char can be either signed or unsigned depending on the compiler, an unsigned char cannot store negative values like -1. Using int (signed by default) ensures EOF can be correctly represented and detected.
Comparison of putchar() and getchar()
putchar(c): Outputs a single character to the terminal. The argumentccan be acharorintvariable, as long as it corresponds to a valid ASCII character.getchar(): Reads a single character from standard input. It takes no arguments, and its return value is the character read (as anint, including the EOF marker).
Case Swapping with Cahracter I/O Functions
What does this code do?
int inputChar;
while ((inputChar = getchar()) != '\n') {
if (inputChar >= 'A' && inputChar <= 'Z') {
inputChar = inputChar - 'A' + 'a';
} else if (inputChar >= 'a' && inputChar <= 'z') {
inputChar = inputChar - 'a' + 'A';
}
putchar(inputChar);
}
putchar('\n');
This code reads a line of input, swaps the case of all alphabetic characters (uppercase to lowercase and vice versa), and prints the modified line. Non-alphabetic characters remain unchanged.
Converting String Digits to Integers
To convert a string of digits to an integer, iterate over each character in the string. For each digit character, subtract the ASCII value of '0' to get its integer equivalent. Build the total number by multiplying the current total by 10 and adding the new digit.
Converting an Infinite for Loop to while
This for loop represents an infinite loop:
for (;;)
;
The equivalent while loop is:
while (1)
;
Both loops run indefinitely since their conditions are always true.
Converting a while Loop to for Format
This while loop reads input until a newline is encountered and prints each character:
char inputChar;
while ((inputChar = getchar()) != '\n') {
printf("%c", inputChar);
}
The equivalent for loop (though less intuitive for this use case) is:
char inputChar;
for (; (inputChar = getchar()) != '\n'; ) {
printf("%c", inputChar);
}
Most developers prefer the while loop here because there’s no initialization or increment step required.
Validating Input with scanf_s()
The scanf_s function returns the number of successfully read items. To validate that a single input value was read correctly, check if the return value equals 1. This ensures the input matches the expected format, helping catch invalid entries early.
Difference Between while(i++) and while(++i)
while(++i): The variableiis incremented first, then the new value is used as the loop condition.while(i++): The current value ofiis checked first, theniis incremented after the condition evaluation.
Key differences when i starts as a negative number (e.g., int i = -10):
- Loop count:
while(++i)runs 10 times (i goes from -10 to -1, then increments to 0 which fails the condition).while(i++)runs 11 times (i goes from -10 to 0, increments to 1 after the final condition check). - Final value of
i: Afterwhile(++i),iis 0. Afterwhile(i++),iis 1. Whenistarts at 0,while(++i)runs infinitely (i becomes 1 and stays positive), whilewhile(i++)never runs (the initial condition checks 0, which is false).