Unit - 2
Arithmetic expressions, operators and precedence
Q.1) Explain operator ?
Ans : Operator
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 |
Q.2) Define while loop ?
Ans : While loop
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition.
It can be viewed as a repeating if statement. The while loop is mostly used in the
case where the number of iterations is not known in advance.
Syntax
The syntax of while loop in c language is given below:
while(condition)
{
//code to be executed
}
Fig 1: flowchart of while loop
Example :
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
Program to print table for the given number using while loop in C
#include<stdio.h>
int main()
{
int i=1,number=0,b=9;
printf(“Enter a number:”);
scanf(“%d”,&number);
while(i<=10)
{
printf(“%d \n”,(number*i));
i++;
}
return 0;
}
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000
Q.3) What are Character arrays and Strings ?
Ans : Character arrays and Strings
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 the 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 2: 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 the 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 the 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, |
Q.4) What do you mean by precedence of operator ?
Ans : Precedence of operator
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 |
Q.5) Describe for loop ?
Ans : for loop
The for loop in C language is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like the
array and linked list.
Syntax
The syntax of for loop in c language is given below:
for(Expression 1; Expression 2; Expression 3)
{
//code to be executed
}
Fig 3: flowchart of for loop
Example :
Let’s see the simple program of for loop that prints table of 1.
#include<stdio.h>
int main()
{
int i=0;
for(i=1;i<;=10;i++)
{
printf(“%d \n”,i);
}
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
#include<stdio.h>
int main()
{
int i=1,number=0;
printf(“Enter a number: “);
scanf(“%d”,&number);
for(i=1;i<=10;i++)
{
printf(“%d \n”,(number*i));
}
return 0;
}
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Q.6) Write short notes on arithmetic expressions ?
Ans : Arithmetic Expression
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.
Q.7) Write properties of while loop ?
Ans : Properties of while loop
● A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
● The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
● In a while loop, the condition expression is compulsory.
● Running a while loop without a body is possible.
● We can have more than one conditional expression in a while loop.
● If the loop body contains only one statement, then the braces are optional.
Q.8) What do you mean by 1D array ?
Ans : 1D Array (one dimensional array)
A one-dimensional array can be thought of as a row in which elements are stored one after the other.
Fig 4: 1D array
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
Q.9) Explain control structure ?
Ans : Control structure
Control structure is an important concept in high level programming languages. Control structures are the instruction or the group of instructions in the programming language which are responsible for determining 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. The conditional branching flow of a program is transferred when the specified condition is satisfied.
Fig 5: 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. The unconditional branching flow of the program is transferred as per the instruction.
Q.10) Explain do while loop ?
Ans : do while loop
The do while loop is a post tested loop. Using the do-while loop, we can repeat the
execution of several parts of the statements. The do-while loop is mainly used in the
case where we need to execute the loop at least once. The do-while loop is mostly
used in menu-driven programs where the termination condition depends upon the
end user.
Syntax :
The syntax of the C language do-while loop is given below:
do
{
//code to be executed
}while(condition);
Example
#include<stdio.h>
#include<stdlib.h>
void main ()
{
char c;
int choice,dummy;
do
{
printf(“\n1. Print Hello\n2. Print Welcome\n3. Exit\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1 :
printf(“Hello”);
break;
case 2:
printf(“Welcome”);
break;
case 3:
exit(0);
break;
default:
printf(“please enter valid choice”);
}
printf(“do you want to enter more?”);
scanf(“%d”,&dummy);
scanf(“%c”,&c);
}while(c==’y’);
}
Output
Print Hello
Print Welcome
Exit
1
Hello
do you want to enter more?
y
Print Hello
Print Welcome
Exit
2
Welcome
do you want to enter more?
n
Fig 6: flowchart of do while loop
Example :
There is given the simple program of c language do while loop where we are printing the table of 1.
#include<stdio.h>
int main()
{
int i=1;
do
{
printf(“%d \n”,i);
i++;
}while(i<=10);
return 0;
}
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
#include<stdio.h>
int main()
{
int i=1,number=0;
printf(“Enter a number: “);
scanf(“%d”,&number);
do
{
printf(“%d \n”,(number*i));
i++;
}while(i<=10);
return 0;
}
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
Infinitive do while loop
Q.11) What do you mean by 2D array ?
Ans : 2D Array (two dimensional array)
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 an array of arrays.
Syntax :
data_type array_name[num_of_rows][num_of_column];
Fig 7: 2D array
2D arrays contain a grid of values of several rows/columns.
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>().
Q.12) Describe if and if else statement ?
Ans : 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.
Q.13) Explain switch statements with examples ?
Ans : 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
Q.14) Write about unconditional branching ?
Ans : 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.