UNIT-II: Operators, Expressions, and Input/Output Operations
Operators and Expressions
In programming, operators are special symbols that perform operations on one or more operands (variables or values). An expression is a combination of operators, constants, and variables that evaluates to a single value.
Operands and Operators
An operand is the data item on which operators act. For example, in a + b, 'a' and 'b' are operands, and '+' is the operator.
Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b (Integer division truncates fractional part if operands are integers) |
| % | Modulo (Remainder) | a % b (Gives the remainder when a is divided by b) |
Note: The % operator cannot be used with floating-point numbers.
Example:
int x = 10, y = 3;
int sum = x + y; // sum is 13
int diff = x - y; // diff is 7
int prod = x * y; // prod is 30
int quot = x / y; // quot is 3 (integer division)
int rem = x % y; // rem is 1
Relational Operators
Relational operators are used to compare two operands. They return a boolean result (true or false, often represented as 1 or 0 in C/C++).
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | a == b |
| != | Not equal to | a != b |
| > | Greater than | a > b |
| < | Less than | a < b |
| >= | Greater than or equal to | a >= b |
| <= | Less than or equal to | a <= b |
Example:
int p = 5, q = 10;
bool check1 = (p == q); // false (0)
bool check2 = (p != q); // true (1)
bool check3 = (p < q); // true (1)
Logical Operators
Logical operators combine or negate relational expressions. They are typically used to construct complex conditions.
| Operator | Meaning | Example |
|---|---|---|
| && | Logical AND | (condition1 && condition2) (True if both are true) |
| || | Logical OR | (condition1 || condition2) (True if at least one is true) |
| ! | Logical NOT | !(condition) (Reverses the truth value) |
Example:
int age = 25;
bool isStudent = true;
bool condition1 = (age > 18 && isStudent); // True
bool condition2 = (age < 20 || !isStudent); // False
Assignment Operators
Assignment operators are used to assign a value to a variable. The most common is =.
| Operator | Example | Equivalent To |
|---|---|---|
| = | a = 5; |
a = 5; |
| += | 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; |
Example:
int x = 10;
x += 5; // x becomes 15
x *= 2; // x becomes 30
Increment/Decrement Operators
These are unary operators used to increase or decrease the value of a variable by one.
| Operator | Meaning | Position | Example |
|---|---|---|---|
| ++ | Increment by 1 | Prefix (++a) |
Increments a, then uses the new value. |
| ++ | Increment by 1 | Postfix (a++) |
Uses the current value of a, then increments it. |
| -- | Decrement by 1 | Prefix (--a) |
Decrements a, then uses the new value. |
| -- | Decrement by 1 | Postfix (a--) |
Uses the current value of a, then decrements it. |
Example:
int i = 5;
int j = ++i; // i becomes 6, j becomes 6 (prefix)
int x = 5;
int y = x++; // y becomes 5, x becomes 6 (postfix)
Precedence of Operators in Arithmetic, Relational and Logical Expression
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, their associativity (left-to-right or right-to-left) determines the order.
Important: Parentheses () can always be used to explicitly control the order of evaluation, overriding default precedence.
General Precedence Hierarchy (Highest to Lowest, common for C/C++):
- Parentheses
(): Highest precedence. - Unary operators:
++,--(prefix),!,-(unary minus) - Arithmetic operators:
*,/,%(Multiplication, Division, Modulo) - Higher than Addition/Subtraction - Arithmetic operators:
+,-(Addition, Subtraction) - Relational operators:
<,<=,>,>= - Relational operators:
==,!= - Logical operators:
&&(Logical AND) - Logical operators:
||(Logical OR) - Assignment operators:
=,+=,-=, etc. (Lowest precedence for these categories)
Associativity:
- Most binary operators (arithmetic, relational, logical) have left-to-right associativity. E.g.,
a - b + cis(a - b) + c. - Unary operators and assignment operators generally have right-to-left associativity. E.g.,
a = b = cisa = (b = c).
Example:
int result = 5 + 3 * 2; // result will be 11 (3*2 is evaluated first due to higher precedence of *)
int x = 10, y = 5, z = 2;
bool complexCondition = (x > y && y != z * 2);
// 1. z * 2 -> 4
// 2. y != 4 -> true (5 != 4)
// 3. x > y -> true (10 > 5)
// 4. true && true -> true
// complexCondition will be true
Library Functions
Library functions are pre-defined functions that are readily available for use in programs. They are typically grouped into libraries (e.g., stdio.h for standard input/output, math.h for mathematical operations, string.h for string manipulation). Using library functions saves development time and ensures code correctness and efficiency.
To use a library function, you usually need to include the appropriate header file at the beginning of your source code using the #include directive.
Common Categories of Library Functions:
- Input/Output Functions: For reading data from and writing data to consoles, files, etc. (e.g.,
printf(),scanf(),getchar(),putchar()). - Mathematical Functions: For performing mathematical calculations (e.g.,
sqrt(),pow(),sin(),cos()). Requires<math.h>. - String Manipulation Functions: For working with strings (e.g.,
strlen(),strcpy(),strcat()). Requires<string.h>. - General Utility Functions: For tasks like memory allocation, random number generation, type conversions (e.g.,
malloc(),rand(),atoi()). Requires<stdlib.h>.
Example (using math library function):
#include <stdio.h>
#include <math.h> // Required for sqrt()
int main() {
double num = 25.0;
double squareRoot = sqrt(num); // sqrt() is a library function
printf("The square root of %.2f is %.2f\n", num, squareRoot);
return 0;
}
Managing Input and Output Operations
Input/Output (I/O) operations are fundamental for any program to interact with the user or external systems. Input operations allow a program to read data, while output operations allow it to display data.
In C, I/O operations are primarily handled by functions available in the <stdio.h> header file (Standard Input/Output).
Reading and Printing Formatted Data
Formatted I/O allows you to read and write data according to a specified format. This means you can specify the data type, width, alignment, and precision for numerical values.
1. Formatted Output: printf()
int printf(const char *format, ...);
- Used to print formatted output to the standard output device (usually the console).
- The
formatstring contains plain characters to be printed as is, and format specifiers (placeholders) that determine how the subsequent arguments are displayed. - Returns the number of characters printed, or a negative value on error.
Common Format Specifiers:
| Specifier | Data Type | Description |
|---|---|---|
%d or %i |
int |
Signed decimal integer |
%f |
float, double |
Decimal floating point (default 6 decimal places) |
%lf |
double |
Used with scanf for double; printf uses %f for both float and double. |
%c |
char |
Single character |
%s |
char* (string) |
Sequence of characters |
%u |
unsigned int |
Unsigned decimal integer |
%x or %X |
int |
Hexadecimal integer (lowercase or uppercase) |
%o |
int |
Octal integer |
%p |
void* |
Pointer address |
Example:
#include <stdio.h>
int main() {
int age = 30;
float height = 1.75f;
char initial = 'J';
char name[] = "John"; // C-style string
printf("Name: %s, Initial: %c\n", name, initial);
printf("Age: %d years, Height: %.2f meters\n", age, height); // .2f for 2 decimal places
printf("Formatted output with padding: |%10d|\n", age); // 10 spaces total, right-aligned
return 0;
}
2. Formatted Input: scanf()
int scanf(const char *format, ...);
- Used to read formatted input from the standard input device (usually the keyboard).
- The
formatstring contains format specifiers that tellscanfwhat type of data to expect. - Subsequent arguments must be addresses of variables (using the
&address-of operator) where the input data will be stored. - Returns the number of input items successfully matched and assigned, or
EOFif an input failure occurs before any data could be read.
Example:
#include <stdio.h>
int main() {
int rollNo;
float marks;
char grade;
printf("Enter Roll No, Marks, and Grade (e.g., 101 85.5 A): ");
scanf("%d %f %c", &rollNo, &marks, &grade); // Note the & before variable names
printf("\nYou entered:\n");
printf("Roll No: %d\n", rollNo);
printf("Marks: %.1f\n", marks);
printf("Grade: %c\n", grade);
return 0;
}
Common Mistakes with scanf():
- Forgetting the
&(address-of) operator before variable names (except for character arrays/strings where the array name itself is an address). - Not matching the format specifiers with the actual data types of the variables.
- Forgetting to handle leftover newline characters in the input buffer, especially after reading a character with
%cfollowed by anotherscanf. (e.g.,scanf(" %c", &grade);with a space before%cto consume whitespace).
Reading and Printing Unformatted Data
Unformatted I/O operations handle single characters or strings without any specific formatting. They are often simpler and faster for character-by-character or line-by-line input/output.
1. Character I/O Functions:
getchar(): Reads a single character from the standard input.int getchar(void);Returns the character read (as an
int) orEOFon end-of-file/error.putchar(): Writes a single character to the standard output.int putchar(int char_to_write);Returns the character written or
EOFon error.getch()/getche()(non-standard, often from<conio.h>):getch(): Reads a character without echoing it to the screen.getche(): Reads a character and echoes it to the screen.- These are not part of standard C and should be avoided for portability.
Example (getchar() and putchar()):
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Reads a single character
printf("You entered: ");
putchar(ch); // Prints the single character
putchar('\n'); // Prints a newline character
return 0;
}
2. String I/O Functions:
gets()(DEPRECATED and UNSAFE): Reads a line of text from standard input into a string.char *gets(char *str);It does not perform bounds checking, leading to buffer overflows if the input is longer than the buffer. Avoid using
gets().puts(): Writes a string to standard output, followed by a newline character.int puts(const char *str);Returns a non-negative value on success,
EOFon error.fgets()(SAFE alternative togets()): Reads a line from a specified input stream (e.g.,stdin) into a string, with a size limit.char *fgets(char *str, int num, FILE *stream);Reads up to
num-1characters or until a newline or EOF. The newline character (\n) is included in the buffer if read.
Example (puts() and fgets()):
#include <stdio.h>
#include <string.h> // For strlen if needed
int main() {
char name[50];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin); // Safe way to read a line
// fgets includes the newline, remove it if not desired
name[strcspn(name, "\n")] = 0; // Removes trailing newline
printf("Hello, ");
puts(name); // Prints the name and adds a newline
return 0;
}
strcspn() Explanation: The strcspn(name, "\n") function returns the length of the initial segment of name which consists of characters not in the string "\n". Essentially, it finds the position of the first newline character. Setting that position to 0 effectively truncates the string before the newline.