Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Module-2

The document provides an overview of operators in the C programming language, categorizing them into groups such as arithmetic, relational, equality, logical, bitwise, unary, conditional, and assignment operators. It explains the functionality and usage of each operator type, including examples and syntax. Additionally, it highlights the importance of understanding operator precedence and the evaluation of expressions in C.

Uploaded by

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

Module-2

The document provides an overview of operators in the C programming language, categorizing them into groups such as arithmetic, relational, equality, logical, bitwise, unary, conditional, and assignment operators. It explains the functionality and usage of each operator type, including examples and syntax. Additionally, it highlights the importance of understanding operator precedence and the evaluation of expressions in C.

Uploaded by

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

Course Title : Principles of Programming Using C

Course Code: BPOPS103

Module-2
Faculty:
Dr. Vikhyath K B

Dr H N National College of Engineering


1
Operators in C

9.15 Operators
• An operator is a symbol that specifies the mathematical, logical or relationship
operation to be performed.
• C supports a lot of operators to be used in expressions.
• An expression is a combination of operators, constants and variables.
• An expression may consist of one or more operands, and zero or more operators to
produce a value.

Dr H N National College of Engineering 2


These operators can be categorized into the following
groups:
— Arithmetic operator
— Relation operator
— Equality operator
— Logical operator
— Bitwise operator
— Unary operator
— Conditional operator
— Assignment operator
— Comma operator
— Sizeof operator

Dr H N National College of Engineering 3


9.15.1 Arithmetic operator
— C supports the following operators to perform arithmetic operations which is illustrated
in the following table.
— Arithmetic operators can be applied to any integer or floating point number. The
addition, subtraction and multiplication operators perform usual arithmetic operations
in C program.
— The modulus (%) operator finds remainder of an integer division cannot be applied on
float or double operands.

Dr H N National College of Engineering 4


#include<stdio.h>
int main()
{
float c=20.0;
printf("\n Result = %f:”, c %5);
// Wrong. Modulus operators is being applied to a float operand
return 0;
}
While performing the modulo devision, the sign of the result is the sign of the first
operand.
Example: 16 % 3 = 1
16 % -3 = 1
-16 % 3 = -1
-16 % -3 = -1

Dr H N National College of Engineering 5


9.15.2 Relational Operators
— They are also called as comparison operators which compares two values. Expressions
that contain relational operators are called as relational expressions.
— They return true or false value depending on whether the conditional relationship
between the two operands holds or not.
— Relational operators are used to determine the relationship between the operands. They
are evaluated from left to right.
— The following are the relational operators supported in C:

Dr H N National College of Engineering 6


— When arithmetic expressions are used on either side of the relational operators, first
arithmetic expression is evaluated and then result will be compared.
— Relational operators should not be used to compare the strings as this will result in
comparing the address of the string and not their string.

#include <stdio.h>
int main()
{
int x=10, y=20;
printf(" \n %d < %d = %d", x, y, x<y);
printf(" \n %d == %d = %d", x, y, x==y);
printf(" \n %d != %d = %d", x, y, x!=y);
printf(" \n %d > %d = %d", x, y, x>y);
printf(" \n %d >= %d = %d", x, y, x>=y);
printf(" \n %d <= %d = %d", x, y, x<=y);
return 0;
}

Dr H N National College of Engineering 7


Output:
10 < 20 = 1

10 == 20 = 0

10 != 20 = 1

10 > 20 = 0

10 >= 20 = 0

10 <= 20 = 1

Dr H N National College of Engineering 8


9.15.3 Equality Operators
— C language supports two types of equality operators to compare their operands for
strict equality or inequality.

— They are equal to (==) and not equal to (! =) operators. The equality operators have
lower precedence than the relational operators.

— The equal to operator returns true (1) if both the sides of the operator have the same
value otherwise, it returns false (0). On the contrary side, the not equal to operator
returns true if the operands do not have the same value else it returns false.

Dr H N National College of Engineering 9


9.15.4 Logical Operators
— C language supports three logical operators- logical AND (&&), logical
OR (||), logical NOT (!)

— Logical operators are also evaluated from left to right.

Logical AND (&&):

— It is used to simultaneously evaluate two conditions or expressions with


relational operators.

— If the expressions on both the sides (left and right side) of the logical
operator is true, then the whole expression is true.

Dr H N National College of Engineering 10


¨ The truth table of logical AND is given in the above table Example : a=10 , b=20;
a<40 && b>a will evaluate to 1(TRUE)

Dr H N National College of Engineering 11


Logical OR
— Logical OR (||)
— It is used to simultaneously evaluate two conditions or expressions with relational
operators.

— If the one or both the expressions on both the sides (left and right side) of the logical
operator is true, then the whole expression is true.

— The truth table of logical OR is given in the following table example: a= 5, b =10
(a>b) || (b<30) will be TRUE(1)

Dr H N National College of Engineering 12


Logical NOT
— Logical NOT (!)
— It takes a single expression and negates the value of the expression.
— It produces a zero if the expression evaluates a non-zero value and
produces 1 if expression produces zero.
— It just reverses the value of the expression.
— For example: int a=10, b; (here, a=10 and !a=0. The value of !a is
assigned to b) b=!a;

Dr H N National College of Engineering 13


9.15.5 Unary Operator
These operators act on single operands. C supports three unary operators.
Unary Minus
Increment
Decrement
Unary Minus:
¨ Unary minus (-) is different from binary arithmetic operator that operates on two operands and
performs subtraction operation.
¨ When an operand is preceded by a minus sign, the unary operator negates its value.
¨ If a number is positive then it becomes negative when preceded by a unary minus operator,
similarly if the number is negative, it becomes positive after applying the unary operator.
¨ Example: consider the declaration int a, b=10;
a= (-b);
the result of this expression is a= -10

Dr H N National College of Engineering 14


Increment (++) and Decrement (--)
operators
— The increment operator (++) is a unary operator that increases the value of the
operand by 1. Similarly, the decrement operator (--) is a unary operator that
decreases the value of the operand by 1.
Example: x-- means x=x-1

— The increment/decrement operator has two variants- prefix and postfix.

— In a prefix expression (++x or - -x), the operator is applied before an operand is


used for the computation.

— On the other side, in a postfix expression (x++ or x- -) an operator is applied


after an operand is used for computation of the expression in which it occurs.

— One important is that, ++x is not same as x++. Similarly, x- - or - - x are


different.

Dr H N National College of Engineering 15


Example:

int x=10, y;
y=x++; is equivalent to writing as
y=x;
x=x+1;

whereas, y=++x; is equivalent in writing as

x=x+1;
y=x;

Dr H N National College of Engineering 16


Write a program to illustrate the use of unary prefix
increment and decrement operators.
#include <stdio.h>
int main() {
int num=3;
// Using unary prefix increment operator
printf(" \n The value of num = %d", num);
printf(" \n The value of ++num = %d", ++num);
printf(" \n The value of num = %d", num);
// Using unary prefix decremnet operator
printf(" \n The value of num = %d", num);
printf(" \n The value of --num = %d", --num);
printf(" \n The value of num = %d", num);
return 0;
}

Dr H N National College of Engineering 17


Output:
— The value of num = 3

— The value of ++num = 4

— The value of num = 4

— The value of num = 4

— The value of --num = 3

— The value of num = 3

Dr H N National College of Engineering 18


9.15.6 Conditional Operators
— The conditional or ternary operator (? :) is equivalent to simple if-else statement that can be
used within expressions.

— The syntax of the conditional operator is

exp1? exp2: exp3

— exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result of the
expression, otherwise exp3 is evaluated and becomes the result of the expression.

— Example:

— large= (a>b)? a: b

Dr H N National College of Engineering 19


Example program: To find largest of two numbers using
conditional operator
#include<stdio.h>
int main ()
{
int num1, num2, max;
printf (“enter the values of num1 and num2\n”);
scanf (“%d%d”, &num1, &num2);
max=num1>num2? num1:num2;
printf (“largest is %d\n”, max);
return 0;
}
Output: Enter the values of num1 and num2
— 20
— 30
— Largest is 30

Dr H N National College of Engineering 20


9.15.7 Bitwise Operators
— These are the operators that perform the operations at bit level.

— They include bitwise AND, bitwise OR, bitwise XOR and shift operators.

— Bitwise operators expect their operands to be integers and they treat them as sequence of bits.

BITWISE AND (&)

¨ It is the smaller version of Boolean AND (&&) as it performs on the bits instead of bytes,
characters, integers etc.,
¨ When we use bitwise AND, the bit in the first operand is ANDed with the corresponding bit in
the second operand.
¨ The truth table is same as the logical AND operation. If both the bits are 1, the corresponding bit
in the result is 1 or 0 otherwise.

Dr H N National College of Engineering 21


Example:
— 10101010 & 01010101 = 00000000
— int a=10, b=12, c;
— c= a & b;

— Here, c = a & b
— = 00001010 & 00001100

— c = 00001000

— Therefore c = 8

Dr H N National College of Engineering 22


BITWISE OR (|)

¨ It is the smaller version of Boolean OR (||) as it performs on the bits instead of bytes,
characters, integers etc.,

¨ When we use bitwise OR, the bit in the first operand is ORed with the corresponding bit in the
second operand.

¨ The truth table is same as the logical OR operation. If one or both bits are 1, the corresponding
bit in the result is 1 or 0 otherwise.

Dr H N National College of Engineering 23


Example:

¨ 10101010 | 01010101 = 11111111


¨ int a = 10, b = 12;
¨ c = a | b;
¨ Here, c = a | b
¨ 00001010 | 00001100 c = 00001110
¨ Therefore c = 14

Dr H N National College of Engineering 24


BITWISE XOR (^):
— When we use the bitwise XOR operator, the bit in the first operand is
XORed with corresponding bit in the second operand.
— The truth table of XOR is as shown in the table
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

— The bitwise XOR operator compares each bit of its first operand with
the corresponding bit its second operand. If one of the bits is 1, the
corresponding bit in the result is 1 or 0 otherwise.

Dr H N National College of Engineering 25


Example:
— 10101010 ^ 11010111 = 01111101
— int a=10, b=12, c;

c = a ^ b;
Here, c = a ^ b

— 00001010 ^ 00001100

— c = 00000110

— Therefore c = 6

Dr H N National College of Engineering 26


BITWISE NOT (~):

— It is a unary operator which performs the logical negation on each bit of


the operand. By performing negation of each bit of the operand, it
actually produces the 1s complement of the given binary value.

— Bitwise NOT operator sets the bit to 1 if it was initially 0 and sets to 0 if
1

Example:

— ~10101010 = 01010101

Dr H N National College of Engineering 27


SHIFT OPERATOR:

¨ C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>). These
operations are simple and are responsible for shifting bits either to left or to right.

¨ The syntax for a shift operation is given as

operand op num

¨ where the bits in operand are shifted left or shifted right depending upon the operator by the
number of places denoted by num.

Dr H N National College of Engineering 28


Example:

— x = 00011101 then

— x << 1

— Produces: 00111010

— x<<4

— Produces: 11010000

Dr H N National College of Engineering 29


9.15.8 Assignment Operator
¨ In C, assignment operator is responsible for assigning the values to variables.

¨ While the equal sign (=) is the fundamental assignment operator, C also supports other
assignment operators that provides simpler ways to represent the common variable
assignments.

¨ When an equal sign is encountered in an expression, the compiler processes the statement on
the right side of the sign and assigns the result to the variable on the left side.

Example:- int k; k = 10; à this assigns value 10 to variable k


If we have in the declaration
int x = 2, y = 3, sum = 0;
sum = x + y;
then sum = 5
¨

Dr H N National College of Engineering 30


¨ The assignment operator has right to left associativity consider an expression, a=b=c=10; is
evaluated as:

¨ (a=(b=(c=10)));

¨ First 10 is assigned to c, then value of c is assigned to b and finally the value of b is assigned to a.

¨ The operand to the left of assignment operator must always be a variable name. C does not
allow any expression, constant or function to be placed to the left of the assignment operator.

¨ Therefore, the statement a+b=0 is invalid in C

Dr H N National College of Engineering 31


Other assignment operators: C supports a set of shorthand assignment operators
of the form:
Syntax:
variable op = expression
where op is a binary arithmetic operator. The table illustrates the list of shorthand
assignment operators.

The advantages of using shorthand assignment


operators are as follows:

They are easy to read as they are more concise.

They are also more efficient and easy to understand.

Dr H N National College of Engineering 32


Dr H N National College of Engineering 33
9.15.9 COMMA Operator
¨ The comma operator in C accepts two operands.

¨ It is evaluated in left-to-right sequence with the right most value yielding the result of the
expression.

¨ Among the operators, the comma operator is having the lowest precedence.

Example:

¨ Int a=2, b=3, x=0;


¨ x=(++a, b+=a);
¨ The value of x=6

Dr H N National College of Engineering 34


9.15.10 Sizeof Operator
¨ It is a unary operator which is used to find out the size of data types. This is applied to all
datatypes.
¨ When using this operator, the keyword sizeof is followed by the type name, variable name or
expression.
¨ The operator returns the size of the variable, datatype or expression in bytes.

Example:

¨ int a=10;
¨ int result;
¨ result = sizeof(a);
¨ Then result is 2 or 4, that is the space required to store the variable in memory. Since “a” is an
integer, it requires 2 or 4 bytes of storage space.

Dr H N National College of Engineering 35


9.15.11 Operator Precedence Chart
¨ C operators have two properties: priority and associativity.

¨ When an expression has more than one operator, then it is the relative priorities of
the operator with respect to each other which determines the order in which
expression is evaluated.

¨ Associativity refers to the direction in which operator having the same precedence
acts as operands. it can be either left-to right associativity or from right-to-left
associativity.

Rules for evaluation of expression:


¨ First parenthesized sub expression from left to right are evaluated.

¨ If parentheses are nested, the evaluation begins with the innermost sub expression.

Dr H N National College of Engineering 36


¨ The precedence rule is applied in determining the order of application
of operators in evaluating sub expressions.

¨ The associatively rule is applied when two or more operators of the


same precedence level appear in a sub expression.

¨ Arithmetic expressions are evaluated from left to right using the rules of
precedence.

¨ When parentheses are used, the expressions within parentheses


assume highest priority.

Dr H N National College of Engineering 37


Dr H N National College of Engineering 38
Evaluate the expression using the precedence chart:

— 1. x=3*4+5*6
– = 12 + 5 * 6
– = 12 + 30
– 42
¨ 2. x =3 * ( 4 + 5 ) * 6

– =3*9*6
– = 27 * 6
– 162
— 3. x = 3 * 4 % 5 / 2
– = 12 % 5 /2
– =2/2
– 1

Dr H N National College of Engineering 39


— 4. x=3*(4%5) / 2
– =3 * 4/2
– = 12 / 2
– 6
— 5. x=3*4% (5 / 2)
– =3 * 4%2
– = 12 % 2
– 0
— 6. x=3* ((4%5) / 2)
– =3 * (4 /2)
– =3 * 2
– 6

Dr H N National College of Engineering 40


— Here int a = 0, b = 1, c = -1;
— 7. a += b -= c *= 10
— This is expanded as
– a = a + ( b = b – ( c = c * 10 ) )
– a = a + ( b = 1 – (-10) )
– a = a + ( b = 11 )
– a = 0 + 11
– a = 11
¨ 8. -- a * ( 5 + b ) / 2 – c++ * b
– = --a * 6 / 2 – c++ * b
– = --a * 6 / 2 - -1 * b
– = - 1 * 6 / 2 - -1 * 1
– -1 * 3 - -1 * 1
– -3 - -1 = -2

Dr H N National College of Engineering 41


¨ 9. a*b*c
– = (a * b ) * c ( Because of associativity of * is from left to right)
– =0

¨ 10. a && b
– =0

¨ 11. a < b && c < b


– =1

¨ 12. b + c || ! A
– = ( b + c ) || ( !a)
– 0 || 1
– 1

Dr H N National College of Engineering 42


Write a program to print the ASCII value of a
character
#include <stdio.h>

int main() {
char ch;
printf(" \n Enter any character \n ");
scanf("%c", &ch);
printf( " \n The ASCII value of %c is: %d", ch, ch);
return 0;
}
Output:
— Enter any character
— a
— The ASCII value of a is: 97

Dr H N National College of Engineering 43


Write a program to read a character in upper case
and then print it in lower case.
#include <stdio.h>

int main() {

char ch;
printf(" \n Enter the character in upper case: \n ");
scanf("%c", &ch);
printf( " \n The character in lower case is %c",ch+32);
return 0;
}
Output: Enter the character in upper case:
A
The character in lower case is a

Dr H N National College of Engineering 44


Write a program to print the digit at ones place of a
number.
#include <stdio.h>
int main() {
int num, digit_at_ones_place;
printf(" \n Enter any number \n ");
scanf("%d", &num);
digit_at_ones_place = num % 10;
printf( " \n The digit at ones place of %d is %d", num, digit_at_ones_place);
return 0;
}
Output:
Enter any number
458
The digit at ones place of 458 is 8

Dr H N National College of Engineering 45


Write a program to swap two numbers using a
temporary variable
#include <stdio.h>
int main() {
int num1, num2, temp;
printf(" \n Enter the first and second numbers \n ");
scanf("%d%d", &num1, &num2);
Output:
temp = num1;
Enter the first and second numbers
num1 = num2;
59
num2 = temp;
87
printf( " \n The first number is %d", num1);
The first number is 87
printf( " \n The second number is %d", num2);
The second number is 59
return 0;
}

Dr H N National College of Engineering 46


Write a program to swap two numbers without using
a temporary variable
#include <stdio.h>
int main()
{
int num1, num2, temp;
printf(" \n Enter the first and second numbers \n ");
scanf("%d%d", &num1, &num2);
num1 = num1 + num2; Output:
num2 = num1 – num2;
Enter the first and second numbers
num1 = num1 – num2;
3
printf( " \n The first number is %d", num1);
5
printf( " \n The second number is %d", num2);
The first number is 5
return 0;
The second number is 3
}

Dr H N National College of Engineering 47


Write a program to convert degrees Fahrenheit into
degrees Celsius.
#include <stdio.h>
int main() {
float fahrenheit, celsius;
printf(" \n Enter the temperature in fahrenheit \n");
scanf("%f", &fahrenheit);
celsius=(0.56)*(fahrenheit-32);
printf( " \n The temperature in degree celsius = %f", celsius);
return 0;
}
Output:
Enter the temperature in fahrenheit
32
The temperature in degree celsius = 0.000000`

Dr H N National College of Engineering 48


9.16.1 Type Conversion and Typecasting
— Type conversion or type casting of variables refers to changing a variable of one data
type into another.

— Type conversion is done implicitly, whereas typecasting has to be done explicitly by


the programmer.

9.16.1 Type Conversion:

— Type conversion is done when the expression has variables of different data types.

— To evaluate the expression, the data type is promoted from lower to higher level.

— The hierarchy of data types (from higher to lower) are given as: Double, float, int,
short, and, char.

Dr H N National College of Engineering 49


Dr H N National College of Engineering 50
Examples:
1. int a = 5;
— float b = 6.5, c;
— c = a + b;
Here, c = 5 + 6.5
= 5.0 + 6.5 = 11.5

2. int a=5, b=6;


float c;
c = a + b;
Here, c = 5 + 6
= 11
c = 11.0 (since c is declared as float)

Dr H N National College of Engineering 51


Type conversion in an expression

Dr H N National College of Engineering 52


Example:
— float f = 3.5;
— int i;
— i = f;
The statement i = f results in f to be demoted to type int. The fractional part of “f”
will be lost and i will contain 3 (not 3.5).

Rules:

— When a float value is converted to an int value, the fractional part is truncated.
— When a double value is converted to a float value, rounding of digit is done.
— When a long int is converted into int, the excess higher order bits are dropped.

Dr H N National College of Engineering 53


9.16.2 Typecasting
— Typecasting is also known as forced conversion. Typecasting an arithmetic expression tells
the compiler to represent the value of the expression in a certain way.

— It is done when the value of the higher data type has to be converted into the value of the
lower data type. This is completely under the programmer control not under the compiler
control.

— Example: float salary = 10000.00


int sal;
sal = (int) salary;

— When floated point number are converted to integer, the digits after the decimal are
truncated.

— Therefore data is lost when floating-point representations are converted to integral


representations. So in order to avoid such type of inaccuracies, int type variables must be
typecast to float type.

Dr H N National College of Engineering 54


— As in the previous example, typecasting can be done by placing the destination data type in
parentheses followed by the variable name that has to be converted.

— Example: int a = 500, b = 70;


float res;
res = (float) a/b;

res = (int) 9.5;


9.5 is converted to 9 by truncation and then assigned to res.

res = (int) 12.3 / (int) 4.2;


It is evaluated as 12/4 and the value 3 is assigned to res.

Dr H N National College of Engineering 55


Write a program to convert a floating point number
into the corresponding integer.
#include <stdio.h>
int main()
{
float f_num;
int i_num;
printf(" \n Enter any floating point number \n");
scanf("%f", &f_num);
i_num = (int) f_num;
printf(" \n The integer variant of %f is = %d", f_num, i_num);
return 0;
}
Output: Enter any floating point number
23.45
The integer variant of 23.450001 is = 23

Dr H N National College of Engineering 56


Write a program to convert a integer number into
the corresponding floating point number.
#include <stdio.h>
int main()
{
float f_num;
int i_num;
printf(" \n Enter any integer number \n");
scanf("%d", &i_num);
f_num = (float) i_num;
printf(" \n The floating variant of %d is = %f", i_num, f_num);
return 0;
}
Output: Enter any integer number
12
The floating variant of 12 is = 12.000000

Dr H N National College of Engineering 57


Decision Control and Looping Statements
10.1 Introduction to Decision Control Statements
— The code in C program is executed sequentially from the first line of the
program to its last line.

— Although this is true, but in some cases we want only selected statements to be
executed. Such type of conditional processing extends the usefulness of
programs. It allows the programmers to build programs that determine which
statement of the code should be executed and which should be ignored.

C supports two type of decision control statements:

— 1. conditional type branching


— 2. unconditional type branching

Dr H N National College of Engineering 58


Dr H N National College of Engineering 59
10.2 Conditional Branching Statements
The conditional branch statements helps to jump from one part of the
program to another depending on whether a particular condition is satisfied
or not.

— if-statement
— if-else statement
— is-else-if statement
— switch statement

10.2.1 if-statement
The if statement is the simplest form of decision control statement that is
frequently used in decision-making.

Dr H N National College of Engineering 60


Syntax:

if (test expression)
{
statement 1;

statement n;
}
statement x;

— The if block may include one statement or n statements enclosed within


curly brackets. First, the test expression is evaluated. If the test
expression is true, the statement of if block (statement 1 to n) are
executed otherwise these statements will be skipped and the execution
will jump to statement to x.

Dr H N National College of Engineering 61


Example programs:
#include <stdio.h>
int main()
{
int x = 10;
if( x > 0)
x++;
printf(" \n x = %d", x);
return 0;
}
Output:
x = 11

Dr H N National College of Engineering 62


Write a program to determine whether a person is
eligible to vote or not
#include <stdio.h>
int main()
{
int age;
printf(" \n Enter the age \n");
scanf("%d", &age);
if( age >= 18)
printf(" \n You are eligible to vote");
else
printf(" \n You are not eligible to vote");
return 0;
}
Output: Enter the age
27
You are eligible to vote

Dr H N National College of Engineering 63


10.2.2 if-else Statement
Syntax:
if (test expression)
{
statement block 1;
}
else
{
statement block 2;
}
statement x;
According to the if-else construct, first the test expression is evaluated. if the expression is true,
statement block1 is executed. If the expression is false, statement block 2 is executed and statement
block 1 is ignored. In any case after the statement block 1 or 2 gets executed, the control will pass to
statement x. Therefore statement x is executed in every case.

Dr H N National College of Engineering 64


Dr H N National College of Engineering 65
Write a program to enter any character. If the entered character is in
lower case then convert it into upper case and if it is a lower case
character then convert it into upper case.
#include <stdio.h>
int main() {
char ch;
printf("\n Enter any character: \n");
scanf("%c", &ch);
if(ch>='A' && ch<='Z')
printf(" \n The entered character is in upper case. In lower case it is: %c", (ch+32));
else
printf(" \n The entered character is in lower case. In upper case it is: %c", (ch-32));
return 0;
}
Output: Enter any character:
a
The entered character is in lower case. In upper case it is: A

Dr H N National College of Engineering 66


Write a program to enter a character and then
determine whether it is a vowel or not.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch ==
'I' || ch == 'O' || ch == 'U' )
printf("%c is a vowel.", ch);
else
printf("%c is a consonant.", ch);
return 0;
}
Output: Enter any character: a
a is a vowel.

Dr H N National College of Engineering 67


10.2.3 if-else-if Statement
— C language supports if-else-if statements to test additional conditions
apart from the initial test expression.
— The if-else-if construct works in the same way as a normal if statement.
— If-else-if construct is also known as nested if construct.

Dr H N National College of Engineering 68


Syntax:
if ( test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
else
{
statement block x;
}
statement y;

Dr H N National College of Engineering 69


Write a program to demonstrate the use of nested if
structure
#include <stdio.h>
int main() {
int x, y;
printf(" \n Enter two numbers: \n"); Output:
scanf("%d%d", &x, &y); ¨ Enter two numbers:
if(x == y) ¨ 12
printf(" \n The two numbers are equal"); ¨ 23
else if(x > y) ¨ 12 is smaller than 23
printf(" \n %d is greater then %d", x, y);
else
printf("\n %d is smaller than %d", x, y);
return 0;
}

Dr H N National College of Engineering 70


Write a program to display the examination results.
#include <stdio.h>
int main() {
int marks;
printf(" \n Enter the marks obtained: \n");
scanf("%d", &marks);
if(marks >=75) Output:
printf("\n Distinction \n"); ¨ Enter the marks obtained:
else if( marks >= 60 && marks < 75) ¨ 72
printf(" \n First Division "); ¨ First Division
else if( marks >= 50 && marks < 60)
printf("\n Second Division");
else if( marks >=40 && marks < 50)
printf(" \n Third Division");
else
printf(" \n Fail");
return 0; Dr H N National College of Engineering 71

}
10.2.4 switch case
— A switch case statement is a multi-way decision statement that is a simplified version of an if-
else block that evaluates only one variable.
Syntax:
switch (variable)
{
case value 1: statement block 1;
break;
case value 2: statement block 2;
break;
…………….
case value n: statement block n;
break;
default: statement block D;
break;
}
statement x;

Dr H N National College of Engineering 72


Dr H N National College of Engineering 73
— The power of nested if-else statement lies in the fact that it can evaluate
more then one expression in a single logic structure.

Switch statements are mostly used in two situation:

— When there is only one variable to evaluate in the expression


— When many conditions are being tested for

— When there are many conditions to test, using the if and else-if
constructs becomes a bit complicated and confusing.
— Therefore, switch case statements are often used as an alternative to long
if statement that compare a variable to several integral values.

Dr H N National College of Engineering 74


Write a program to enter a number from 1-7 and display the
corresponding day of the week using switch case statement.
#include <stdio.h>
int main()
{
int day;
printf("\n Enter any number from 1 to 7:");
scanf("%d", &day);

switch(day)
{
case 1: printf(" \n Sunday");
break;
case 2: printf(" \n Monday");
break;
case 3: printf(" \n Tuesday");
break;

Dr H N National College of Engineering 75


case 4: printf(" \n Wednesday");
break;
case 5: printf(" \n Thursday");
break;
case 6: printf(" \n Friday");
break;
case 7: printf(" \n Saturday");
break;
default: printf(" \n Wrong Number");
}
return 0;
}
Output:
— Enter any number from 1 to 7: 4
— Wednesday

Dr H N National College of Engineering 76


10.3 Iterative Statements
— Iterative statements are used to repeat the execution of a list of
statements, depending on the value of an integer expression.

— C language supports three types of iterative statements also known as


looping statements. They are:

— while loop
— do-while loop
— for loop

Dr H N National College of Engineering 77


10.3.1 while loop
— The while loop provides a mechanism to repeat one or more statements while a particular
condition is true.

Syntax:
statement x;
while (condition)
{
statement block;
}
statement y;

¨ In while loop, the condition is tested before any of the statements in the statement block is
executed.
¨ If the condition is true, only then the statement will be executed otherwise if the condition is
false, the control will jump to statement y.

Dr H N National College of Engineering 78


Dr H N National College of Engineering 79
Write a C program to print the first 10 numbers
using a while loop.
#include<stdio.h>
int main()
{
int i=1;
while(i<=10)
{
printf(“ %d”, i);
i = i + 1;
}
return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

Dr H N National College of Engineering 80


Write a C program to calculate the sum of first 10
numbers.
#include<stdio.h>
int main()
{
int i=0, sum = 0;

while (i<=10)
{
sum = sum + i;
i = i +1;
}

printf(“ \n SUM = %d”, sum);


return 0;
}
Output:

SUM = 55

Dr H N National College of Engineering 81


Write a program to print 20 horizontal asterisks (*).
#include<stdio.h>
int main()
{
int i=0;
while (i<=20)
{
printf(“ * ”);
i++;
}
return 0;
}

Output:

*********************

Dr H N National College of Engineering 82


Write a program to calculate the sum of numbers
from m to n.
#include<stdio.h>
int main()
{
int n, m, sum = 0;
printf("\n Enter the value of m:");
scanf("%d", &m);
printf("\n Enter the value of n:"); Output:
scanf("%d", &n);
¨ Enter the value of m: 7
while(m<=n)
{ ¨ Enter the value of n: 11
sum = sum + m; ¨ SUM=45
m = m + 1;
}
printf("\n SUM=%d",sum);
return 0;
}

Dr H N National College of Engineering 83


10.3.2 do-while loop
— The do-while loop is similar to while loop. Only difference is that in a do-while loop, the test
condition is evacuated at the end of the loop. This clearly means that the body of the loop gets
executed at least one time.

— The test condition is enclosed in parenthesis and followed by a semicolon. The statement in the
statement blocks are enclosed within curly brackets. The curly brackets are optional if there is
only one statement in the body of the do-while loop.

Syntax: statement x;
do
{
statement block;
}
while(condition);
statement y;

Dr H N National College of Engineering 84


Dr H N National College of Engineering 85
Output:
#include<stdio.h> 1
int main()
{ 2
int i = 1;
do 3
{
printf(“ \n %d”, i); 4
i = i+1;
} 5
while (i<=10);
return 0; 6
}
7

10
Dr H N National College of Engineering 86
Write a program to calculate the average of first n
numbers.
#include<stdio.h>

int main()
{
int n, i=1, sum=0;
float avg = 0.0;
printf(" \n Enter the Value of n:");
scanf("%d", &n);
do
{
sum = sum + i;
i = i + 1;
}
while(i<=n);

Dr H N National College of Engineering 87


avg = (float) sum/n;
printf(" \n The sum of first %d numbers = %d", n, sum);
printf("\n The average of first %d numbers = %.2f", n, avg);
return 0;
}

Output:
◦ Enter the Value of n:18
◦ The sum of first 18 numbers = 171
◦ The average of first 18 numbers = 9.50

Dr H N National College of Engineering 88


10.3.3 for Loop
— Like the while and do-while loops, the for loop provides a mechanism to repeat a task until
a particular condition is true.

— For loop is usually known as a determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.

Syntax:

for(initialization; condition; increment/decrement)


{
statement block;
}
statement y;

Dr H N National College of Engineering 89


Dr H N National College of Engineering 90
— When a for loop is used, the loop variable is initialized only once. With
every iteration of the loop, the value of the loop variable is updated and
the condition is checked.

— If the condition is true, then the statement block of the loop is executed,
else the statements comprising the statement block of the for loop are
skipped and the control jumps to the immediate statement following the
for loop body.

Dr H N National College of Engineering 91


#include<stdio.h>
int main()
{
int i, n;
printf(" \n Enter the value of n: ");
scanf("%d", &n);
for(i=1;i<=n;i++)
printf("\n %d", i);
return 0;
}

Output:
Enter the value of n: 4
1
2
3
4

Dr H N National College of Engineering 92


#include<stdio.h>
int main()
{
int i;
for(i=0;i<10;i++);
printf("\n %d", i);
return 0;
}
Output:
10
In this code loop initializes i to 0 and increments its value. Since a semicolon is
placed after the loop, it means that loop does not contain any statement. So even if
the condition is true, no statement is executed. The loop continues till i becomes
10 and the moment i=10, the statement following the for loop is executed and the
value of i (10) is printed on the screen.

Dr H N National College of Engineering 93


#include<stdio.h>
int main()
{
int i, sum;
for(i=0, sum=0;i<10;i++);
sum+=i;
printf("%d", sum);
return 0;
}

Output:
10

Dr H N National College of Engineering 94


10.4 Nested Loops
— C allows its users to have nested loops, i.e., loops that can be placed inside other
loops.

— Although this feature will work with any loop such as while, do-while, and for,
it is most commonly used with the for loop, because it is easiest to control.

#include <stdio.h>
int main()
{

int i,j,n;

printf("Input number of rows : ");

scanf("%d",&n);

Dr H N National College of Engineering 95


for (i=0; i<=n;i++)
{ /* print blank spaces */

for(j=1; j<=n-i;j++)

printf(" ");

/* Display number in ascending order upto middle*/

for(j=1;j<=i;j++)
printf(" %d",j);
/* Display number in reverse order after middle */
for(j=i-1;j>=1;j--)
printf(" %d ",j);
printf("\n");
}
}

Dr H N National College of Engineering 96


Output:
Input number of rows : 4

1
121
1232 1
12343 2 1

Dr H N National College of Engineering 97


10.5 Break and Continue Statements
10.5.1 Break statements

— In C, the break statement is used to terminate the execution of the nearest


enclosing loop in which it appears.

— The break statement is widely used with for loop, while loop and do-while
loop. When the compiler encounters a break statement, the control passes to
the statement that follows the loop in which the break statement appears.

Syntax: break;

— In switch statement if the break statement is missing then every case from the
matched case label till the end of the switch, including the default, is executed.
Dr H N National College of Engineering 98
while(….)
{
if(condition)
break;
……..
}
…….
Transfers the control out of the loop while

do
{
….
if(condition)
break;
….
} while(…..);
……
Transfers the control out of the do-while loop

Dr H N National College of Engineering 99


— Like the break statement, the continue statement is used in the body of a loop.

— When the compiler encounters a continue statement then the rest of the
statement in the loop are skipped and the control is unconditionally transferred
to the loop-continuation portion of the nearest enclosing loop.

Syntax: continue;

Example:
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=10;i++)

Dr H N National College of Engineering 100


{
if(i==5)
continue;
printf(“\t %d”, i);
}
return 0;
}

The code given here is meant to print numbers from 1 to 10. But as soon as
i becomes equal to 5, the continue statement is encountered, so rest of the
statements in the for loop are skipped and the control passes to the
expression that increments the value of i.

Output:
1 2 3 4 6 7 8 9 10

Dr H N National College of Engineering 101


The goto statement is used to transfer control to a specified label.
However, the label must reside in the same function and appears only
before one statement in the same function.

Syntax:

Forward jump

goto label
……….
……….
label:
statements

Dr H N National College of Engineering 102


Backward jump

label:
statements
…………
…………
goto label

— The goto statement is often combined with the if statement to cause a


conditional transfer of control.

Dr H N National College of Engineering 103


#include<stdio.h>
int main()
{
int num, sum=0;
read:
printf("\n Enter the number. Enter 999 to end:");
scanf("%d", &num);
if(num!=999)
{
if(num<0)
goto read;
sum+=num;
goto read;
}
printf(" \n Sum of the numbers entered by the user is = %d", sum);
return 0;
}

Dr H N National College of Engineering 104


Output:

— Enter the number. Enter 999 to end:10

— Enter the number. Enter 999 to end:20

— Enter the number. Enter 999 to end:1

— Enter the number. Enter 999 to end:999

— Sum of the numbers entered by the user is = 31

Dr H N National College of Engineering 105


Dr H N National College of Engineering 106

You might also like