0% found this document useful (0 votes)
23 views

Computer Applications: C & Python Programming: Unit Ii - Operators and Expressions: Arrays

The document discusses various operators in C programming language including: 1. Arithmetic operators that are used to perform mathematical operations like addition, subtraction, multiplication, and division on numeric values. 2. Relational operators like <, >, <=, >= that are used to compare two values and return a boolean result. 3. Logical operators like &&, ||, ! that are used to combine or negate relational or logical expressions and return a boolean result. 4. The precedence and associativity rules that determine the order of evaluation of operators in an expression.

Uploaded by

Rummy Boy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Computer Applications: C & Python Programming: Unit Ii - Operators and Expressions: Arrays

The document discusses various operators in C programming language including: 1. Arithmetic operators that are used to perform mathematical operations like addition, subtraction, multiplication, and division on numeric values. 2. Relational operators like <, >, <=, >= that are used to compare two values and return a boolean result. 3. Logical operators like &&, ||, ! that are used to combine or negate relational or logical expressions and return a boolean result. 4. The precedence and associativity rules that determine the order of evaluation of operators in an expression.

Uploaded by

Rummy Boy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

1

COMPUTER APPLICATIONS: C
& PYTHON PROGRAMMING

UNIT II - OPERATORS AND EXPRESSIONS: ARRAYS

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


2

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.

There are following types of operators to perform different types of operations in C


language.

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.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


3

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

ARITHMETIC OPERATORS

You can use an arithmetic operator with one or two arguments to add, subtract, multiply,
and divide numeric values.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


4

Operator Name Description

+ Addition to add two numbers together

- Subtraction to subtract one number from


another

* Multiplication to multiply one number by


another.

/ Division to divide one number by another.

% Modulus (Remainder) to find the remainder from dividing one


number by another

Arithmetic Operators Example:

i. 5 + 3 = 8

ii. 5 – 3 = 2

iii. 5 * 3 = 15

• *, / and % will be performed before + or - in any expression.

• Brackets can be used to force a different order of evaluation to this.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


5

Here are some arithmetic expressions used within assignment statements:

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.

• It always gives an integer as the result.

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

Let x = 14.0 and y = 4.0 then

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


6

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:

x < 5 means x is less than 5

• 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.

• The following are relational operators:

Operator Name Description

< Less than Indicates whether the value of the left


operand
is less than the value of the right
operand.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


7

<= Less than or equal to Indicates whether the value of the


left operand
is less than or equal to the value of the operand.
right
> Greater than Indicates whether the value of the left
operand
is greater than the value of the right
operand.

>= Greater than or equal to Indicates whether the value of the


left
operand is greater than or equal to of
the value the right operand.

• The following are relational operators:

Operator Name Description

== Equal to Indicates whether the value of the left


operand is equal to the value of the right
operand.

!= Not equal to Indicates whether the value of the left


operand is not equal to the value of the
right operand.

Example:

Let x = 2 and y = 5 then

i. x<y = True
ii. (x + 2) > (y * 2) = False
iii. (x + 3) <= y = True
iv. x != y = True
v. y > (3 + x) = False

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


8

LOGICAL OPERATORS
• An operator that compare or evaluate logical and relational expressions.
• The following are logical operators:

Operator Name

&& Logical AND

|| 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.

Exp1 Exp2 Exp1 && Exp2

False False False

True False False

False True False

True True True

Example:

(a > b) && (x == 10)

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


9

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:

i. (a > b) && (c != 5) = False


ii. (a < b) && (c < b) = False
iii. (a > b) && (c == 5) = False
iv. (a < b) && (b < c) = True

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.

Exp1 Exp2 Exp1 || Exp2

False False False

True False True

False True True

True True 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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


10

iii. (a > b) || (c == 5) = True


iv. (a < b) || (b < c) = 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.

• In other words it just reverses the value of the expression.


Exp1 !Exp1
True False

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:

Given a = 2, b = 3 and c = 5, evaluate the following logical expressions:


a) !(a > b) = True

b) !(a < b) = False

c) !(a > b || c == 5) = False

INCREMENT AND DECREMENT OPERATORS


• The increment and decrement operators are one of the unary operators which are very
useful in programming language.
• They are extensively used in loops.

• The syntax of the operators is given below:

++ variable name
variable name++
– –variable name
variable name– –

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


11

• 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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


12

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 %=.

Example of the Assignment Operators:

A = 5; // use Assignment symbol to assign 5 to the operand


A B = A; // Assign operand A to the B
B = &A; // Assign the address of operand A to the variable
B A = 20 \ 10 * 2 + 5; // assign equation to the variable A

Simple Assignment Operator (=):

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';

It's create a program to use the simple assignment operator in C.

Program1.c
#include <stdio.h>

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


13

#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 value of n1: 5


The value of n2: 5
The value of c: 10
The value of x: 15

Plus and Assign Operator (+=):

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;

Let's create a program to use the Plus and assign operator in C.


Program2.c

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


14

#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

Subtract and Assign Operator (-=):


The operator is used to subtract the left operand with the right operand and then assigns the
result to the left operand.
Syntax
A -=
B;
Or
A = A - B;

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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


15

int n1, n2, c;


n1 = 5;
n2 = 10;
n2 -= n1; // Use Subtract and Equal operator (b = b - a)
printf (" \n The value of n1: %d", n1);
printf (" \n The value of n2: %d", n2);

return 0;
}

Output

The value of n1: 5


The value of n2: 5

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. 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;

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


16

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 ':'.

As conditional operator works on three operands, so it is also known as the ternary


operator.

The behavior of the conditional operator is similar to the 'if-else

- statement as 'if-else' statement is also a decision-making


statement. Syntax of a conditional operator
Expression1? expression2: expression3;
Meaning of the above syntax.
o In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.
Let's understand the ternary or conditional operator through an example.
#include <stdio.h>
int main()
{
int age; // variable declaration printf("Enter
your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // condition al
operator
return 0;
}

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


17

- 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")).

Let's observe the output of the above program.

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.

Let's understand this scenario through an example.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


18

#include <stdio.h> int


main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}

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.

o A conditional operator is a single programming statement, while the 'if-else' statement is


a programming block in which statements come under the parenthesis.
o A conditional operator can also be used for assigning a value to the variable, whereas the
'if-else' statement cannot be used for the assignment purpose.
o It is not useful for executing the statements when the statements are multiple, whereas the
'if-else' statement proves more suitable when executing multiple statements.
o The nested ternary operator is more complex and cannot be easily debugged, while the
nested 'if-else' statement is easy to read and maintain.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


19

ARITHMETIC EXPRESSIONS

C has a wide range of operators. An arithmetic expression is composed of operators and


operands. Operators act on operands to yield a result. Commonly used arithmetic operators are +,
-, *, / and %.

 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.

Following are examples of arithmetic expressions :

result = x - y;

total = principle + interest;


numsquare = x * x;
celcius = (fahrenheit - 32) / 1.8

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;

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


20

int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;

printf("Sum of var1 and var2 is %d\n", result);


result = var3 * var3;
printf("Square of var3 is %d\n", result);
result = var2 +var3 * var4; /* precedence */
printf("var2 + var3 * var4 =%d\n", result);
}
EVALUATION OF EXPRESSION

Evaluate an expression represented by a String. The expression can contain parentheses,


you can assume parentheses are well-matched. For simplicity, you can assume only binary
operations allowed are +, -, *, and /. Arithmetic Expressions can be written in one
of three forms.

Infix Notation: Operators are written between the operands they operate on, e.g. 3 + 4.

Prefix Notation: Operators are written before the operands, e.g + 3 4

Postfix Notation: Operators are written after operands. Eg: 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.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


21

PRECEDENCE OF ARITHMETIC OPERATORS

o Operator precedence determines the grouping of terms in an expression and decides


how an expression is evaluated.

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.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


22

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Example

Try the following example to understand operator precedence in C −


#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 );

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


23

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

TYPE CONVERSION IN EXPRESSION


A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion
Also known as ‘automatic type conversion’.

 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.

bool -> char -> short int -> int ->


unsigned int -> long -> unsigned ->
long long -> float -> double -> long double

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


24

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).

Example of Type Implicit Conversion:


#include<stdio.h>
int main()
{
int x = 10;
char y = 'a';
x = x + y;
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
Output:

x = 107, z = 108.000000

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


25

2. Explicit Type Conversion

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

Advantages of Type Conversion

 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.

OPERATOR PRECEDENCE AND ASSOCIATIVITY


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.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


26

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.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


27

Category Operator Associativity

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Example Code

#include<stdio.h>
main()
{

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


28

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 Programming allows us to perform mathematical operations through the functions defined in


<math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions

There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


29

No. Function Description

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.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of 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:

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


30

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;
}

Advantages of using arrays:


 Arrays allow random access to elements. This makes accessing elements by position faster.
 Arrays have better cache locality that makes a pretty big difference in performance.
 Arrays represent multiple data items of the same type using a single name.

Disadvantages of using arrays:

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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


32

are some obvious flaw.


Let’s take the POP operation of the stack. The algorithm would go something like this.
1. Check for the stack underflow
2. Decrement the top by 1

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


33

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'};

// An Integer array in C/C++/Java


int arr2[] = {10, 20, 30, 40, 50};

// Item at i'th index in array is typically accessed

// as "arr[i]". For example arr1[0] gives us 'g'

// and arr2[3] gives us 40.

Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is


simply called an array.
Applications on Array
1. Array stores data elements of the same data type.
2. Arrays can be used for CPU scheduling.
3. Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc. If
you like GeeksforGeeks and would like to contribute, you can also write an article using
write.geeksforgeeks.org or mail your article to [email protected]. See your article
appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.

000
4.000000
One
di45751
16.00000
0dfd
27.000000
12

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


34

ONE DIMENSIONAL ARRAY

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.

To store roll no. of 100 students, we have to declare an array of size


100 i.e roll_no[100]. Here size of the array is 100 , so it is capable of storing 100 values. In C,
index or subscript starts from 0, so roll_no[0] is the first element, roll_no[1] is the second
element and so on. Note that the last element of the array will be at roll_no[99] not at
roll_no[100] because the index starts at 0.

Arrays can be single or multidimensional. The number of subscript or index determines


the dimensions of the array. An array of one dimension is known as a one- dimensional array or
1-D array, while an array of two dimensions is known as a two- dimensional array or 2-D array.

Let's start with a one-dimensional array.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


35

Conceptually you can think of a one-dimensional array as a row, where elements are stored one
after another.

Syntax: datatype array_name[size];

datatype: It denotes the type of the elements in the array.


array_name: Name of the array. It must be a valid identifier.
size: Number of elements an array can hold. here are some example of array declarations:

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.

Note: When an array is declared it contains garbage values.


The individual elements in the array:
1 num[0], num[1], num[2], ...... , num[99]
2 temp[0], temp[1], temp[2], ....... , temp[19]
3 ch[0], ch[1], ch[2], ..... , ch[49]
We can also use variables and symbolic constants to specify the size of the array.

1 #define SIZE 10

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


36

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

direct-declarator: /* A function declarator */


direct-declarator [ constant-expressionopt ]

Because constant-expression is optional, the syntax has two forms:

 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:

type-specifier declarator [ constant-expression ] [ constant-expression ] ...

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];

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


38

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.

To refer to an individual element of an array, use a subscript expression, as described in


Postfix Operators.

Examples

These examples illustrate array declarations:

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.

extern char *name[];

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.

INITIATING ON TWO AND MULTIDIMENSIONAL ARRAYS

Array-Basics

In C/C++, we can define multidimensional arrays in simple words as an array of


arrays. Data in multidimensional arrays are stored in tabular form (in row-major order).

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


39

The general form of declaring N-dimensional arrays:

data_type array_name[size1][size2] ...... [sizeN];

data_type: Type of data to be stored in the array.


Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, .... ,sizeN: Sizes of the dimensions
Examples:

Two dimensional array:

int two_d[10][20];

Three dimensional array:

int three_d[10][20][30];

Size of multidimensional arrays


The total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

Multi dimensional arrays

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).

The general syntax of multidimensional arrays :

Data-type array-name[index1][index2][index3]… [indexn];

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


40

Example of 4 dimensional array :

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


41

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

Row 0 a[0][0] a[0][1]

Row 1 a[1][0] a[1][1]

Assigning values to the matrix

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


42

A matrix can be assigned values by specifying bracketed values for each row as Follows.

int a[2][2] = {0,1,2,3};

The other method which is more readable is like


Int a[2][2] = {
{0, 1} , //first row
{2,3} //second row
};

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];

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


43

printf("Enter the number of rows and columns of matrix ");


scanf("%d%d", &m, &n);
printf("Enter the elements of matrix ");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
scanf("%d", &a[i][j]);
}
}
printf("The elements of matrix a is");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
printf("%d", a[i][j] “ “);
}
printf(“\n”) // for new line( for rows)
}
}
When execute this program it reads the size and then assign the values to the matrix as , if
m=2,n=3 then the values assigned is like
a[0][0] = 0;
a[0][1] = 10;
a[0][2] = 8;
a[1][0] = 4;
a[1][1] = 9;
a[1][2] = 12;

0 10 8

4 9 12

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


44

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.

Program to add two matrices.

#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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


46

3 25

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


47

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.

 The basic form of declaring a two-dimensional array of size x, y: Syntax:

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:

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}


The above array has 3 rows and 4 columns. The elements in the braces from left to right are
stored in the table also from left to right. The elements will be filled in the array in order, the
first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


48

Better Method:

int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};


This type of initialization makes use of nested braces. Each set of inner braces represents one
row. In the above example, there is a total of three rows so there are three sets of inner braces.
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are
accessed using the row indexes and column indexes.
Example:

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.

// C++ Program to print the elements of a

// Two-Dimensional array
#include<iostream>
using namespace std;
int main()
{

// an array with 3 rows and 2 columns. int


x[3][2] = {{0,1}, {2,3}, {4,5}};
// output each array element's value

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


49

for (int i = 0; i < 3; i++)

for (int j = 0; j < 2; j++)

cout << "Element at x[" << i

<< "][" << j << "]: ";

cout << x[i][j]<<endl;

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

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


50

Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the


same as that of Two-dimensional arrays. The difference is as the number of dimensions increases
so the number of nested braces will also increase. Method 1:

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};
Better Method:

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} }
};

Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional


Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use three
loops instead of two loops for one additional dimension in Three-dimensional Arrays.

// C++ program to print elements of Three-Dimensional


// Array
#include<iostream>
using namespace std;
int main()
{
// initializing the 3-dimensional array int
x[2][3][2] =
{
{ {0,1}, {2,3}, {4,5} },
{ {6,7}, {8,9}, {10,11} }
};

// output each element's value


for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


51

{
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.

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


52

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


53

II BSc CS UNIT II – C & Py NEETHU DS - SNGC


54

II BSc CS UNIT II – C & Py NEETHU DS - SNGC

You might also like