Programming I: Fundamental Arithmetic in C Language

Addition of Two Integers in C

  • The following program demonstrates a basic structure in C to add two numbers provided by the user:

/* Second Simple Program: add 2 numbers */
#include <stdio.h>

int main() {
    int integer1, integer2;
    int sum;

    printf("Enter first integer\n");
    scanf("%d", &integer1);

    printf("Enter second integer\n");
    scanf("%d", &integer2);

    sum = integer1 + integer2;
    printf("Sum is %d\n", sum);

    return 0;
}

User Input and the scanf() Function

  • The scanf() function is defined in the stdio.h header file.

  • It performs the reverse operation of printf(), as it reads information provided by the user from the standard input.

  • When the program executes a line such as scanf("%d", &integer1);, execution pauses. The program waits for the user to type a value (in this case, an integer) and press the ENTER key before proceeding.

scanf() Format Specifiers

Different specifiers are used to dictate the type of data the function should expect and read:

  • d: Reads an integer as a signed decimal, such as 392.

  • c: Reads a single character, such as a.

  • f: Reads a floating-point decimal number, such as 392.65.

  • x: Reads an unsigned hexadecimal number, such as 7fa.

  • o: Reads an octal number, such as 610.

  • s: Reads a string (alphanumeric), such as sample.

  • (space): Reads white space.

  • lf: Reads a double precision floating-point number, such as 1.333.

  • Lf: Reads a long double precision floating-point number, such as 1.333.

Security and Practical Use of scanf()

  • While scanf() is highly useful for introductory programming and educational exercises, it possesses several security vulnerabilities and can exhibit unpredictable behavior in specific cases.

  • In professional practice, it is more common to use fgets() to read input initially as a string. This is often combined with other functions for parsing input from standard entry or files.

  • Alternative functions for processing input include strtok(), strod(), and strol().

  • Although these alternatives are preferred in industry, scanf() is sufficient for fundamental learning until more advanced techniques are introduced.

Arithmetic in C

  • Most C programs perform mathematical calculations involving constants and variables.

  • Example of basic arithmetic assignments:

int x, y;
x = 1;
y = x + 100;

Binary Arithmetic Operators

Operators in C typically map directly to standard algebraic expressions:

  • Addition (+): Algebraic x + 7 translates to x + 7 in C.

  • Subtraction (-): Algebraic p - c translates to p - c in C.

  • Multiplication (*): Algebraic bm translates to b * m in C.

  • Division (/): Algebraic x/yx/y or x÷yx \div y translates to x / y in C.

  • Modulo/Remainder (%): Algebraic r(mods)r \pmod s translates to r % s in C.

  • Parentheses: Used similarly to algebra to group expressions and dictate evaluation order, for example: a = b * (c + d);.

Operator Precedence and Rules of Evaluation

The order in which an expression is calculated follows specific precedence levels:

  1. Parentheses (): Evaluated first, from left to right. If there are nested parentheses, the innermost ones are calculated first.

  2. Multiplication *, Division /, and Modulo %: Evaluated second, from left to right.

  3. Addition + and Subtraction -: Evaluated next, from left to right.

  4. Assignment =: Evaluated last, from right to left.

Converting Algebraic Expressions to C

  • Arithmetic Mean: The algebraic expression m=a+b+c+d+e5m = \frac{a+b+c+d+e}{5} is written in C as m = (a+b+c+d+e)/5;.

  • Polynomial Expression: The algebraic expression y=ax2+bx+cy = ax^2 + bx + c is written in C as y = a * x * x + b * x + c;.

Sequential Execution Example

Consider the expression: z=p×r%q+w/xyz = p \times r \% q + w/x - y

The steps of execution based on precedence and left-to-right evaluation are:

  1. p * r is calculated.

  2. The result of (p * r) is used with modulo % q.

  3. w / x is calculated.

  4. The result of the modulo operation and the result of the division are added together.

  5. The value of y is subtracted from that sum.

  6. The final result is assigned to z via the = operator.

Integer vs. Floating-Point Division

  • The behavior of the division operator / depends on the data types of its operands.

  • Mixed or Float Division: Division between floating-point numbers, or between an integer and a floating-point number, returns a floating-point number.

  • Integer Division: Division between two integers returns an integer. Any decimal portion is truncated (not rounded).

Code Example Analysis:

int a = 1, b;
float x = 1.0f, y;

b = a / 2;     /* Result is 0; integer division 1/2 is 0.5, truncated to 0 */
b = a / 2.0f;  /* Result is 0; calculation is 0.5, but assignment to int b truncates it to 0 */
y = a / 2;     /* Result is 0.00; because a and 2 are integers, division yields 0 before being assigned to float y */
y = a / 2.0f;  /* Result is 0.50; because 2.0f is a float, the result is 0.5 */

Unary Arithmetic Operators

Unary operators act on a single operand and have higher precedence than binary arithmetic operators (except for parentheses):

  • Unary Plus (+): e.g., y = +5;.

  • Unary Minus (-): e.g., x = -y;.

  • Increment (++): Increases a variable by 1.

  • Decrement (--): Decreases a variable by 1.

Prefix vs. Postfix Increment and Decrement

The positioning of ++ and -- relative to the variable affects when the operation occurs during evaluation:

  • Postfix (x++, x--): The current value of the variable is used in the expression first, and then the variable is incremented or decremented.

  • Prefix (++x, --x): The variable is incremented or decremented first, and then the new value is used in the expression.

Example Demonstrating Differences:

int x = 1, y;
y = x++; /* x becomes 2, y becomes 1 (original x) */
y = ++x; /* x becomes 3, y becomes 3 (new x) */
y = x--; /* x becomes 2, y becomes 3 (original x) */
y = --x; /* x becomes 1, y becomes 1 (new x) */

Complex Incremental Evaluation and Warnings

Code using multiple increments or decrements in the same line can be difficult to read and may lead to non-portable or undefined behavior in functions:

int x = 3, y;
y = x++; /* y = 3, x = 4 */
printf("%d %d\n", x++, ++y); /* prints 4 4; then x becomes 5, y is 4 */
printf("%d %d\n", ++x, ++y); /* x becomes 6, y becomes 5; prints 6 5 */
printf("%d\n", y++ + ++x);   /* uses 5 + 7 = 12; then y becomes 6, x is 7 */
printf("%d\n", --y + --x);   /* y becomes 5, x becomes 6; uses 5 + 6 = 11 */

Note: Avoid using ++ or -- multiple times within the same function call or complex expression.

Assignment and Compound Assignment Operators

  • Assignment Association: The = operator evaluates from right to left.

  • Return Value: An assignment expression like x = 5 returns the value assigned (5). This allows for chaining: y = x = 5; first assigns 5 to x, then 5 is assigned to y.

  • Compound Operators: C provides shorthand for updating variables:

    • c += 7 is equivalent to c = c + 7

    • d -= 4 is equivalent to d = d - 4

    • e *= 5 is equivalent to e = e * 5

    • f /= 3 is equivalent to f = f / 3

    • g %= 9 is equivalent to g = g % 9

Comprehensive Table of Operator Precedence

Evaluation follows this hierarchy:

  1. Primary: (), expr++, expr-- (Evaluated Left-to-Right).

  2. Unary: +, -, ++expr, --expr (Evaluated Right-to-Left).

  3. Multiplicative: *, /, % (Evaluated Left-to-Right).

  4. Additive: +, - (Evaluated Left-to-Right).

  5. Assignment: =, +=, -=, *=, /=, %= (Evaluated Right-to-Left).

Programming Exercises

  1. Write a program that defines two float variables x and y, reads their values from standard input, and calculates the result of the expression: x3+4×y2+3\text{x}^3 + 4 \times \text{y}^2 + 3

  2. Write a program that defines two float variables x and y, reads their values from standard input, and calculates the summation: n=03(x/y)n\sum_{n=0}^{3} (x/y)^n

  3. Write a program that accepts two integers from standard input and calculates the quotient and the remainder of their division.

  4. Write a program that accepts two integers from standard input and calculates and prints the result of their division in decimal form.

  5. Implement a program that reads two integers from standard input, increases their value by one using three alternative methods, and prints the result.