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 thestdio.hheader 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 as392.c: Reads a single character, such asa.f: Reads a floating-point decimal number, such as392.65.x: Reads an unsigned hexadecimal number, such as7fa.o: Reads an octal number, such as610.s: Reads a string (alphanumeric), such assample.(space): Reads white space.lf: Reads adoubleprecision floating-point number, such as1.333.Lf: Reads along doubleprecision floating-point number, such as1.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(), andstrol().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 (
+): Algebraicx + 7translates tox + 7in C.Subtraction (
-): Algebraicp - ctranslates top - cin C.Multiplication (
*): Algebraicbmtranslates tob * min C.Division (
/): Algebraic or translates tox / yin C.Modulo/Remainder (
%): Algebraic translates tor % sin 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:
Parentheses
(): Evaluated first, from left to right. If there are nested parentheses, the innermost ones are calculated first.Multiplication
*, Division/, and Modulo%: Evaluated second, from left to right.Addition
+and Subtraction-: Evaluated next, from left to right.Assignment
=: Evaluated last, from right to left.
Converting Algebraic Expressions to C
Arithmetic Mean: The algebraic expression is written in C as
m = (a+b+c+d+e)/5;.Polynomial Expression: The algebraic expression is written in C as
y = a * x * x + b * x + c;.
Sequential Execution Example
Consider the expression:
The steps of execution based on precedence and left-to-right evaluation are:
p * ris calculated.The result of
(p * r)is used with modulo% q.w / xis calculated.The result of the modulo operation and the result of the division are added together.
The value of
yis subtracted from that sum.The final result is assigned to
zvia 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 = 5returns the value assigned (5). This allows for chaining:y = x = 5;first assigns 5 tox, then 5 is assigned toy.Compound Operators: C provides shorthand for updating variables:
c += 7is equivalent toc = c + 7d -= 4is equivalent tod = d - 4e *= 5is equivalent toe = e * 5f /= 3is equivalent tof = f / 3g %= 9is equivalent tog = g % 9
Comprehensive Table of Operator Precedence
Evaluation follows this hierarchy:
Primary:
(),expr++,expr--(Evaluated Left-to-Right).Unary:
+,-,++expr,--expr(Evaluated Right-to-Left).Multiplicative:
*,/,%(Evaluated Left-to-Right).Additive:
+,-(Evaluated Left-to-Right).Assignment:
=,+=,-=,*=,/=,%=(Evaluated Right-to-Left).
Programming Exercises
Write a program that defines two
floatvariablesxandy, reads their values from standard input, and calculates the result of the expression:Write a program that defines two
floatvariablesxandy, reads their values from standard input, and calculates the summation:Write a program that accepts two integers from standard input and calculates the quotient and the remainder of their division.
Write a program that accepts two integers from standard input and calculates and prints the result of their division in decimal form.
Implement a program that reads two integers from standard input, increases their value by one using three alternative methods, and prints the result.