Unit 2
Unit 2
In the example below, we use the + operator to add together two values:
Example
int myNum = 100 + 50;
Although the + operator is often used to add together two values, like in the example above, it can also be
used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
+= x += 3 x=x+3
-= x -= 3 x=x–3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming,
because it helps us to find answers and make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are
known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
== Equal to x == y
!= Not equal x != y
Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
int main() {
int a = 6, b = 3, c = 4;
int res;
printf("%d", res);
return 0;
}
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the associativity for each of
the operators:
Operator
Precedence Description Associativity
* Dereference Operator
12 || Logical OR Left-to-Right
14 = Assignment Right-to-Left
Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC
Relational Operators in C
In C, relational operators are the symbols that are used for comparison between two values to understand
the type of relationship a pair of numbers shares. The result that we get after the relational operation is a
boolean value, that tells whether the comparison is true or false. Relational operators are mainly used in
conditional statements and loops to check the conditions in C programming.
Mixed operand a mixed mode expression is an expression that contains both real and integer operands. When
evaluating a mixed mode expression, the integer operand is converted to a real operand, and the result is a
real value.
If any of the operands in a mixed mode expression are real, the result of the operation will be real.
Mixed mode arithmetic should be used with caution, as it's possible to have two integer operands
when you think you have a real operand.
Examples of mixed mode arithmetic expressions: 1 + 2.5 = 3.5, 1/2.0 = 0.5, 2.0/8 = 0.25, and -3**2.0 = -9.0.
Other C operators:
Sizeof operator: A unary operator that returns the number of bytes an operand occupies
Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with the sizeof operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
Note that we use the %lu format specifer to print the result, instead of %d. It is because the compiler
expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d). On some computers it
might work with %d, but it is safer to use %lu.
Type Conversion in C
In C, type conversion refers to the process of converting one data type to another. It can be done
automatically by the compiler or manually by the programmer. The type conversion is only performed to
those data types where conversion is possible.
Expression: An expression is a combination of operators, constants and variables. An expression may consist
of one or more operands, and zero or more operators to produce a value.
Example:
a+b
s-1/7*f
etc
Types of Expressions:
Constant expressions: Constant Expressions consists of only constant values. A constant value is one
that doesn’t change.
Examples:
5, 10 + 5 / 6.0, 'x’
Integral expressions: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
Floating expressions: Float Expressions are which produce floating point results after implementing
all the automatic and explicit type conversions.
Examples:
x + y, 10.75
Relational expressions: Relational Expressions yield results of type bool which takes a value true or
false. When arithmetic expressions are used on either side of a relational operator, they will be
evaluated first and then the results compared. Relational expressions are also known as Boolean
expressions.
Examples:
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or more relational expressions and produces
bool type results.
Examples:
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are basically
used for testing or shifting bits.
Examples:
x << 3
y >> 1
Shift operators are often used for multiplication and division by powers of two.
C - Decision Making
Decision making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of
the programming languages –
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 false value.
Sr.No
Statement & Description
.
1 if statement
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.
nested if statements
#include <stdio.h>
int main() {
// Declare a variable to store the student's score
int score;
// Prompt the user to enter the score
printf("Enter the student's score: ");
scanf("%d", &score);
// Nested if-else conditions to determine the grade
if (score >= 90) {
printf("Grade: A\n");
} else {
if (score >= 80) {
printf("Grade: B\n");
} else {
if (score >= 70) {
printf("Grade: C\n");
} else {
if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F (Fail)\n");
}
}
}
}
return 0;
}
C - switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C programming language is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Example
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main () {
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200
C - Loops
You may encounter situations, when a block of code needs to be executed several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
Sr.No
Loop Type & Description
.
while loop
1
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
2
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
do...while loop
3
It is more like a while statement, except that it tests the condition at the end of the loop
body.
nested loops
4
You can use one or more loops inside any other while, for, or do..while loop.
Sr.No
Control Statement & Description
.
break statement
1
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
goto statement
3
Transfers control to the labeled statement.
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the
for(;;) construct to signify an infinite loop.
Example Code
#include <stdio.h>
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
C Loops:
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is
less than 5:
Example
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
O/P:
0
1
2
3
4
Note: Do not forget to increase the variable used in the condition (i++), otherwise the loop will never
end!
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
printf("%d\n",10* i);
i++;
}
while (i < =10);
O/P:
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Example
int i;
O/P:
0
1
2
3
4
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true,
the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
This example will only print even values between 0 and 10:
Example
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
O/P:
0
2
4
6
8
10
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
int i, j;
// Outer loop
for (i = 1; i <= 2; ++i) {
printf("Outer: %d\n", i); // Executes 2 times
// Inner loop
for (j = 1; j <= 3; ++j) {
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3)
}
}
O/P:
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
C Break and Continue
Break
O/P:
0
1
2
3
Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 4:
Example
int i;
O/P:
0
1
2
3
5
6
7
8
9
10
Continue Example
int i = 0;
The exit() function is used to terminate a process or function calling immediately in the program. It
means any open file or function belonging to the process is closed immediately as the exit() function
occurred in the program. The exit() function is the standard library function of the C, which is defined in
the stdlib.h header file. So, we can say it is the function that forcefully terminates the current program
and transfers the control to the operating system to exit the program. The exit(0) function determines the
program terminates without any error message, and then the exit(1) function determines the program
forcefully terminates the execution process.
The exit () function is used to break out of a loop. This function causes an immediate termination of
the entire program done by the operation system.
The general form of the exit() function is as follows −
void exit (int code);
The value of the code is returned to the calling process, which is done by an operation system.
Generally, zero is used as return code to indicate normal program termination.
Example
1-
#include <stdio.h>
#include <stdlib.h>
int main ()
{
// declaration of the variables
int i, num;
printf ( " Enter the last number: ");
scanf ( " %d", &num);
for ( i = 1; i<num; i++)
{
// use if statement to check the condition
if ( i == 6 )
exit(0);
else
goto statement in C
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand and
hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program
above or below to goto statement.
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Variations of for loop
1. WAP in C to Printing a right-angled triangle pattern:
*
**
***
****
*****
#include <stdio.h>
#include <conio.h>
Void main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
printf("* ");
}
printf("\n");
}
getch();
}