C Unit 2 notes
C Unit 2 notes
NOTES
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. By
definition, an operator performs a certain operation on operands. An operator needs one or more operands
for the operation to be performed.
Depending on how many operands are required to perform the operation, operands are called as unary,
binary or ternary operators. They need one, two or three operands respectively.
C language is rich in built-in operators and provides the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
We are most familiar with the arithmetic operators. These operators are used to perform arithmetic
operations on operands. The most common arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/).
Arithmetic operators
In addition, the modulus (%) is an important arithmetic operator that computes the remainder of a division
operation. Arithmetic operators are used in forming an arithmetic expression. These operators are binary in
nature in the sense they need two operands.
We are also acquainted with relational operators while learning secondary mathematics. These operators
are used to compare two operands and return a boolean value (true or false). They are used in a boolean
expression.
The most common relational operators are less than (<), greater than (>), less than or equal to (<=), greater
than or equal to (>=), equal to (==), and not equal to (!=). Relational operators are also binary operators,
needing two numeric operands.
Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
==
condition becomes true. true.
Checks if the values of two operands are equal or not. If the values are
!= (A != B) is true.
not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand. If yes, then the condition becomes true. true.
Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand. If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand. If yes, then the condition becomes true. true.
Checks if the value of left operand is less than or equal to the value of
<= (A <= B) is true.
right operand. If yes, then the condition becomes true.
Logical Operators
These operators are used to combine two or more boolean expressions. We can form a compound Boolean
expression by combining Boolean expression with these operators. An example of logical operator is as
follows −
The most common logical operators are AND (&&), OR(||), and NOT (!). Logical operators are also binary
operators.
(A &&
Called Logical AND operator. If both the operands are non-zero, then the
&& B) is
condition becomes true.
false.
Called Logical OR Operator. If any of the two operands is non-zero, then the (A || B)
||
condition becomes true. is true.
!(A &&
Called Logical NOT Operator. It is used to reverse the logical state of its
! B) is
operand. If a condition is true, then Logical NOT operator will make it false.
true.
Bitwise Operators
Bitwise operators let you manipulate data stored in computer’s memory. These operators are used to
perform bit-level operations on operands.
The most common bitwise operators are AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right
shift (>>). Here the "~" operator is a unary operator, while most of the other bitwise operators are binary in
narure.
Bitwise operator works on bits and perform bit−by−bit operation. The truth tables for &, "|", and "^" are as
follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
------------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Operator Description Example
Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e.,
&
operands. 0000 1100
(A | B) = 61, i.e.,
| Binary OR Operator copies a bit if it exists in either operand.
0011 1101
Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49, i.e.,
^
not both. 0011 0001
Binary One's Complement Operator is unary and has the effect of (~A ) = ~(60), i.e,.
~
'flipping' bits. -0111101
Binary Left Shift Operator. The left operands value is moved left A << 2 = 240 i.e.,
<<
by the number of bits specified by the right operand. 1111 0000
Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e.,
>>
right by the number of bits specified by the right operand. 0000 1111
Assignment Operators
As the name suggests, an assignment operator "assigns" or sets a value to a named variable in C. These
operators are used to assign values to variables. The "=" symbol is defined as assignment operator in C,
however it is not to be confused with its usage in mathematics.
Simple assignment operator. Assigns values from right side C = A + B will assign
=
operands to left side operand the value of A + B to C
C <<= 2 is same as C =
<<= Left shift AND assignment operator.
C << 2
C >>= 2 is same as C =
>>= Right shift AND assignment operator.
C >> 2
C &= 2 is same as C =
&= Bitwise AND assignment operator.
C&2
C ^= 2 is same as C = C
^= Bitwise exclusive OR and assignment operator.
^2
C |= 2 is same as C = C
|= Bitwise inclusive OR and assignment operator.
|2
Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
Expressions in C:
1. Arithmetic Expressions
Operators: +, -, *, /, %
Example: a + b * (c - d) / e
2. Relational Expressions
These compare two values and yield a boolean result (true or false).
3. Logical Expressions
4. Bitwise Expressions
Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >>
(right shift)
Example: x & y
5. Assignment Expressions
These assign a value to a variable. Assignment operators can also combine assignment with arithmetic
operations.
7. Comma Expressions
These allow multiple expressions to be evaluated in a single statement, with the result being the value of
the last expression.
Operator: ,
Example: a = (b = 2, b + 3); (Here, b is first assigned 2, then b + 3 is evaluated, resulting in 5.)
8. Unary Expressions
9. Pointer Expressions
Operators: * (dereference), & (address-of), -> (member access through pointer), [] (array
subscripting)
Example: *(ptr + 2)
These involve calling functions and using their return values in expressions.
Example: max(a, b) + 10 where max is a function that returns the maximum of a and b.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
1. Using getchar()
getchar() reads a single character from standard input (usually the keyboard). It returns the
character read as an int, which allows it to return EOF if there’s an error or if the end of the file is
reached.
Example:
#include <stdio.h>
int main() {
int c;
return 0;
}
2. Using scanf()
scanf() can also be used to read characters. Use %c as the format specifier.
#include <stdio.h>
int main() {
char ch;
return 0;
}
Character Output
1. Using putchar()
#include <stdio.h>
int main() {
char ch = 'A';
return 0;
}
2. Using printf()
printf() can be used for more complex formatting. Use %c to print a character.
#include <stdio.h>
int main() {
char ch = 'B';
printf("The character is: %c\n", ch); // Output the character with formatting
return 0;
}
Handling Multiple Characters
Inputting a String
To read a string (an array of characters), use %s with scanf(). Note that scanf() will stop reading at
the first whitespace character.
#include <stdio.h>
int main() {
char str[100];
return 0;
}
Reading a Line
#include <stdio.h>
int main() {
char line[100];
return 0;
}
1. String Input
Using scanf()
scanf() can be used to read strings, but it will stop reading at the first whitespace character.
#include <stdio.h>
int main() {
char str[100];
return 0;
}
Note:
scanf("%99s", str); // Read up to 99 characters, leaving space for the null terminator
Using fgets()
fgets() reads a whole line, including spaces, until a newline character or the end of the file is encountered,
or until the specified number of characters are read.
#include <stdio.h>
int main() {
char str[100];
printf("Enter a line of text: ");
fgets(str, sizeof(str), stdin); // Read a whole line (including spaces)
printf("You entered: %s", str); // Output the string
return 0;
}
Note: fgets() includes the newline character if it fits in the buffer, so you might need to remove it if
it's not desired:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a line of text: ");
if (fgets(str, sizeof(str), stdin)) {
// Remove trailing newline character if present
size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}
}
printf("You entered: %s\n", str);
return 0;
}
2. String Output
Using printf()
c
Copy code
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("The string is: %s\n", str); // Output the string
return 0;
}
Using puts()
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
return 0;
}
Formatted input and output in C
Formatted input and output in C are handled using the printf and scanf family of functions from the C
Standard I/O library (<stdio.h>). These functions allow you to format data for output and interpret
formatted data from input.
The printf() function allows you to format data before printing it to the standard output (usually the
console). Here are some common format specifiers and options:
%d or %i: Integer
%f: Floating-point number
%c: Character
%s: String
%u: Unsigned integer
%x or %X: Hexadecimal integer
%o: Octal integer
%p: Pointer address
Formatting Options
Field Width: Specifies the minimum number of characters to be printed. Example: %5d prints an
integer in a field of at least 5 characters wide.
Precision: For floating-point numbers, it specifies the number of digits after the decimal point.
Example: %.2f prints a float with 2 decimal places.
Flags: Control alignment and padding.
o -: Left-align the output (default is right-align).
o 0: Pad the output with zeros instead of spaces.
Examples:
#include <stdio.h>
int main() {
int num = 42;
float pi = 3.14159;
char ch = 'A';
char str[] = "Hello, World!";
// Character
printf("Character: %c\n", ch);
// String
printf("String: %s\n", str);
// Hexadecimal and octal
printf("Hexadecimal: %x\n", num);
printf("Octal: %o\n", num);
// Left alignment
printf("Left-aligned: %-5d\n", num);
return 0;
}
2. Formatted Input with scanf()
The scanf() function reads formatted input from the standard input. It uses format specifiers to interpret the
data entered by the user.
%d or %i: Integer
%f: Floating-point number
%c: Character
%s: String (stops at whitespace)
%u: Unsigned integer
%x or %X: Hexadecimal integer
Examples:
#include <stdio.h>
int main() {
int num;
float pi;
char ch;
char str[100];
// Read an integer
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
In programming, we come across situations when we need to make some decisions. Based on these
decisions, we decide what should we do next. Similar situations arise in algorithms too where we need to
make some decisions and based on these decisions, we will execute the next block of code.
The next instruction depends on a Boolean expression, whether the condition is determined to be True or
False. C programming language assumes any non-zero and non-null values as True, and if it is either zero
or null, then it is assumed as a False value.
if statement
1
An if statement consists of a boolean expression followed by one or more statements.
if...else statement
2 An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
nested if statements
3
You can use one if or else-if statement inside another if or else-if statement(s).
switch statement
4
A switch statement allows a variable to be tested for equality against a list of values.
If Statement in C Programming
The if statement is used for deciding between two paths based on a True or False outcome. It is represented
by the following flowchart −
Syntax
if (Condition){
expression;
...
}
Example:
#include <stdio.h>
int main() {
int num;
if (num > 0) {
printf("The number is positive.\n");
}
return 0;
}
The if–else statement offers an alternative path when the condition isn't met.
Syntax
if (condition){
expression;
...
else{
expression;
. . .\
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Example:
#include <stdio.h>
int main() {
int num;
scanf("%d", &num);
if (num % 2 == 0) {
} else {
return 0;
}
Nested If Statements in C Programming
Nested if statements are required to build intricate decision trees, evaluating multiple nested conditions for
nuanced program flow.
You can use one if or else-if statement inside another if or else-if statement(s).
Syntax
The syntax of nested if statements is as follows –
if (condition-1){
if (condition- 2){
else{
Example:
#include <stdio.h>
int main() {
int score;
scanf("%d", &score);
if (score >= 90) {
printf("Grade: A\n");
printf("Grade: B\n");
printf("Grade: C\n");
printf("Grade: D\n");
} else {
printf("Grade: F\n");
return 0;
A switch statement simplifies multi-way choices by evaluating a single variable against multiple values,
executing specific code based on the match. It allows a variable to be tested for equality against a list of
values.
Syntax
switch(expression) {
case constant-expression:
statement(s);
break; /* optional */
case constant-expression:
statement(s);
break; /* optional */
default: /* Optional */
statement(s);
As in if statements, you can use one switch statement inside another switch statement(s).
Example:
#include <stdio.h>
int main() {
int day;
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
break;
return 0;
We have covered the conditional operator (?:) in the previous chapter which can be used to replace if-
else statements. It condenses an if-else statement into a single expression, offering compact and readable
code.
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon (:). The value of a
"?" expression is determined like this −
Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the : expression.
Loop control structures
Loop control structures in C are used to execute a block of code repeatedly based on certain conditions.
The primary loop control structures in C are for, while, and do-while loops. Here’s an overview of each,
along with examples.
1. for Loop
The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and iteration expression.
Syntax:
// Code to be executed
#include <stdio.h>
int main() {
int i;
printf("%d\n", i);
return 0;
2. while Loop
The while loop is used when the number of iterations is not known and depends on a condition. The loop
continues as long as the condition is true.
Syntax:
while (condition) {
// Code to be executed
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
return 0;
3. do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at
least once before the condition is tested.
Syntax:
do {
// Code to be executed
} while (condition);
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
return 0;
The break and continue statements in C are used to alter the flow of execution within loops. They are
useful for controlling the flow of your program and handling specific conditions during iteration.
1. break Statement
The break statement is used to exit from the nearest enclosing loop or switch statement. When break is
encountered, the control flow immediately jumps to the statement following the loop or switch.
Syntax:
break;
Example: Using break to exit a for loop when a condition is met.
#include <stdio.h>
int main() {
int i;
if (i == 6) {
printf("%d\n", i);
return 0;
Explanation: In this example, the for loop will iterate from 1 to 10. However, when i equals 6, the break
statement is executed, which exits the loop. The program then prints a message indicating that the loop was
exited.
2. continue Statement
The continue statement is used to skip the current iteration of the nearest enclosing loop and proceed with
the next iteration. It does not exit the loop but rather jumps to the next iteration.
Syntax:
continue;
#include <stdio.h>
int main() {
int i;
if (i == 3) {
printf("%d\n", i);
}
return 0;
The goto statement in C is a form of unconditional branching that allows you to jump to a different part of
the program. While it can be useful in certain scenarios, its use is generally discouraged because it can
make code less readable and harder to maintain. Instead, structured control flow statements like loops and
conditionals are often preferred.
Syntax of goto
goto label;
Label Syntax:
label_name:
// Code to be executed
Basic Example
Here's a simple example that demonstrates the use of goto to jump to a specific point in the program:
#include <stdio.h>
int main() {
int num = 5;
if (num > 0) {
goto positive;
} else {
goto non_positive;
positive:
goto end;
non_positive:
end:
printf("End of program.\n");
return 0;