Computer Applications: C & Python Programming: Unit Ii - Operators and Expressions: Arrays
Computer Applications: C & Python Programming: Unit Ii - Operators and Expressions: Arrays
COMPUTER APPLICATIONS: C
& PYTHON PROGRAMMING
C OPERATORS
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise, etc.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
ARITHMETIC OPERATORS
You can use an arithmetic operator with one or two arguments to add, subtract, multiply,
and divide numeric values.
i. 5 + 3 = 8
ii. 5 – 3 = 2
iii. 5 * 3 = 15
i. z=x+y
ii. no1 = x – y
iii. age = a * b + c
iv. velocity = distance / time
v. force = mass * acceleration
vi. count = count + 1
Integer Arithmetic
• When an arithmetic operation is performed on two whole numbers or integers than such
an operation is called as integer arithmetic.
Example
Let x = 27 and y = 5 be two integer numbers. Then the integer operation leads to the following
results:
i. x + y = 32
ii. x – y = 22
iii. x * y = 115
iv. x% y=2
v. x/ y=5
Floating-point Arithmetic
• When an arithmetic operation is preformed on two real numbers or fraction numbers such an
operation is called floating-point arithmetic.
Floating-point Arithmetic
Example
i. x + y = 18.0
ii. x – y = 10.0
iii. x * y = 56.0
iv. x / y = 3.50
RELATIONAL OPERATORS
• An operator that compares two values.
For example, the expression:
• This expression will have a value of TRUE if the variable x is less than 5; otherwise the
value of the expression will be FALSE.
• Relational operators are sometimes called comparison operators.
• Expressions that contain relational operators are called relational expressions.
• A simple relational expression contains only one relational operator and takes the
following form:
Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them.
Example:
i. x<y = True
ii. (x + 2) > (y * 2) = False
iii. (x + 3) <= y = True
iv. x != y = True
v. y > (3 + x) = False
LOGICAL OPERATORS
• An operator that compare or evaluate logical and relational expressions.
• The following are logical operators:
Operator Name
|| Logical OR
! Logical NOT
Logical AND
• This operator is used to evaluate two conditions or expressions with relational operators
simultaneously.
• If both the expressions to the left and to the right of the logical operator is true then the
whole compound expression is true.
Example:
The expression to the left is a > b and that on the right is x == 10, the whole expression is true
only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Example:
Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:
Logical OR
• The logical OR is used to combine two expressions or the condition evaluates to true if any
one of the 2 expressions is true.
• The expression evaluates to true if any one of them is true or if both of them are true.
Example:
(a < m) || (a < n)
The expression evaluates to true if any one of them is true or if both of them are true.
Example:
Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:
i. (a > b) || (c != 5) = False
ii. (a < b) || (c < b) = True
Logical NOT
• The logical NOT operator takes single expression and evaluates to true if the expression is
false and evaluates to false if the expression is true.
False True
Example:
! (x >= y)
The NOT expression evaluates to true only if the value of x is neither greater than or equal to y
Example:
++ variable name
variable name++
– –variable name
variable name– –
• The increment operator ++ adds the value 1 to the current value of operand.
• The decrement operator – – subtracts the value 1 from the current value of operand.
Example:
Suppose if we rewrite the above statement as
Consider the following:
m = 5;
m = 5; y = ++m; (prefix)
y = m++; (postfix)
In this case the value of y and m would
be 6. Then the value of y will be 5 and that of m will
be 6.
• A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on the left.
• On the other hand, a postfix operator first assigns the value to the variable on the left and
then increments the operand.
Example 1:
x=4
y = ++x
PRINT
x
PRINT
y
What is the output? 5 5
Example 2:
x=3
y = x++
PRINT
x
PRINT
y
What is the output?
ASSIGNMENT OPERATORS
There are different kinds of the operators, such as arithmetic, relational, bitwise, assignment, etc.,
in the C programming language. The assignment operator is used to assign the value, variable
and function to another variable. Let's discuss the various types of the assignment operators such
as =, +=, -=, /=, *= and %=.
It is the operator used to assign the right side operand or variable to the left side variable.
Syntax
int a = 5;
or int b = a;
ch = 'a';
Program1.c
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c, x, y;
n1 = 5;
n2 = n1;
c = n1 + n2;
x = 20 / 4 * 2 + 5;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);
printf (" \n The value of c: %d", c);
printf (" \n The value of x: %d", x);
return 0;
}
Output
The operator is used to add the left side operand to the left operand and then assign results
to the left operand.
Syntax
A +=
B;
Or
A = A + B;
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
int n1, n2, c;
n1 = 5;
n2 = 10;
n2 += n1;
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);
return 0;
}
Output
of 5 b: 15
The value of a: 5
The value of b: 15
Let's create a program to use the Subtract and Assign (-=) operator in C.
Program3.c
#include <stdio.h>
#include <conio.h>
int main ()
{
// initialize variables
return 0;
}
Output
The operator is used to multiply the left operand with the right operand and then assign
result to the left operand.
Syntax
A *=
B;
Or
A = A * B;
Let's create a program to use the multiply and assign operator (*=) in C. Multiply
and Assign Operator (*=)
The operator is used to multiply the left operand with the right operand and then assign result
to the left operand.
Syntax
A *=B;
Or
A = A * B;
Let's create a program to use the multiply and assign operator (*=) in C.
CONDITIONAL OPERATOR
The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.
- In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator.
- In this condition, we are checking the age of the user. If the age of the user is greater than or
equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting")) otherwise,
statement2 will execute, i.e., (printf("not eligible for voting")).
If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:
As we can observe from the above two outputs that if the condition is true, then the statement1 is
executed; otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and based on
condition, it executes the statements. Now, we will see how a conditional operator is used to
assign the value to a variable.
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to
the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using the
conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value otherwise
2.
Output
The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is equal
to 5.
As we know that the behavior of conditional operator and 'if-else' is similar but they have
some differences. Let's look at their differences.
ARITHMETIC EXPRESSIONS
The plus sign (+) is used to add two values, the minus sign (-) to subtract one value from
another, the asterisk(*) to multiply two values, the division (/) to divide a value and the
modulus (%) to obtain the reminder of integer division. These are known as binary
operators since they operate on two values or variables.
result = x - y;
Notice the equal sign (=) in the above expressions, it is known as the assignment
operator. It assigns the value on the right hand side of the equal sign to the variable on the left
hand side.
In the last expression, parentheses are used to perform a certain operation first. This is
because in C, operators follow a precedence rule. *, / and % have a higher precedence
over + and -.
Hence to override the precedence, parentheses should be used. Expressions having
operators of the same precedence are generally evaluated from left to right.
Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value.
Program
#include
main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;
Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.
Infix Expressions are harder for Computers to evaluate because of the additional work
needed to decide precedence. Infix notation is how expressions are written and
recognized by humans and, generally, input to programs.
Given that they are harder to evaluate, they are generally converted to one of the two
remaining forms.
This algorithm takes as input an Infix Expression and produces a queue that has this
expression converted to postfix notation.
The same algorithm can be modified so that it outputs the result of the evaluation of
expression instead of a queue. The trick is using two stacks instead of one, one for
operands, and one for operators.
o 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.
Example
main() {
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d;
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d;
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d);
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d;
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
When you compile and execute the above program, it produces the following result
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
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid loss of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
It is possible for implicit conversions to lose information, signs can be lost (when signed
is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).
x = 107, z = 108.000000
This process is also called type casting and it is user defined. Here the user can type cast the
result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
#include<stdio.h>
int main()
{
double x = 1.2;
sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
Output:
sum = 2
This is done to take advantage of certain features of type hierarchies or type representations.
It helps us to compute expressions containing variables of different data types.
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.
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.
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;
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d;
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d);
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d;
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
MATHEMATICAL FUNCTIONS
C Math
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.
1) ceil(number) rounds up the given number. It returns the integer value which is greater
than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is less
than or equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
#include<stdio.h>
#include <math.h>
int main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
400
4 Output:
93.7K
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
12
.000000
3.000000
ARRAYS
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together.
This makes it easier to calculate the position of each element by simply adding an offset
to a base value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array).
The base value is index 0 and the difference between the two indexes is the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is placed a
value (let’s say one of your friends).
Here, you can identify the location of any of your friends by simply knowing the
count of the step they are on. Remember: “Location of next index
depends on the data type we use”.
Array’s size
In C language, array has a fixed size meaning once the size is given to it, it cannot be
changed i.e. you can’t shrink it neither can you expand it.
The reason was that for expanding, if we change the size we can’t be sure ( it’s not
possible every time) that we get the next memory location to us as free.
The shrinking will not work because the array, when declared, gets memory statically
II BSc CS UNIT II – C & Py NEETHU DS - SNGC
31
allocated, and thus compiler is the only one can destroy it.
Types of indexing in an array:
0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.
1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
n (n-based indexing): The base index of an array can be freely chosen. Usually, programming
languages allowing n-based indexing also allow negative index values,and other scalar data
types like enumerations, or characters may be used as an array index.
#include <iostream>
using namespace std;
int main()
{
// Creating an integer array named arr of size 10. int
arr[10];
// accessing element at 0 index and setting its value
// to 5.
arr[0] = 5;
// access and print value at 0 index we get the output
// as 5.
cout << arr[0];
return 0;
}
You can’t change the size i.e. once you have declared the array you can’t change its
size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as the
elements are stored in consecutive memory locations and the shifting operation is costly too.
Now if take an example of implementation of data structure Stack using array there
So there what we are doing is that, the pointer to the topmost element is decremented
means we are just bounding our view actually that element stays there taking up of the memory
space. If you have any primitive datatype then it might be ok but the object of an array would
take a lot of memory.
Examples –
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};
000
4.000000
One
di45751
16.00000
0dfd
27.000000
12
The variable allows us to store a single value at a time, what if we want to store roll no.
of 100 students? For this task, we have to declare 100 variables, then assign values to each of
them. What if there are 10000 students or more? As you can see declaring that many variables
for a single entity (i.e student) is not a good idea. In a situation like these arrays provide a better
way to store data.
What is an Array?
An array is a collection of one or more values of the same type. Each value is called an
element of the array. The elements of the array share the same variable name but each element
has its own unique index number (also known as a subscript). An array can be of any type, For
example: int, float, char etc. If an array is of type int then it's elements must be of type int only.
Conceptually you can think of a one-dimensional array as a row, where elements are stored one
after another.
1 int num[100];
2 float temp[20];
3 char ch[50];
num is an array of type int, which can only store 100 elements of type int. temp is
an array of type float, which can only store 20 elements of type float. ch is an array
of type char, which can only store 50 elements of type char.
1 #define SIZE 10
2
3 int main()
4 {
5 int size = 10;
6
7 int my_arr1[SIZE]; // ok
8 int my_arr2[size]; // not allowed until C99
9 // ...
10 }
Note: Until C99 standard, we were not allowed to use variables to specify the size of the array. If
you are using a compiler which supports C99 standard, the above code would compile
successfully. However, If you're using an older version of C compiler like Turbo C++, then you
will get an error.
The use of symbolic constants makes the program maintainable, because later if you want to
change the size of the array you need to modify it at once place only i.e in the
#define directive.
DECLARATION OF ARRAY
An "array declaration" names the array and specifies the type of its elements. It can also
define the number of elements in the array. A variable with array type is considered a pointer to
the type of the array elements.
Syntax
declaration:
declaration-specifiers init-declarator-listopt ;
init-declarator-list:
init-declarator
init-declarator-list , init-declarator
init-declarator:
declarator
declarator = initializer
declarator:
pointeropt direct-declarator
II BSc CS UNIT II – C & Py NEETHU DS - SNGC
37
The first form defines an array variable. The constant-expression argument within the
brackets specifies the number of elements in the array. The constant-expression, if present,
must have integral type, and a value larger than zero. Each element has the type given by
type-specifier, which can be any type except void. An array element cannot be a function
type.
The second form declares a variable that has been defined elsewhere. It omits the
constant-expression argument in brackets, but not the brackets. You can use this form only
if you previously have initialized the array, declared it as a parameter, or declared it as a
reference to an array explicitly defined elsewhere in the program.
In both forms, direct-declarator names the variable and can modify the variable's type. The
brackets ([ ]) following direct-declarator modify the declarator to an array type.
Type qualifiers can appear in the declaration of an object of array type, but the qualifiers apply to
the elements rather than the array itself.
You can declare an array of arrays (a "multidimensional" array) by following the array declarator
with a list of bracketed constant expressions in this form:
Each constant-expression in brackets defines the number of elements in a given dimension: two-
dimensional arrays have two bracketed expressions, three-dimensional arrays have three, and so
on. You can omit the first constant expression if you have initialized the array, declared it as a
parameter, or declared it as a reference to an array explicitly defined elsewhere in the program.
You can define arrays of pointers to various types of objects by using complex declarators, as
described in Interpreting More Complex Declarators.
Arrays are stored by row. For example, the following array consists of two rows with three
columns each:
CCopy
char A[2][3];
The three columns of the first row are stored first, followed by the three columns of the
second row. This means that the last subscript varies most quickly.
Examples
float matrix[10][15];
The two-dimensional array named matrix has 150 elements, each having float type.
struct {
float x, y;
} complex[100];
This is a declaration of an array of structures. This array has 100 elements; each element is a
structure containing two members.
This statement declares the type and name of an array of pointers to char. The actual definition of
name occurs elsewhere.
Microsoft Specific
The type of integer required to hold the maximum size of an array is the size of size_t. Defined
in the header file STDDEF.H, size_t is an unsigned int with the range 0x00000000 to
0x7CFFFFFF.
Array-Basics
int two_d[10][20];
int three_d[10][20][30];
Multi dimensional arrays are the arrays with a single variable name and more than one
subscript. Declaration is as like one dimensional but only change is there in the subscript. It need
data type array name and the subscript (indices).
int multi[10][10][10];
here the multidimensional array ‘multi’ is an integer array the sizes are given as the
subscript.
Matrix
A two dimensional array is called a matrix. Thus it is two dimensional it has two
subscripts. A matrix is used to store a table of values. As it is similar to a table a matrix has rows
and columns. Thus the first subscript refers as the rows and second index as the columns.
Syntax :
Data-type matrix-name[rows][columns];
Example :
int a[2][2];
here a is a matrix with 2 rows and 2 columns. We can say ‘a’ is a 2 x 2 (read 2 by two)
matrix.
Column 0 Column 1
A matrix can be assigned values by specifying bracketed values for each row as Follows.
Here the values enclosed in brackets denotes the rows of the matrix.
This two initializations results as a matrix like
0 1
2 3
For accessing matrix variables we use the subscripts along with the name of the matrix.
But make sure that we number the values of rows and columns from 0. In the above example to
access the value 1 we use a[0][1] that is the position of 1 is in the 0th row and the 1st column.
The dynamic initialization of matrix, need two loops one for row values and another for
column values.
Program to assign the values to the matrix and print that matrix
#include <stdio.h>
void main()
{
int i, j, m, n, a[10][10];
0 10 8
4 9 12
The values are assigned like this and it displays the matrix as
0 10 8
4 9 12
Operations on matrices
As on arrays a set of operations are performed using matrices, they may be
Addition
Subtraction
Multiplication
Transpose etc.
For the first three we need two or more arrays , transpose is done on that same matrix, it is
changing the values on rows to columns and columns as rows.
#include <stdio.h>
int main()
{
int m, n, i, j, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix");
for (i = 0 ; i < m ; i++ )
{
for ( j= 0 ; j < n ; j++)
{
scanf("%d", &first[i][j]);
}
}
printf("Enter the elements of second matrix ");
for ( i = 0 ; i< m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
II BSc CS UNIT II – C & Py NEETHU DS - SNGC
45
scanf("%d", &second[c][d]);
}
}
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
sum[i][j] = first[i][j] + second[i][j];
}
printf("Sum is") ;
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d\t", sum[i][j]);
}
printf("\n");
}
}
first
10 5
20 10
second
9 10
3 25
sum
19 15
23 35
Two – dimensional array is the simplest form of a multidimensional array. We can see a two –
dimensional array as an array of one – dimensional array for easier understanding.
data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
We can declare a two-dimensional integer array say ‘x’ of size 10,20 as:
int x[10][20];
Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row
number and ‘j’ is the column number.
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where
the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two
– dimensional array ‘x’ with 3 rows and 3 columns is shown below:
Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional
array can be initialized.
First Method:
Better Method:
int x[2][1];
The above example represents the element present in the third row and second column.
Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for
row index 2 row number is 2+1 = 3.
To output all the elements of a Two-Dimensional array we can use nested for loops. We will
require two for loops. One to traverse the rows and another to traverse columns.
// Two-Dimensional array
#include<iostream>
using namespace std;
int main()
{
return 0;
Output:
Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5
Three-Dimensional Array
int x[2][3][4] ={{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
{
cout << "Element at x[" << i << "][" << j
<< "][" << k << "] = " << x[i][j][k]
<< endl;
}
}
}
return 0;
}
Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
In similar ways, we can create arrays with any number of dimensions. However, the
complexity also increases as the number of dimensions increases. The most
used multidimensional array is the Two-Dimensional Array.