Podcast
Questions and Answers
Given the ANSI C standard, what is the expected behavior when an identifier exceeds the compiler's limit of significant characters?
Given the ANSI C standard, what is the expected behavior when an identifier exceeds the compiler's limit of significant characters?
- The compiled code may exhibit undefined behavior. (correct)
- The preprocessor substitutes the identifier with a predefined macro.
- The linker will produce an error due to symbol collision.
- The compiler truncates the identifier and issues a warning.
In C, the identifiers KmsPerMile
and KMS_PER_MILE
are semantically equivalent and can always be used interchangeably.
In C, the identifiers KmsPerMile
and KMS_PER_MILE
are semantically equivalent and can always be used interchangeably.
False (B)
A variable is assigned the value of $10.50
. Write the assignment operator in C.
A variable is assigned the value of $10.50
. Write the assignment operator in C.
This expression is invalid. C language only accepts digits, letters, and underscores.
Which of the following arithmetic operations involving floating-point numbers is most susceptible to precision loss and why?
Which of the following arithmetic operations involving floating-point numbers is most susceptible to precision loss and why?
In C, the expression x+++++y
is syntactically ______, due to the greedy nature of token parsing.
In C, the expression x+++++y
is syntactically ______, due to the greedy nature of token parsing.
When using prefix increment/decrement operators in C, what subtle side effect can occur within complex expressions that might lead to unexpected behavior?
When using prefix increment/decrement operators in C, what subtle side effect can occur within complex expressions that might lead to unexpected behavior?
In C, the relational operators <
, >
, <=
, >=
, ==
, and !=
always return either 0
or 1
, strictly adhering to the Boolean interpretation of false and true.
In C, the relational operators <
, >
, <=
, >=
, ==
, and !=
always return either 0
or 1
, strictly adhering to the Boolean interpretation of false and true.
Describe a scenario in C where the expression a == b
evaluates to true
, but the memory representations of variables a
and b
are fundamentally different. Provide a specific type for a
and b
to exemplify the situation.
Describe a scenario in C where the expression a == b
evaluates to true
, but the memory representations of variables a
and b
are fundamentally different. Provide a specific type for a
and b
to exemplify the situation.
Consider the logical expression (x && y) || (x && z)
in C. Under what specific conditions will the side effects in y
and z
be guaranteed not to occur?
Consider the logical expression (x && y) || (x && z)
in C. Under what specific conditions will the side effects in y
and z
be guaranteed not to occur?
In C, the !
operator, when applied to a pointer, returns 1
if the pointer is ______ and 0
otherwise.
In C, the !
operator, when applied to a pointer, returns 1
if the pointer is ______ and 0
otherwise.
Match the following C operators with their corresponding precedence level (lower number indicates higher precedence):
Match the following C operators with their corresponding precedence level (lower number indicates higher precedence):
Consider the C expression $a = b+++c*d;
. How does the compiler resolve this expression according to operator precedence and associativity rules?
Consider the C expression $a = b+++c*d;
. How does the compiler resolve this expression according to operator precedence and associativity rules?
In C, the math library function pow(x, y)
always returns a valid numerical value, even when x
is negative and y
is a non-integer.
In C, the math library function pow(x, y)
always returns a valid numerical value, even when x
is negative and y
is a non-integer.
Illustrate a scenario where using the floor()
function could lead to incorrect results when performing monetary calculations that require precise rounding to two decimal places.
Illustrate a scenario where using the floor()
function could lead to incorrect results when performing monetary calculations that require precise rounding to two decimal places.
Given the quadratic formula $Root = (-b ± \sqrt{b^2 - 4ac}) / (2a)$, which potential issue should be accounted for when implementing this formula in C using floating-point arithmetic?
Given the quadratic formula $Root = (-b ± \sqrt{b^2 - 4ac}) / (2a)$, which potential issue should be accounted for when implementing this formula in C using floating-point arithmetic?
According to the C standard, if the return type of main()
is declared as void, any attempt to use exit()
with a status value is considered ______.
According to the C standard, if the return type of main()
is declared as void, any attempt to use exit()
with a status value is considered ______.
When translating an English condition such as 'x and y are greater than z' into C code, which of the following expressions correctly represents this condition?
When translating an English condition such as 'x and y are greater than z' into C code, which of the following expressions correctly represents this condition?
In the context of C programming, the omission of braces {}
around a single-line statement following an if
condition always leads to a compile-time error.
In the context of C programming, the omission of braces {}
around a single-line statement following an if
condition always leads to a compile-time error.
Describe a potential pitfall when using nested if-else
statements without proper indentation and how it could lead to unexpected program behavior.
Describe a potential pitfall when using nested if-else
statements without proper indentation and how it could lead to unexpected program behavior.
Under what circumstance when writing an if-else statement is a compile-time error thrown?
Under what circumstance when writing an if-else statement is a compile-time error thrown?
When using the switch
statement in C, the ___
keyword is essential at the end of each case
block to prevent fall-through.
When using the switch
statement in C, the ___
keyword is essential at the end of each case
block to prevent fall-through.
In a switch
statement in C, what is the key distinction in behavior between using a char
data type and a double
data type for the switch
expression?
In a switch
statement in C, what is the key distinction in behavior between using a char
data type and a double
data type for the switch
expression?
In C, it is always preferable to use a switch
statement instead of a series of nested if-else
statements when handling multiple alternatives, due to the switch
statement's inherently faster execution speed.
In C, it is always preferable to use a switch
statement instead of a series of nested if-else
statements when handling multiple alternatives, due to the switch
statement's inherently faster execution speed.
Explain a scenario in C where using a series of if
statements is more appropriate than a switch
statement and explain why.
Explain a scenario in C where using a series of if
statements is more appropriate than a switch
statement and explain why.
In the absence of a default
case within a switch
statement, if the value of the switch expression doesn't match any of the case
labels, the switch
statement will execute ______ instructions.
In the absence of a default
case within a switch
statement, if the value of the switch expression doesn't match any of the case
labels, the switch
statement will execute ______ instructions.
Given a situation where it's necessary to perform different actions based on several related conditions, what's the MOST efficient and readable coding approach?
Given a situation where it's necessary to perform different actions based on several related conditions, what's the MOST efficient and readable coding approach?
In C, all programming errors—including syntax errors, runtime errors, and logical errors—are always detected and reported by the compiler at compile time.
In C, all programming errors—including syntax errors, runtime errors, and logical errors—are always detected and reported by the compiler at compile time.
Describe a common programming error that involves unintended assignment within a conditional expression and explain how to prevent it.
Describe a common programming error that involves unintended assignment within a conditional expression and explain how to prevent it.
When employing nested if
statements, failure to use proper _______ can cause an else
clause to improperly associate with the wrong if
statement, leading to logical errors.
When employing nested if
statements, failure to use proper _______ can cause an else
clause to improperly associate with the wrong if
statement, leading to logical errors.
Which of the choices correctly calculates compound daily interest on a loan of p dollars over n days?
Which of the choices correctly calculates compound daily interest on a loan of p dollars over n days?
A switch-statement is a lot more general than an if statement.
A switch-statement is a lot more general than an if statement.
You have a lightbulb that can function at 25 Watts, 40 Watts, 60 Watts, 75 Watts, and 100 Watts. You've created two different sets of code, the first implements nested if-if-else statements, and the second uses a switch statement. Which code is more readable and clear?
You have a lightbulb that can function at 25 Watts, 40 Watts, 60 Watts, 75 Watts, and 100 Watts. You've created two different sets of code, the first implements nested if-if-else statements, and the second uses a switch statement. Which code is more readable and clear?
Given that the _____ case is optional, if no other case is equal to the value of the controlling expression, and there is a default case, then default case is executed.
Given that the _____ case is optional, if no other case is equal to the value of the controlling expression, and there is a default case, then default case is executed.
What happens if the lightbulb is not 25 Watts, 40 Watts, 60 Watts, 75 Watts, or 100 Watts in the switch statement?
What happens if the lightbulb is not 25 Watts, 40 Watts, 60 Watts, 75 Watts, or 100 Watts in the switch statement?
Can string values be defined as case labels?
Can string values be defined as case labels?
Please name two more common errors.
Please name two more common errors.
Given the scenario of declaring an int, char, or double variable, only type ______ and type ______ values may be used as case labels. The rest cannot be used.
Given the scenario of declaring an int, char, or double variable, only type ______ and type ______ values may be used as case labels. The rest cannot be used.
Flashcards
Identifier Naming: Case Sensitivity
Identifier Naming: Case Sensitivity
Avoid identifier names that differ only by case to prevent bugs. Example: LETTER, Letter, letter
Identifier name length
Identifier name length
Some compilers have a limit on the length of identifier names. Avoid using names longer than 31 characters.
Shortcut assignment operator
Shortcut assignment operator
Operators that combine an arithmetic operation with an assignment. Example: a += b is equivalent to a = a + b
Prefix increment/decrement
Prefix increment/decrement
Signup and view all the flashcards
Postfix increment/decrement
Postfix increment/decrement
Signup and view all the flashcards
Logical AND (&&) operator
Logical AND (&&) operator
Signup and view all the flashcards
Logical OR (||) operator
Logical OR (||) operator
Signup and view all the flashcards
Logical NOT (!) operator
Logical NOT (!) operator
Signup and view all the flashcards
Control Structures
Control Structures
Signup and view all the flashcards
Compound Statement
Compound Statement
Signup and view all the flashcards
Selection control structure
Selection control structure
Signup and view all the flashcards
Repetition Control Structure
Repetition Control Structure
Signup and view all the flashcards
Condition
Condition
Signup and view all the flashcards
If statement
If statement
Signup and view all the flashcards
If-else statement
If-else statement
Signup and view all the flashcards
Nested if statements
Nested if statements
Signup and view all the flashcards
Switch statement
Switch statement
Signup and view all the flashcards
Break statement (in switch)
Break statement (in switch)
Signup and view all the flashcards
Default case (in switch)
Default case (in switch)
Signup and view all the flashcards
Mistake checking range
Mistake checking range
Signup and view all the flashcards
Study Notes
Identifier Naming Guidelines
- Compliers may only recognize the first 31 characters of an identifier name
- Avoid using identifier names that only differ by case, as they can cause issues in bug detection
- Use meaningful identifiers for clarity
- Use all uppercase for constant macros, as defined using
#define
KMS_PER_MILE
serves as a constantKmsPerMile
orKms_Per_Mile
is a variable
Invalid Identifiers
1Letter
is invalid because it begins with a numberdouble
andint
are invalid because they are reserved wordsTWO*FOUR
,joe’s
, andage#
are invalid because they contain disallowed characters like*
, backtick, and#
Age-of-cat
is invalid because it uses a hyphen instead of an underscore
Valid Identifiers
Age_of_person
,taxRateY2k
, andPrintHeading
are valid
Arithmetic Operators: Shortcut Assignment
Expression | Equivalent Expression |
---|---|
a += b |
a = a + b |
a -= b |
a = a - b |
a *= b |
a = a * b |
a /= b |
a = a / b |
a %= b |
a = a % b |
- Shortcut assignment operators combine an operation with an assignment
- Instead of writing
a = a + 1
, you can writea += 1
Arithmetic Operators: Prefix Form
- Prefix increment and decrement operators increment or decrement the variable before returning the resulting value
int a, b;
a = b = 10;
printf("%d\n", ++a); /* Prints 11 */
printf("%d\n", a); /* Prints 11 */
printf("%d\n", --b); /* Prints 9 */
printf("%d\n", b); /* Prints 9 */
- If
++
comes before the variable, it increments before determining the result
Arithmetic Operators: Postfix Form
- Postfix increment and decrement operators return the original value of the variable before incrementing or decrementing it
int a, b;
a = b = 10;
printf("%d\n", a++); /* Prints 10 */
printf("%d\n", a); /* Prints 11 */
printf("%d\n", b--); /* Prints 10 */
printf("%d\n", b); /* Prints 9 */
Relational Operators
Operator | Meaning |
---|---|
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
== |
Equal |
!= |
Not equal |
Relational Operator Example
Variable | Value |
---|---|
x |
-5 |
power |
1024 |
MAX_POW |
1024 |
y |
7 |
item |
1.5 |
MIN_ITEM |
-999.0 |
mom_or_dad |
'M' |
num |
999 |
SENTINEL |
999 |
Operator | Condition | English Meaning | Value |
---|---|---|---|
<= |
x <= 0 |
x less than or equal to 0 |
1 (true ) |
< |
power < MAX_POW |
power less than MAX_POW |
0 (false ) |
>= |
x >= y |
x greater than or equal to y |
0 (false ) |
> |
item > MIN_ITEM |
item greater than MIN_ITEM |
1 (true ) |
== |
mom_or_dad == 'M' |
mom_or_dad equal to 'M' |
1 (true ) |
!= |
num != SENTINEL |
num not equal to SENTINEL |
0 (false ) |
Logical Operators
&&
represents the AND operator||
represents the OR operator!
represents the NOT operator
Logical Operator: AND
- AND returns
true
only when both operands aretrue
Operand1 | Operand2 | Operand1 && Operand2 |
---|---|---|
false |
false |
false |
false |
true |
false |
true |
false |
false |
true |
true |
true |
- Example:
Salary < 100 && Age >= 35
Logical Operator: OR
- OR returns
true
if at least one operand istrue
| Operand1 | Operand2 | Operand1 ||
Operand2 |
| :------- | :------- | :----------------------- |
| false
| false
| false
|
| false
| true
| true
|
| true
| false
| true
|
| true
| true
| true
|
Logical Operator: NOT
- NOT negates the operand
Operand1 | ! Operand1 |
---|---|
false |
true |
true |
false |
Logical Operator Example
int age, height, weight;
age = 25;
height = 70;
weight = 145;
Expression | Value |
---|---|
!(age < 10) |
true |
!(height > 60) |
false |
`(height > 60) | |
(weight < 180) && (age >= 20) |
true |
`!(height > 60) |
Operator Precedence and Associativity
Precedence (Highest to Lowest) | Operator | Associativity |
---|---|---|
[] () |
Left | |
Postfix ++ -- |
Left | |
Prefix ++ -- sizeof ~ ! + - & * |
Right | |
Casts | Right | |
* / % |
Left | |
+ - |
Left | |
<< >> |
Left | |
< > <= >= |
Left | |
== != |
Left | |
& |
Left | |
^ |
Left | |
| |
Left | |
&& |
Left | |
|| |
Left | |
?: |
Right | |
`= += -= *= /= %= <<= >>= &= ^= | =` | |
, |
Left |
Math Library (math.h)
- The C math library offers predefined math functions
- A function serves as a subprogram for tasks, accepting zero or more inputs (parameters) and producing zero or one output (return value)
- Include the math library using
#include <math.h>
- To use function
sqrt
, usey = sqrt(x);
Common Math Functions
sin(x)
cos(x)
tan(x)
sqrt(x)
pow(x, y)
abs(x)
log(x)
log10(x)
exp(x)
fabs(x)
floor(x)
ceil(x)
Math Library Example: abs()
abs(int)
: Returns the absolute value of an integer
int n = -1234, x;
x = abs(n); // x will be 1234
Math Library Example: floor()
floor(double)
: Rounds down to the nearest integer
double n = 123.54, x;
x = floor(n); // x will be 123.0
Math Library Example: ceil()
ceil(double)
: Rounds up to the nearest integer
double n = 123.54, x;
x = ceil(n); // x will be 124.0
Math Library Example: pow()
pow(double x, double y)
: Calculatesx
to the power ofy
double x = 3.0, y = 2.0, result;
result = pow(x, y); // result will be 9.0
Math Library Example: sqrt()
sqrt(double)
: Calculates the positive square root
double n = 4, x;
x = sqrt(n); // x will be 2.0
Math Library Example: exp()
exp(double)
: Calculates the exponentiale
to the power ofx
double n = 4, x;
x = exp(n); // x will be e^4
Sample Problem: Quadratic Equation Roots
- Goal: Obtain the roots of a quadratic equation given its coefficients
- Equation: ax² + bx + c = 0
- Roots are determined as
(-b ± √(b² - 4ac)) / (2a)
disc = pow(b, 2) - 4 * a * c;
root_1 = (-b + sqrt(disc)) / (2 * a);
root_2 = (-b - sqrt(disc)) / (2 * a);
Control Structures
- These control the flow of execution in programs
- Three primary control structures exist: sequential, selection, and repetition
Control Structures: Sequential Flow
- Statements are executed in the order they appear
- A compound statement or code block groups statements within
{
and}
, dictating sequential flow
{
Statement_1;
Statement_2;
Statement_3;
}
- The function body is a compound statement
C Control Structures: Selection
- Includes statements
if
,if...else
, andswitch
C Control Structures: Repetition
- Includes statements
for
,while
, anddo...while
Selection Control Structure
- Is a control structure that chooses among alternative program statements based on a condition
- A condition is an expression that is
false
(0) ortrue
(1)
Conditions
- Operators: Relational and Logical
<
Less than>
Greater than<=
Less than or equal>=
Greater than or equal==
Equal!=
Not equal!
Not&&
AND||
OR
if
statement
- Is a selection of whether or not to execute a statement, which may be a single statement or a block
if
Syntax
if (Expression)
Statement
- The Statement can be a single, null, or block statement
Terminating Programs with if
int number;
printf("Enter a non-zero number ");
scanf("%d", &number);
if (number == 0) {
printf("Bad input. Program terminated ");
return; // or exit(1);
}
// otherwise continue processing
Writing English Conditions in C
- Ensure the C condition is logically equivalent to the English statement.
- Example
//valid
(x > z) && (y > z)
//invalid
x && y > z
- "x and y are greater than z"
Example if
Statement
- Increase price by adding
taxRate
timesprice
to the original price iftaxCode
is'T'
if (taxCode == 'T')
price = price + taxRate * price;
if-else
Statement
- A selection of whether to execute statement A or statement B. Either can be a single statement or a block
if-else
Syntax
if (Expression)
Statement A
else
Statement B
- Both Statement A and Statement B can be single, null, or block statements
if-else
Alternatives
if (condition) {
compound_statement_1 // if condition is true
} else {
compound_statement_2 // if condition is false
}
Example if-else
Statement
- If A is strictly between 0 and 5, set B equal to 1/A; otherwise, set B equal to A.
if (A > 0 && A < 5)
B = 1 / A;
else
B = A;
Example if-else
Statement: Area & Circumference of a Circle
- Calculate area and circumference of a circle for non-negative radius
if (radius >= 0) {
area = 2 * 3.14 * pow(radius, 2);
cir = 2 * 3.14 * radius;
printf("area=%f, circumference=%f \n", area, cir);
} else
printf("ERROR! Negative values for radius are not allowed.\n");
Note on else
Braces
- In some cases, braces for the else block can be omitted
Braces for else
in an if-else
Statement
- Braces can only be omitted when each clause contains a single statement
if (lastInitial <= 'K')
volume = 1;
else
volume = 2;
printf("Look it up in volume # %d of the phone book", volume);
Nested if
Statements
- Used to code decisions with multiple alternatives.
if (x > 0)
num_pos = num_pos + 1;
else
if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;
Comparison of Nested if
and Sequences of ifs
- A sequence of
if
statements may be used instead of a nestedif
, but are less efficient - All conditions are always tested in a sequence of
ifs
- In a nested
if
, only the first condition is tested when x is positive
Multi-way Branching
if (Expression1)
Statement1
else if (Expression2)
Statement2
else if (ExpressionN)
StatementN
else
Statement N+1
- Exactly 1 of these statements will be executed
Example of Nested if
Statements
if (creditsEarned >= 90)
printf ("Fourth year student ");
else if (creditsEarned >= 60)
printf ("Third year student ");
else if (creditsEarned >= 30)
printf ("Second year student ");
else
printf ("First year student ");
Example of describing an int value
- Display one word to describe the int value of the number as “Positive,” “Negative,” or “Zero”
if (number > 0)
printf ("Positive");
else if (number < 0)
printf ("Negative");
else
printf ("Zero");
Nested if Statements Example
- Pollution index classification
if (index < 35)
printf ("Pleasant");
else if (index <= 60)
printf ("Unpleasant");
else
printf ("Health Hazard");
Example: Nested If Statement (with char
grade)
float score;
Char grade;
scanf("%f", &score);
if(score>=0 && score= 85 )
grade='A';
else if ( score >= 75 )
grade='B';
else if ( score >= 65 )
grade='c';
else if ( score >= 50 )
grade='D';
else
grade='F';
printf("grade is %c", grade);
else printf("ERROR! Wrong score.");
Common if
Statement Errors
- No parentheses around the condition causes a syntax error
if crsr_or_frgt == 'C' // Error
printf("Cruiser\n");
- A semicolon after the condition is interpreted as doing nothing if the condition is true.
if (crsr_or_frgt == 'C'); // Error
printf("Cruiser\n");
switch
statement
- Usually used instead of nested
if
for selecting multiple alternatives - Useful when selection is based on a single variable or simple expression
- The controlling expression is of type integer or character, not floating-pointing
- Example: Determine a student's grade given their score
switch
Statement Selection Flow
graph TD
A[expression] --> B{case value1}
B -- true --> C[statements1]
C --> D[break]
B -- false --> E{case value2}
E -- true --> F[slatements2]
F --> G[break]
E -- false --> H{case valuen}
H -- true --> I[statementsn]
I --> J[break]
H -- false --> K[default]
K --> L[statements]
switch
Syntax
switch (controlling expression) {
case value1: statements 1;
break;
...
case valueN: statements n;
break;
default: statements;
}
Example: switch
Statement with char
Type
#include
int main(void) {
char classID;
printf("Enter class id [b, c, d, or f]: ");
scanf("%c", &classID);
switch (classID) {
case 'B':
case 'b':
printf("Battleship\n");
break;
case 'C':
case 'c':
printf("Cruiser\n");
break;
case 'D':
case 'd':
printf("Destroyer\n");
break;
case 'F':
case 'f':
printf("Frigate\n");
break;
default:
printf("Unknown ship class %c\n", classID);
}
return 0;
}
Explanation of the switch
Example
- The value of the variable
class
is compared to each case in a top-down approach - Execution stops when the first case is found
- Execution starts and continues until a
break
statement is encountered, or the switch statement ends - If no case is matched, the default case (if provided) is executed
switch
Statement Example 2
char color;
printf("Enter a color: ");
scanf("%c", &color);
switch (color) {
case 'R':
printf("red\n");
break;
case 'B':
printf("blue\n");
break;
case 'Y':
printf("yellow\n");
break;
}
switch
Statement Example 3
char grade;
printf("Enter your letter grade: ");
scanf("%c", &grade);
switch (grade) {
case 'A':
printf(" Excellent Job");
break;
case 'B':
printf(" Very Good “);
break;
case 'C':
printf(" Not bad ");
break;
case 'F':
printf("Failing");
break;
default:
printf(" Wrong Grade");
}
switch
Statement Example 4
- Program asks for brightness of a light bulb (Watts) & prints expected lifetime
Brightness | Lifetime in hours |
---|---|
25 | 2500 |
40, 60 | 1000 |
75, 100 | 750 |
otherwise | 0 |
int bright;
printf("Enter the bulb brightness: ");
scanf("%d", &bright);
switch (bright) {
case 25:
printf(" Expected Lifetime is 2500 hours");
break;
case 40:
case 60:
printf("Expected Lifetime is 1000 hours“);
break;
case 75:
case 100:
printf("Expected Lifetime is 750 hours ");
break;
default:
printf("Wrong Input ");
}
Key Reminders for Switch Statements
- Statements following a case label can be one or more C statements without braces
- Strings cannot be used as case labels
- double type values cannot be case labels
- Forgetting the
break
statement is a common error, leading to fall-through into the next alternative - Forgetting the closing brace of the switch statement body is easy to do
Nested-if versus switch
- Advantages of if:
- More general than a switch,
- Operates on ranges of values (e.g.,
x 100
- Can't compare doubles
- Advantages of switch:
- Switch is more readable
- Use the switch whenever there are ten or fewer case labels
switch
versus if-else
- Example 5: Prompt user for two integer values, to choose a calculation
USING IF-ELSE STATEMENT
#include
void main()
{ int x,y,result; char op;
printf(“please enter the first number:”); scanf(“%d”,&x);
printf(“please enter the second number:”); scanf(“%d”,&y);
printf(“please enter an operation(+ - * /):”); scanf(“%c”,&op);
if (op==‘+’)
result=x+y;
else if (op==‘-’)
result=x-y;
else if (op==‘*’)
result=x*y;
else if (op==‘/’)
result=x/y;
printf(“result= %d:”, result);
}
USING SWITCH STATEMENT
#include
void main()
{
int x, y, result;
char op;
printf(“please enter the first number:”); scanf(“%d”,&x);
printf(“please enter the second number:”); scanf(“%d”,&y);
printf(“please enter an operation(+ - * /):”);scanf(“%c”,&p);
switch(op)
{
case ‘+’: result=x+y; break;
case ‘-’: result=x-y; break;
case ‘*’: result=x*y; break;
case ‘/’: result=x/y; break;
}
printf(“result= %d:”,result);
}
Common Programming Errors
- Consider the Statement
if (0 <= x <= 4)
- This is always evaluated to true in C
- First 0 > You must use == for comparison
More Common Errors:
- Parenthesizing the condition.
- The
{
and}
if they are needed - In switch statements, make sure the controlling expression and case labels are of the same permitted type.
- Remember to include the default case for switch statements.
- Don't forget your
{
and}
for the switch statement. - Avoid forgetting the break statements!!!
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.