Unit - 2
Arithmetic expressions, operators and precedence
Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated.
Here is an example of an arithmetic expression with no variables:
3.14*10*10
This expression evaluates to 314, the approximate area of a circle with radius 10. Similarly, the expression
3.14*radius*radius
would also evaluate to 314, if the variable radius stored the value 10.
Note that the parentheses in the last expression helps dictate which order to evaluate the expression.
Multiplication and division have a higher order of precedence than addition and subtraction. In an arithmetic expression, it is evaluated left to right, only performing the multiplications and divisions.
After doing this, process the expression again from left to right, doing all the additions and subtractions.
So,
3+4*5
first evaluates to
3+20 which then evaluates to 23.
Consider this expression:
3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2
First go through and do all the multiplications and divisions:
3 + 20 - 1 + 12 - 24
Integer Division: In particular, if the division has a leftover remainder or fraction, this is simply discarded.
For example:
13/4 evaluates to 3
Every expression in C language contains a set of operators and operands. Operators are the special symbols which are used to indicate the type of operation whereas operands are the data members or variables operating as per operation specified by the operator.
One expression contains one or more sets of operators and operands. So to avoid the ambiguity in execution of expression, C compiler fixed the precedence of operator.
Operators
Depending on the operation, operators are classified into the following category.
Sr. No | Operator | Description | Example |
1 | + | Used to add two operands | Result of A+B is 15 |
2 | - | Used to subtract two operands | Result of A-B is 5 |
3 | * | Used to multiply two operands | Result of A*B is 50 |
4 | / | Used to divide two operands | Result of A/B is 2 |
5 | % | Find reminder of the division of two operand | Result of A%B is 0 |
2. Relational Operators: Relational operators used to compare two operands. Relational operators produce results in terms of binary values. It returns 1 when the result is true and 0 when the result is false. Following are the list of relational operators in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No | Operator | Description | Example |
1 | < | This is less than operator which is used to check whether the value of left operand is less than the value of right operand or not | Result of A<B is false.
|
2 | > | This is greater than the operator which is used to check whether the value of the left operand is greater than the value of the right operand or not. | Result of A>B is true. |
3 | ≤ | This is less than or equal to the operator. | Result of A≤B is false.
|
4 | ≥ | This is greater than or equal to the operator. | Result of A≥B is true. |
5 | == | This is equal to the operator which is used to check if the value of both operands are equal or not. | Result of A==B is false.
|
6 | != | This is not equal to the operator which is used to check if the value of both operands are equal or not. | Result of A!=B is true.
|
3. Logical Operators: Logical operators are used to compare logical values of two operands. Following are the list of logical operators in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No | Operator | Description | Example |
1 | && | This is logical AND, it returns true when both the values are non zero. | Result of (A&&B) is true. |
2 | || | This is logical OR, it returns true when any of two values is non zero. | Result of (A||B) is true. |
3 | ! | This is a logical NOT operator, it is used to reverse the logical state of operands. | Result of !(A&&B) is false. |
4. Assignment Operators: Assignment operator is used to assign the value to a variable. To understand the operation assume variable A contains value 10 and variable contains value 5.
5. Increments and Decrement Operators: These operators are used to increase or decrease the value of a variable by one. Following are the list of logical operators in C language. To understand the operation assume variable A contains value 10.
Sr. No | Operator | Description | Example |
1 | ++ | This is an incremental operator which is used to increase the value of a variable by 1. | Result of (A++) is the value of A is 11. |
2 | -- | This is a decrement operator which is used to decrease the value of a variable by 1. | Result of (A--) is the value of A is 9. |
6. Bitwise Operators: These operators are used to work on each bit of data. These operators can work on the binary data. If the data is non binary then
the computer first of all converts it into binary form and then performs the operation.
Following are the list of logical operators in C language. To understand the
operation assumes variable A contains value 10 and variable contains value 5. So the binary values of
A = 0000 1010 and
B = 0000 0101
Sr. No | Operator | Description | Example |
1 | & | This is bitwise AND | Result of (A&B) is 0000 0000 |
2 | | | This is bitwise OR | Result of (A|B) is 0000 1111 |
3 | ^ | This is bitwise Exclusive | Result of (A^B) is 0000 1111 |
4 | << | This is used to shift bit on left side | Result of (A<<B) is |
5 | >> | This is used to shift bit on right side | Result of (A>>B) is |
Precedence of Operators
Expression may have one or more operators in it. If an expression has multiple operators then these operators are solved according to the hierarchy of operators. Hierarchy determines the order in which these operators are executed.
The highest-priority operators appear at the top of the table, while the lowest-priority operators appear at the bottom. Higher precedence operators will be evaluated first within an expression.
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 |
Key takeaway :
Control structure is the important concept in high level programming languages. Control structures are the instruction or the group of instructions in the programming language which are responsible to determine the sequence of other instructions in the program.
Control structure is used for the reusability of the code. Control structure is useful when the program demands to repeatedly execute blocks of code for a specific number of times or till a certain condition is satisfied. Control structures can control the flow of execution of a program based on some conditions. Following are the advantages of using control structures in C language.
● Increases the reusability of the code
● Reduces complexity, improves clarity, and facilitates debugging and modifying
● Easy to define in flowcharts
● Increases programmer productivity.
● Control statements are also useful in the indentation of the program.
There are two types of control statements
Conditional Branching: In conditional branching decision point is based on the run time logic. Conditional branching makes use of both selection logic and iteration logic. In conditional branching flow of a program is transferred when the specified condition is satisfied.
Fig 1: Flowchart for conditional branching
Unconditional Branching: In Unconditional branching flow of a program is transferred to a particular location without concerning the condition. Unconditional branching makes use of sequential logic. In unconditional branching flow of the program is transferred as per the instruction.
Conditional Branching
In conditional branching change in sequence of statement execution depends upon the specified condition. Conditional statements allow programmers to check a condition and execute certain parts of code depending on the result of conditional expression. Conditional expression must be resulted in Boolean value. In C language, there are two forms of conditional statements:
1. if-----else statement: It is used to select one option between two alternatives
2. switch statement: It is used to select one option between multiple alternative
● if Statements
This statement permits the programmer to allocate conditions on the execution of a statement. If the evaluated condition is found to be true, the single statement following the "if" is executed. If the condition is found to be false, the following statement is skipped. Syntax of the if statement is as follows
if(condition)
{
statement1;
statement2;
}
In the above syntax, “if” is the keyword and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then the compiler will execute statement1 and then statement2. If the condition is not satisfied (false) then the compiler will skip statement1 and directly execute statement2.
If-------else statement;
This statement permits the programmer to execute a statement out of the two statements. If the evaluated condition is found to be true, the single statement following the "if" is executed and the statement following else is skipped. If the condition is found to be false, statement following the "if" is skipped and statement following else is executed.
In this statement “if” part is compulsory whereas “else” is the optional part. For every “if” statement there may be or may not be an “else” statement but for every “else” statement there must be an “if” part otherwise the compiler will give a “Misplaced else” error.
Syntax of the “if----else” statement is as follows
if (condition)
statement1;
else
statement2;
In the above syntax, “if” and “else” are the keywords and conditions in parentheses must evaluate to true or false. If the condition is satisfied (true) then the compiler will execute statement1 and skip statement2. If the condition is not satisfied (false) then the compiler will skip statement1 and directly execute statement2.
Nested if----else statements :
Nested “if-----else” statements are used when a programmer wants to check multiple conditions. Nested “if---else” contains several “if---else” statements, out of which only one statement is executed. Number of “if----else” statements is equal to the number of conditions to be checked. Following is the syntax for nested “if---else” statements for three conditions
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
statement4;
In the above syntax, the compiler first checks condition1, if it tries then it will execute statement1 and skip all the remaining statements. If condition1 is false then compiler directly checks condition2, if it is true then compiler execute statement2 and skip all the remaining statements. If condition2 is also false then compiler directly checks condition3, if it is true then compiler execute statement3 otherwise it will execute statement 4.
Note:
If the test expression is evaluated to true,
• Statements inside the body of if are executed.
• Statements inside the body of else are skipped from execution.
If the test expression is evaluated to false,
• Statements inside the body of else are executed
• Statements inside the body of if are skipped from execution.
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
Program to relate two integers using =, > or < symbol
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
//checks if the two integers are equal.
if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}
//checks if both test expressions are false
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
● Switch Statements
This statement permits the programmer to choose one option out of several options depending on one condition. When the “switch” statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose “case” label value matches with the value of the expression. Syntax for switch statement is as follows:
switch(expression)
{
case constant1:
statements 1;
break;
case constant2 :
statements 2;
break;
…………….
default :
statements n;
break;
}
In the above, “switch”, “case”, “break” and “default” are keywords. Out of which “switch” and “case” are the compulsory keywords whereas “break” and “default” are optional keywords.
● “switch” keyword is used to start a switch statement with a conditional expression.
● “case” is the compulsory keyword which is labeled with a constant value. If the value of expression matches with the case value then the statement followed by the “case” statement is executed.
● “break” is the optional keyword in switch statements. The execution of “break” statement causes the transfer of flow of execution outside the “switch” statements scope. Absence of a “break” statement causes the execution of all the following “case” statements without concerning the value of the expression.
● “default” is the optional keyword in the “switch” statement. When the value of expression is not matched with any of the “case” statements then the statement following the “default” keyword is executed.
Example: Program to spell user entered single digit number in English is as follows
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf(“Enter a number”);
scanf(“%d”, &n);
switch(n)
{
case 0: printf(“\n Zero”);
break;
case 1: printf(“\n One”);
break;
case 2: printf(“\n Two”);
break;
case 3: printf(“\n Three”);
break;
case 4: printf(“\n Four”);
break;
case 5: printf(“\n Five”);
break;
case 6: printf(“\n Six”);
break;
case 7: printf(“\n Seven”);
break;
case 8: printf(“\n Eight”);
break;
case 9: printf(“\n Nine”);
break;
default : printf(“Given number is not single digit number”);
break;
}
getch();
}
Output
Enter a number
5
Five
Unconditional Branching
In unconditional branching statements are executed without concerning the condition. Unconditional statements allow programmers to transfer the flow of execution to any part of the program. In C language, there are four types of unconditional statements:
break;
When a “break” statement is used inside loops then execution of the “break” statement causes the immediate termination of the loop and the compiler will execute the next statement after the loop statement.
2. Goto statement: “goto” statement is used to transfer the flow of a program to any part of the program. The syntax of “go to” statement is as follows
goto label name;
In the above syntax “goto” is a keyword which is used to transfer the flow of execution to the label specified after it. Label is an identifier that is used to mark the target statement to which the control is transferred. The target statement must be labeled and the syntax is as follows
label name statement;
In the above syntax label name can be anything but it should be the same as that of the name of the label specified in the “goto” statement, a colon must follow the label. Each labeled statement within the function must have a unique label, i.e., no two statements can have the same label.
3. Continue statement: It is used mainly with “switch” and “loop” statements. The execution of “continue” instruction, skip the remaining iteration of the loop and transfer the flow of the program to the loop control instruction. Syntax of “continue” statement is as follows
continue;
4. Return statement: The “return” statement terminates the execution of the current function and returns control to the calling function. The “return” statement immediately ends the function, ignoring everything else in the function after it is called. It immediately returns to the calling function and continues from the point that it is called. Return is also able to "return" a value which can be used in the calling function.
Key takeaway :
Iteration statements create loops in the program. In other words, it repeats the set of statements until the condition for termination is met. Iteration statements in C are for, while and do-while.
while statement:
The while loop in C is the most fundamental loop statement. It repeats a statement or block while its controlling expression is true.
The general form is:
while(condition) {
// body of loop
}
The condition can be any boolean expression. The body of the loop will be executed if the conditional expression is true.
Let’s see the simple program of while loop that prints table of 1.
#include<stdio.h>
int main()
{
int i=1;
while(i<;=10)
{
printf(“;%d \n”,i);
i++;
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
tick 1
do-while statement
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
Its general form is:
do{
// body of loop
} while(condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of C’s loops, condition must be a Boolean expression.
The program presented in previous while statement can be rewritten using do-while as:
//example program to illustrate do-while looping
#include <stdio.h>
int main ()
{
int n = 10;
do
{
printf("tick %d", n);
printf("\n");
n--;
}while (n > 0);
}
for loop
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}
The program from previous example can be rewritten using for loop as:
//example program to illustrate for looping
#include <stdio.h>
int main ()
{
int n;
for(n = 10; n>0 ; n--){
printf("tick %d",n);
printf("\n");
}
}
The output of the program is the same as the output from the program in while loop.
There can be more than one statement in the initialization and iteration section. They must be separated with a comma.
//example program to illustrate more than one statement using the comma
// for looping
#include <stdio.h>
int main ()
{
int a, b;
for (a = 1, b = 4; a < b; a++, b--)
{
printf("a = %d \n", a);
printf("b = %d \n", b);
}
}
The output of the program is:
a = 1
b = 4
a = 2
b = 3
Here, the initialization portion sets the values of both a and b. The two comma separated statements in the iteration portion are executed each time the loop repeats.
Nested Loops
Loops can be nested as per requirement. Here is an example of nesting the loops.
// nested loops
#include <stdio.h>
int main ()
{
int i, j;
for (i = 0; i< 8; i++)
{
for (j = i; j < 8; j++)
printf(".");
printf("\n");
}
}
Here, two for loops are nested. The number times the inner loop iterates depends on the value of i in the outer loop.
The output of the program is:
........
.......
......
.....
....
...
..
.
Key takeaway :
Arrays are a type of data structure with a fixed size and each spot containing the same type of value. The length of an array cannot be changed; it is determined at the time the object is created. Each spot in an array contains an element, which can be accessed by its index, or the number that represents the array's location.
Since the index starts at zero, the highest index in a ten-dimensional array is just 9. The 9th part, as shown in the diagram, will be at index 8.
Fig 2: Array
Arrays can be rendered in 1D or 2D.
1 D: 2 D:
1D arrays contain only one row of values, while 2D arrays contain a grid of values of several rows/columns.
An ArrayList is similar to a 1D Array, except that its length is unbounded and you can add as many elements as you like.
When creating a 1D or 2D Array, you must first determine the type of object that will be stored in the array. When creating an array, type the object's name followed by two brackets, which represent the array portion of the creation. When you finally initialize the list, you announce its size.
When creating a 2D list, the only difference is that you now have two sets of brackets, one for the number of rows you want and the other for the number of columns you want.
An ArrayList is generated in a slightly different way. You don't need to specify a size when typing ArrayListobject type here>().
Example :
int[] newArray1D = new int[5]; (Creates a 1D Array of length 5 that holds integers)
int[][] newArray2D = new int[5][6]; (Creates a 2D Array with 5 rows and 6 columns that holds integers)
ArrayList<newList> = new ArrayList(); (Creates an ArrayList that holds as many Strings as needed)
newArray1D[0] = 5; (Sets the first value in the Array to 5)
newArray2D[2][1] = 3; (Sets the value at the 3rd row and 2nd column to 3)
newList.add(“Test”); (Adds the String “Test” to the next available slot in the ArrayList, here being the first spot)
One dimensional array (1D)
A one-dimensional array can be thought of as a row in which elements are stored one after the other.
Syntax
data-type array_name[array_size];
Data type - It specifies the form of the array's elements.
Array name - The array's name. It has to be a legitimate identifier.
Example program for one dimensional array in C:
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf(“value of arr[%d] is %d \n”, i, arr[i]);
}
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Two dimensional array (2D)
An array of arrays can be described as a two-dimensional array. The matrices that make up the 2D array are represented as a series of rows and columns. 2D arrays, on the other hand, are used to implement a data structure that resembles that of a relational database. It makes it simple to store large amounts of data at once, which can then be transferred to any number of functions as required.
Two dimensional array is nothing but array of array.
Syntax :
data_type array_name[num_of_rows][num_of_column];
Key takeaway :
If the size of the array is n then the index ranges from 0 to n-1. There can be an array of integer, floating point or character values. Character array is called a String.
Eg.1 A=
This example illustrates integer array A of size 5.
● Array index ranges from 0 to 4.
● Elements of array are {10, 20, 40, 5, 25}.
Arrays can be categorized in following types
These are described below.
The abstract model of string is implemented by defining a character array data type and we need to include the header file ‘string.h’, to hold all the relevant operations of string. The string header file enables the user to view the complete string and perform various operations on the string. E.g. we can call the ‘strlen’ function to find length of string, ‘strcat’ to concatenate two string, ‘strcpy’ to copy one string to another, ‘strrev’ to reverse the string. The definitions of all these functions are stored in the header file ‘string.h’. So string functions with the user provided data becomes the new data type in ‘C’.
Fig 3: String data type
To use the functions related to strings, users only need to include the ‘string.h’ header file. All the definition details of these functions are kept hidden from the user, and the user can directly use these functions without knowing all the implementation details. This is known as abstraction or hiding.
String Manipulation in C Language
Strings are also called as the array of characters.
● A special character usually known as null character (\0) is used to indicate the end of the string.
● To read and write the string in C program %s access specifier is required.
● C language provides several built in functions for the manipulation of the string
● To use the built in functions for string, users need to include string.h header file.
● Syntax for declaring string is
char string name [size of string];
Char is the data type, and the user can give any name to the string by following all the rules of defining the name of the variable. Size of the string is the number of alphabet users want to store in string.
Example:
Sr. No. | Instructions | Description |
#include<stdio.h> | Header file included | |
2. | #include<conio.h> | Header file included |
3. | void main() | Execution of program begins |
4. | { | String is declare with name str and size of storing 10 alphabets |
5. | char str[10]; | |
6. | clrscr(); | Clear the output of previous screen |
7. | printf("enter a string"); | Print “enter a string” |
8. | scanf("%s",&str); | Entered string is stored at address of str |
9. | printf("\n user entered string is %s",str); | Print: user entered string is (string entered by user) |
10. | getch(); | Used to hold the output screen |
11. | } | Indicates end of scope of main function |
Following are the list of string manipulation function
Sr. No. | String Function | Purpose |
strcat | use to concatenate (append) one string to another | |
2. | Strcmp | use to compare one string with another. (Note: The comparison is case sensitive) |
3. | strchr
| use to locate the first occurrence of a particular character in a given string |
4. | Strcpy | use to copy one string to another. |
5. | Strlen | use to find the length of a string in bytes, |
Key takeaway :
References :