Introduction To C
Introduction To C
3. Logical Operators
The logical operators evaluate the logical expression and return a result. The
result is always a Boolean value. A Boolean value determines whether the
expression is true or false. There are three logical operators in C
programming: logical AND( && ), logical OR( || ), and logical NOT ( ! ).
1. Logical AND (&&):This operator returns true if both operands are true;
otherwise, it returns false.
2. Logical OR (||): This operator returns true if at least one of the operands is
true; if both are false, it returns false.
3. Logical NOT (!): This operator negates the truth value of the operand. It
returns true if the operand is false, and vice versa
4. Assignment Operators
Assignment operators are used to assign values to variables. The most basic
assignment operator is the = operator, but there are several compound
assignment operators that combine other operations (like addition, subtraction)
with assignment.
5. Increment/Decrement Operators: are used to increase or decrease the value of a
variable by 1. There are two types of increment and decrement operators:
Increment Operator (++): The increment operator increases the value of a variable by
1
Prefix Increment (++a): Increases the value of a before it is used in the expression.
Example: int a = 5;
int b = ++a; // a is first incremented to 6, then b is assigned the value 6
Postfix Increment (a++): Uses the current value of a in the expression and then
increments a.
Example: int a = 5;
int b = a++; // b is assigned the value 5, then a is incremented to 6
Decrement Operator (--): decreases the value of a variable by 1.
Prefix Decrement (--a): Decreases the value of a before it is used in the expression.
Example: int a = 5;
int b = --a; // a is first decremented to 4, then b is assigned the value 4
Postfix Decrement (a--): Uses the current value of a in the expression and then
decrements a.
Example: int a = 5;
int b = a--; // b is assigned the value 5, then a is decremented to 4
6. Conditional (Ternary) Operator: is a shorthand way of writing simple if-else
statements. It takes three operands and is used to evaluate a condition, returning one
value if the condition is true and another value if the condition is false. The syntax of
the ternary operator is:
condition ? value_if_true : value_if_false;
Syntax Explanation:
condition: An expression that evaluates to either true (non-zero) or false (zero).
value_if_true: The value that is returned if the condition is true.
value_if_false: The value that is returned if the condition is false.
7. Bitwise Operators: used to perform operations at the bit
level. These operators manipulate individual bits of integer
values (like int, char, etc.), allowing for efficient low-level
data processing.
Example: Bitwise AND (&)
a = 5; // Binary: 0101
b = 3; // Binary: 0011
result = a & b; // Binary: 0001, result = 1
8. Miscellaneous Operators:
Precedence of arithmetic operations (the order of operations) dictates the
sequence in which operations are performed in an arithmetic expression.
The standard order is:
1.Parentheses (): Operations inside parentheses are performed first.
2.Exponents ^: Exponential calculations come next (e.g., 23=8).
3.Multiplication *, Division / and modulus %: These operations are performed
from left to right. They are of equal precedence, so you evaluate them as they appear
in the expression, moving left to right.
4. Addition + and Subtraction -: Also performed from left to right, with equal
precedence, evaluated in the order they appear.
5. If parentheses are nested, the evaluation begins with the innermost sub-expression
For the expression: 3+6×(5+4)2÷3−2 Final result: 163.
Type conversion (or type casting) refers to converting a variable from one data type
to another, either automatically or explicitly, in the context of an expression.
There are two types of type conversions in C:
Implicit Conversion (Type Promotion): The compiler automatically converts a
variable from one type to another when required by the expression. For example,
when performing an operation between an int and a float, the int is automatically
promoted to float to avoid losing precision.
Rules for implicit conversion:
1. Integer types smaller than int (like char or short) are promoted to int.
2. If one operand is double and the other is float, the float is promoted to double.
3. If one operand is long and the other is int, the int is promoted to long.
Explicit Conversion (Type Casting): The programmer can force a conversion by
specifying the desired type. This is known as explicit type casting.
The syntax is: (type) expression
Arithmetic Type Conversion in Expressions:
Usual arithmetic conversions: After promotions, if one operand is float and the other is
int, the int is converted to float. If one is double, the other is converted to double.
Program
#include <stdio.h>
int main() {
int a = 5;
float b = 4.5;
// Implicit conversion: 'a' is promoted to float before addition
float result1 = a + b;
printf("Result1: %.2f\n", result1); // Outputs: 9.50
// Explicit conversion: 'a' is cast to float
float result2 = (float) a / 2;
printf("Result2: %.2f\n", result2); // Outputs: 2.50
return 0;
}
Implicit Type Conversion
Mathematical Functions: are available through the standard math library math.h. To
compile a C program using math functions, you must link the math library explicitly.
Here are some common mathematical functions in C:
Basic Arithmetic Functions Trigonometric Functions
double pow(double base, double double sin(double x);
exponent); Returns the sine of `x` (in radians).
Example: pow(2, 3) returns 8.0 Example: sin(3.14159 / 2) returns 1.0.
double sqrt(double x); double cos(double x);
Example: sqrt(16) returns 4.0 Returns the cosine of `x` (in radians).
double fabs(double x); Example: cos(0) returns 1.0.
Returns the absolute value of `x`. double tan(double x);
Example: fabs(-5.5)` returns 5.5. Returns the tangent of `x` (in radians).
Logarithmic and Exponential Functions Example: tan(3.14159 / 4) returns 1.0.
double log(double x); double asin(double x);
Returns the natural logarithm (base `e`) of
Returns the arcsine of `x` (in radians).
`x`. Example: log(2.71828) returns 1.0.
double acos(double x);
double log10(double x);
Returns the base-10 logarithm of `x`.
Returns the arccosine of `x` (in
Example: log10(100) returns 2.0. radians).
double exp(double x); double atan(double x);
Returns `e` raised to the power of `x`. Returns the arctangent of `x` (in
Example: exp(1) returns 2.71828. radians).
4. Rounding and Remainder Functions
double ceil(double x); Returns the smallest integer greater than or equal to `x`.
Example: ceil(3.7) returns 4.0.
double floor(double x); Returns the largest integer less than or equal to `x`.
Example: floor(3.7) returns 3.0.
double fmod(double x, double y);
Returns the remainder of `x` divided by `y` (i.e., x % y).
Example: fmod(10.5, 3) returns 1.5.
Example Usage
#include <stdio.h>
#include <math.h>
int main() {
double x = 9.0;
double result = sqrt(x); // Calculates square root of 9.0
printf("Square root of %.2f is %.2f\n", x, result);
double y = 2.0;
double power = pow(y, 3); // Calculates 2^3
printf("%.2f raised to the power of 3 is %.2f\n", y, power);
return 0;
}
Managing Input and Output Operations
Reading a character:
scanf() is a formatted input getchar() fgetc(stdin)
function variable_name = gatchar(); variable_name =
fgetc(stdin);
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() { int main() { int main() {
char ch; char ch; char ch;
printf("Enter a character: printf("Enter a character: "); printf("Enter a character:
"); ch = getchar(); // Reads a ");
scanf("%c", &ch); single character ch = fgetc(stdin);
printf("You entered: %c\ printf("You entered: %c\n", printf("You entered: %c\n",
n", ch); ch); ch);
return 0; return 0; return 0;
} } }
The scanf() function is a commonly used input function. It allows you to read input
from the user or from a file and store that input in variables of different data types.
Syntax of scanf:
scanf(“control string”,arg1,arg2,…,argn);
The control string specifies the field format in which the data is to be entered and
arguments specifies the address of location where the data is stored. control string and
arguments are separated by comma.
Formatted input: refers to reading input in a specific format from the user or a file
using functions like scanf() or fscanf(). These functions allow you to specify the
data type and format in which the input should be interpreted, using format
specifiers. scanf() Function is reads data according to the format string and stores it
in the provided variables. %d : Reads an integer (int)
%f : Reads a floating-point number (float)
%lf: Reads a double
%c : Reads a single character
%s : Reads a string (character array)
%x : Reads a hexadecimal integer
%o : Reads an octal integer
%ld: Reads a long signed intger
%d or %i Reads a short signed intger
%lu : Reads a long unsigned int
%u reads a short unsigned ; L for long double
Not working:%u : unsigned integer and %e exponent
Inputting Numbers:
The filed specification to read a integer number is : % w d
The percentage sign indicates that a conversion specification follows. w is an integer
number that specifies the width of the number to be read and d, known as data type
character , indicates that the number to be read in integer mode
Scanf(“%2d %5d”, &num1, &num2);
Reading Multiple Values
#include <stdio.h>
int main() {
int num1; float num2; char ch;
printf("Enter an integer, a float, and a character: ");
scanf("%d %f %c", &num1, &num2, &ch); // Reading multiple inputs
printf("Integer: %d\nFloat: %.2f\nCharacter: %c\n", num1, num2, ch);
return 0;
}
Important Considerations with scanf()
1. Whitespace Handling: scanf() skips leading whitespace (spaces, tabs, newlines) for
most format specifiers (like %d, %f, %s), but not for %c. To avoid this issue with %c,
you can add a space before %c in the format string (e.g., " %c").
2. Buffer Overflow: When reading strings with %s, be cautious of buffer overflows.
To limit the number of characters is to be read by specifying a maximum width
scanf("%19s", str); // Limits input to 19 characters, ensuring the string doesn't
overflow
3. Return Value: scanf() returns the number of items successfully read. You can use
this return value to check if the input was successfully parsed.
2. The distance between two cities (in km.) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimetres.
3. The length & breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area & perimeter of the rectangle, and the
area & circumference of the circle.
5. If the marks obtained by a student in five different subjects are input through the
keyboard, find out the aggregate marks and percentage marks obtained by the student.
Assume that the maximum marks that can be obtained by a student in each subject is
100.
6. If a four-digit number is input through the keyboard, write a program to obtain the
sum of the first and last digit of thisnumber.