Identifier Naming & Arithmetic Operators

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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.

False (B)

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?

<p>Subtraction, due to potential catastrophic cancellation when subtracting nearly equal numbers. (C)</p>
Signup and view all the answers

In C, the expression x+++++y is syntactically ______, due to the greedy nature of token parsing.

<p>ambiguous</p>
Signup and view all the answers

When using prefix increment/decrement operators in C, what subtle side effect can occur within complex expressions that might lead to unexpected behavior?

<p>Undefined behavior if the variable is also accessed elsewhere in the same expression without an intervening sequence point. (A)</p>
Signup and view all the answers

In C, the relational operators <, >, <=, >=, ==, and != always return either 0 or 1, strictly adhering to the Boolean interpretation of false and true.

<p>False (B)</p>
Signup and view all the answers

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.

<p>This can occur with floating-point numbers when <code>a</code> and <code>b</code> are calculated through different paths but converge to an equivalent value within the precision limits of the <code>float</code> or <code>double</code> type, even though their underlying bit patterns may differ.</p>
Signup and view all the answers

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?

<p>If <code>x</code> evaluates to false, ensuring short-circuit evaluation. (A)</p>
Signup and view all the answers

In C, the ! operator, when applied to a pointer, returns 1 if the pointer is ______ and 0 otherwise.

<p>null</p>
Signup and view all the answers

Match the following C operators with their corresponding precedence level (lower number indicates higher precedence):

<p><code>*</code> (multiplication) = 3 <code>+</code> (addition) = 4 <code>&amp;&amp;</code> (logical AND) = 8 <code>=</code> (assignment) = 16</p>
Signup and view all the answers

Consider the C expression $a = b+++c*d;. How does the compiler resolve this expression according to operator precedence and associativity rules?

<p>The compiler applies postfix increment after the entire expression is evaluated: <code>$a = b + (c * d); b++</code>. (B)</p>
Signup and view all the answers

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.

<p>False (B)</p>
Signup and view all the answers

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.

<p>Using floor by itself will not result in incorrect results. If we want to perform monetary calculations to two decimal places correctly, a common scenario is calculating the compounded daily interest on a loan.</p>
Signup and view all the answers

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?

<p>Division by zero if <code>a</code> is zero, underflow if b squared is too close to 4ac, and precision loss due to catastrophic cancellation. (C)</p>
Signup and view all the answers

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 ______.

<p>non-portable</p>
Signup and view all the answers

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?

<p><code>x &gt; z &amp;&amp; y &gt; z</code> (C)</p>
Signup and view all the answers

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.

<p>False (B)</p>
Signup and view all the answers

Describe a potential pitfall when using nested if-else statements without proper indentation and how it could lead to unexpected program behavior.

<p>Without proper indentation, an <code>else</code> clause might inadvertently associate with the wrong <code>if</code> statement, leading to logical errors where code blocks are executed under incorrect condition evaluations.</p>
Signup and view all the answers

Under what circumstance when writing an if-else statement is a compile-time error thrown?

<p>There is an else statement after the if statement, but the if statement has not braces. (B)</p>
Signup and view all the answers

When using the switch statement in C, the ___ keyword is essential at the end of each case block to prevent fall-through.

<p>break</p>
Signup and view all the answers

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?

<p><code>double</code> values cannot be directly used as <code>case</code> labels in a <code>switch</code> statement due to their inexact representation. (C)</p>
Signup and view all the answers

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.

<p>False (B)</p>
Signup and view all the answers

Explain a scenario in C where using a series of if statements is more appropriate than a switch statement and explain why.

<p>When dealing with conditions that involve ranges or complex logical expressions, a series of <code>if</code> statements is more apt because <code>switch</code> requires discrete constant values as <code>case</code> labels.</p>
Signup and view all the answers

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.

<p>no</p>
Signup and view all the answers

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?

<p>Implementing a decision table using function pointers. (A)</p>
Signup and view all the answers

In C, all programming errors—including syntax errors, runtime errors, and logical errors—are always detected and reported by the compiler at compile time.

<p>False (B)</p>
Signup and view all the answers

Describe a common programming error that involves unintended assignment within a conditional expression and explain how to prevent it.

<p>A common accidental assignment within a conditional expression. This can be prevented by writing conditional checks in a different order.</p>
Signup and view all the answers

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.

<p>indentation</p>
Signup and view all the answers

Which of the choices correctly calculates compound daily interest on a loan of p dollars over n days?

<p><code>int total = p*pow((1+(double)r/365), n);</code> (B)</p>
Signup and view all the answers

A switch-statement is a lot more general than an if statement.

<p>False (B)</p>
Signup and view all the answers

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?

<p>A switch statement is optimal for code readability.</p>
Signup and view all the answers

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.

<p>default</p>
Signup and view all the answers

What happens if the lightbulb is not 25 Watts, 40 Watts, 60 Watts, 75 Watts, or 100 Watts in the switch statement?

<p>The default statement executes. (A)</p>
Signup and view all the answers

Can string values be defined as case labels?

<p>False (B)</p>
Signup and view all the answers

Please name two more common errors.

<p>1). Don't forget to parenthesize the conditions. 2). C matches each else with the closest unmatched if, so be careful so that you get the correct pairings of if and else statements.</p>
Signup and view all the answers

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.

<p>int, char</p>
Signup and view all the answers

Flashcards

Identifier Naming: Case Sensitivity

Avoid identifier names that differ only by case to prevent bugs. Example: LETTER, Letter, letter

Identifier name length

Some compilers have a limit on the length of identifier names. Avoid using names longer than 31 characters.

Shortcut assignment operator

Operators that combine an arithmetic operation with an assignment. Example: a += b is equivalent to a = a + b

Prefix increment/decrement

Increments/decrements the variable before its value is used in the expression.

Signup and view all the flashcards

Postfix increment/decrement

Returns the original value of the variable before incrementing or decrementing.

Signup and view all the flashcards

Logical AND (&&) operator

The 'And' operator (&&) returns true only if both operands are true.

Signup and view all the flashcards

Logical OR (||) operator

The 'Or' operator (||) returns true if at least one of the operands is true.

Signup and view all the flashcards

Logical NOT (!) operator

The 'Not' operator (!) reverses the logical state of its operand.

Signup and view all the flashcards

Control Structures

Control structures control the flow of execution in a program or function.

Signup and view all the flashcards

Compound Statement

A group of statements bracketed by { and } that specifies sequential flow.

Signup and view all the flashcards

Selection control structure

Allows a program to execute different blocks of code based on a condition.

Signup and view all the flashcards

Repetition Control Structure

Executes a block of code multiple times based on a condition.

Signup and view all the flashcards

Condition

An expression tested within a control structure that evaluates to true (1) or false (0).

Signup and view all the flashcards

If statement

A selection statement that executes a block of code if a condition is true.

Signup and view all the flashcards

If-else statement

Executes one block of code if a condition is true, and another block if the condition is false.

Signup and view all the flashcards

Nested if statements

One if statement placed inside another to handle multiple conditions.

Signup and view all the flashcards

Switch statement

A selection control mechanism that compares a variable against several constant integral values.

Signup and view all the flashcards

Break statement (in switch)

A directive to jump out of a switch statement, preventing fall-through to the next case.

Signup and view all the flashcards

Default case (in switch)

An optional section in a switch statement that executes if no cases match the expression's value.

Signup and view all the flashcards

Mistake checking range

A common mistake is when checking a range, the correct form is (0 <= x && x <= 4).

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 constant
    • KmsPerMile or Kms_Per_Mile is a variable

Invalid Identifiers

  • 1Letter is invalid because it begins with a number
  • double and int are invalid because they are reserved words
  • TWO*FOUR, joe’s, and age# 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, and PrintHeading 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 write a += 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 are true
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 is true

| 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, use y = 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): Calculates x to the power of y
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 exponential e to the power of x
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, and switch

C Control Structures: Repetition

  • Includes statements for, while, and do...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) or true (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 times price to the original price if taxCode 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 nested if, 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.

Quiz Team

Related Documents

More Like This

Identifiers in C++
17 questions

Identifiers in C++

AppropriateShakuhachi avatar
AppropriateShakuhachi
Identifiers in Programming Examples Quiz
18 questions
Variables and Identifiers in Programming
10 questions
Use Quizgecko on...
Browser
Browser