Module 2
Module 2
6. goto statement.
Module - 2 1
OPERATORS IN C
3
2. RELATIONAL OPERATORS
• Also known as a comparison operator, it is an operator that compares two
values.
• Expressions that contain relational operators are called relational
expressions.
• Relational operators return true or false value, depending on whether the
conditional relationship between the two operands holds or not.
4
// Program relational Operators
#include<stdio.h>
int main()
{
int x = 12, y = 13;
printf("x = %d\n", x);
printf("y = %d\n\n", y); Output
// Is x is greater than y? x = 12
printf("x > y : %d\n", x > y);
// Is x is greater than or equal to y?
y = 13
printf("x >= y : %d\n", x >= y); x>y:0
// Is x is smaller than y? x >= y : 0
printf("x < y : %d\n", x < y); x<y:1
// Is x is smaller than or equal to y? x <= y : 1
printf("x <= y : %d\n", x <= y);
// Is x is equal to y?
x == y : 0
printf("x == y : %d\n", x == y); x != y : 1
// Is x is not equal to y?
printf("x != y : %d\n", x != y);
// Signal to operating system everything works fine
return 0; 5
}
3. EQUALITY OPERATORS
• C language supports two kinds of equality operators to compare their
operands for strict equality or inequality.
• They are equal to (==) and not equal to (!=) operator.
• The equality operators have lower precedence than the relational
operators.
OPERATOR MEANING
== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0
OTHERWISE
!= RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME
VALUE, 0 OTHERWISE
6
4. LOGICAL OPERATORS
• C language supports three logical operators. They are- Logical AND (&&),
Logical OR (||) and Logical NOT (!).
• As in case of arithmetic expressions, the logical expressions are evaluated from left
to right.
Logical AND (&&): If both operands Logical OR (||) :The condition
are non zero then the condition becomes true if any one of them is
becomes true. Otherwise, the result has non-zero. Otherwise, it returns false
a value of 0. The return type of the i.e, 0 as the value. Below is the truth
result is int. truth table for the logical table for the logical OR operator.
AND operator. Syntax: (condition_1 || condition_2)
Syntax: (condition_1 && condition_2)
A B A || B
A B A &&B
0 0 0
0 0 0
0 1 1
0 1 0
1 0 1
1 0 0
1 1 1
1 1 1
Module - 2 7
Logical NOT (!):
If the condition is true then the logical NOT operator will make it
false and vice-versa.
Below is the truth table for the logical NOT operator.
Syntax: !(condition_1 && condition_2)
Module - 2 8
Evaluate
(x>9) && (y+1)
here if the first operand is false the entire expression will not be
evaluated
Try for x=8, y=2
and x=10, y=2
OR
(x>9) || (y+1)
Try for x=8, y=2
and x=10, y=2
here if the first operand is false the entire expression will not be
evaluated thus value of y will never be incremented
Module - 2 9
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int x=10,y=2,t; int x=8,y=2,t;
t=(x>9) && (y+2); t=(x>9) && (y+2);
printf(" b, y is:\n %d %d ", t,y); printf(" b, y is:\n %d %d ", t,y);
return 0; return 0;
} }
b, y is: b, y is:
12 02
Module - 2 10
// Program Logical Operators
#include <stdio.h>
// Driver code
int main()
{
int x = 7, y = 3;
// Logical operator
sprintf("Following are the logical operators in C \n");
printf("The value of ((x==y) && (x<y)) is: %d \n", ((x == y) && (x < y)));
printf("The value of ((x==y) || (x<y)) is: %d \n",((x == y) || (x < y)));
printf("The value of (!(x==y)) is: %d ",(!(x == y)));
return 0;
}
Module - 2 11
5. UNARY OPERATORS
• Unary operators act on single operands.
• C language supports three unary operators.
• They are unary minus, increment and decrement operators.
• When an operand is preceded by a minus sign, the unary operator
negates its value.
• The increment operator is a unary operator that increases the value of its
operand by 1.
Similarly, the decrement operator decreases the value of its operand by 1.
For example,
int x = 10, y;
y = x++; whereas, y = ++x;
is equivalent to writing is equivalent to writing
y = x; x = x + 1;
x = x + 1; y = x;
Module - 2 12
// C Program on increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Module - 2 13
int i = 42;
i++; /* increment contents of i, same as i = i + 1; i is now 43 */
i--; /* decrement contents of i, same as i = i – 1; i is now 42 */
++i; /* increment contents of i, same as i = i + 1; i is now 43 */
--i; /* decrement contents of i, same as i = i – 1; */ /* i is now 42 */
#include <stdio.h>
int main()
{
int i = 42;
printf(" i++ = %d \n", i++); Output
printf("i-- = %d \n", i--); i++ = 42
printf("++i = %d \n", ++i); i-- = 43
printf("--i = %d \n", --i); ++i = 43
return 0;
} Module - 2
--i = 42 14
• The pre and post- (++ and --)
operators differ in the value used
for the operand n when it is
embedded inside expressions.
• If it is a ‘pre’ operator, the
value of the operand is
incremented (or decremented)
before it is fetched for
computation.
• The altered value is used for
computation of the
Module - 2 15
expression in which it occurs.
• The pre and post- (++ and --) operators differ in the value used for the
operand n when it is embedded inside expressions.
• If it is a ‘pre’ operator, the value of the operand is incremented (or
decremented) before it is fetched for computation.
• The altered value is used for computation of the expression in which
it occurs.
Module - 2 16
6. CONDITIONAL OPERATOR
The conditional operator operator (?:) is just like an if .. else statement that can be
written within expressions.
The syntax of the conditional operator is
exp1 ? exp2 : exp3
Here, 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. For example,
large = ( a > b) ? a : b
Conditional operators make the program code more compact, more readable, and safer
to use as it is easier both to check and guarantee that the arguments that are used for
evaluation.
Conditional operator is also known as ternary operator as it is neither a unary nor
a binary operator; it takes three operands.
Module - 2 17
The syntax of the conditional operator is
exp1 ? exp2 : exp3
if(expression1)
{
expression2;
}
else
{
expression3;
}
Module - 2 18
Find the number is positive or negative using the conditional operator
#include<stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
(num>=0)?printf("Positive."):printf("Negative");
return 0;
}
Enter a number: 8
Positive.
Enter a number: -10
Negative
Module - 2 19
Find the given number is odd or even using the conditional operator in C
#include<stdio.h>
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
(num%2==0)? printf("Even"): printf("Odd");
return 0;
}
Enter a number: 9
Odd
Enter a number: 8
Even
Module - 2 20
Write a C program to find the maximum of three numbers using
conditional operators.
#include<stdio.h>
int main()
{
float a, b, c, max;
printf("Enter three numbers: ");
scanf("%f %f %f",&a, &b, &c);
max = (a>b && a>c)? a: (b>a && b>c)? b:c;
printf("Maximum number = %.2f",max);
return 0;
}
Enter three numbers: 10 30 12
Maximum number = 30.00
To try: Write a C program to find the minimum of three numbers
using conditional operators. Module - 2 21
7. BITWISE OPERATORS
• Bitwise operators perform operations at bit level. These operators include:
Module - 2 22
Truth table of bitwise XOR
The bitwise XOR operator compares each bit of its first operand with the
corresponding bit of its second operand.
If one of the bits is 1, the corresponding bit in the result is 1 or 0.
Module - 2 23
/ C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;
// The result is 00000001
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);
// The result is 00001101 a = 5, b = 9
printf("a|b = %d\n", a | b);
a&b=1
// The result is 00001100
printf("a^b = %d\n", a ^ b); a | b = 13
// The result is 11111010 a ^ b = 12
printf("~a = %d\n", a = ~a); ~a = -6
// The result is 00010010 b << 1 = 18
printf("b<<1 = %d\n", b << 1);
b >> 1 = 4
// The result is 00000100
printf("b>>1 = %d\n", b >> 1);
return 0;
Module - 2 24
}
8. BITWISE SHIFT OPERATORS
In bitwise shift operations, the digits are moved, or shifted, to the left or right.
The CPU registers have a fixed number of available bits for storing numerals,
so when we perform shift operations:
some bits will be "shifted out" of the register at one end, while the same
number of bits are "shifted in" from the other end.
• In a left arithmetic shift, zeros are shifted in on the right. For example;
• unsigned int x = 11000101;
• Then x << 2 = 00010100
• If a right arithmetic shift is performed on an unsigned integer then zeros
are shifted on the left.
• unsigned int x = 11000101;
• Then x >> 2 = 00110001
Module - 2 25
Module - 2 26
9. ASSIGNMENT OPERATORS
It is responsible for assigning values to the variables. While the equal sign (=) is the
fundamental assignment operator, C also supports other assignment operators that
provide shorthand ways to represent common variable assignments. They are shown in
the table.
OPERATOR SYNTAX EQUIVALENT TO
/= variable /= expression variable = variable / expression
\= variable \= expression variable = variable \ expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
Module - 2 27
• Abbreviated (compound) assignment expressions
It is frequently necessary in computer programs to make
assignments
a –= b; Compound Subtract : First Subtract and assign to a (= a – b)
a *=b; Compound Multiply: Multiply and assign: is equivalent to a = a * b;
a /= b; Compound Divide: Divide and assign: is equivalent to a = a / b;
a %= b Compound modulus: First, Evaluate the a%b then assign the result to a
Module - 2 28
// Assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c); Output
c -= a; // c is 5 c=5
printf("c = %d\n", c); c = 10
c *= a; // c is 25 c=5
printf("c = %d\n", c); c = 25
c /= a; // c is 5
c=5
printf("c = %d\n", c);
c %= a; // c = 0
c=0
printf("c = %d\n", c);
return 0;
} Module - 2 29
#include <stdio.h>
int main()
{
int n; n=0;
n -= 5;
printf("\nn is: %d",n);
n *=5;
printf("\nn is: %d",n); Output
n /= 5; n is: -5
printf("\nn is: %d",n); n is: -25
n %= 5; n is: -5
printf("\nn is: %d",n); n is: 0
return 0;
}
Module - 2 30
10. COMMA OPERATOR
• The comma operator in C takes two operands.
• It works by evaluating the first and discarding its value, and then evaluates the
second and returns the value as the result of the expression.
• Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
• Among all the operators, the comma operator has the lowest precedence. For
example,
Module - 2 31
#include <stdio.h>
int main()
{
int x, y ;
x = 1, 2 ; // Here x=1 and 2 is discarded
y = (3,4) ; // Here y=4 and 3 is discarded
printf( "%d %d\n", x, y ) ;
}
Output
14
Module - 2 32
#include<stdio.h>
int main()
{
int a=1, b=2, c ; // here comma is Separator
c = a , b ; // here comma is Operator
printf(“a = %d b = %d c = %d”,a,b,c);
return 0;
}
output :
a=1b=2c=1
In Above program statement c = a , b
; contains comma operator, Initially a
value is assigned to c. so c value
become 1 and then b is discarded.
Module - 2 33
#include<stdio.h> output
int main() a=1b=2c=2
{ c contains 2 that means
int a=1, b=2, c ; // here comma is Separator value of b. because of the
c = ( a , b ); // here comma is Operator parenthesis around a and
printf(“a = %d b = %d c = %d”,a,b,c); b.
return 0;
}
• For example,
• If we have,
int a = 10;
unsigned int result;
result = sizeof(a);
then result = 2, Module - 2 35
Operator precedence chart
Module - 2 36
Module - 2 37
Evaluate the expressions
X=3*4+5*6 X=3*(4+5)*6
= 12+5*6 = 3*9*6
= 12+30 =162
= 42
X=3*4%5/2 X=3*4%(5/2)
=12%5/2 =3*4%2
=2/2 =3*2
=1 =6
Module - 2 38
int a=0; b=1, c=-1
float x=2.5, y=0.0
Evaluate
(1) a && b =0
(2) a<b && c<b =1
(3) b+c||!a
= (b+c)|| (!a)
=0|| 1 =1
(4)x*5 && 5|| (b/c)
=((x*5) && 5) || (b/c) =1
Module - 2 39
//VTU question paper problem 2018CPS
#include <stdio.h>
10!=10 ||5<4 && 8
int main()
{ #include <stdio.h>
int main()
int x, a=9,b=12,c=3; {
x=a-b/3+c*2-1; printf("Answer is: %d",
10!=10 ||5<4 && 8);
printf("x is: %d", x); return 0;
return 0; }
} Answer is 0
x is: 10
Module - 2 40
2)Evaluate: int a=5 #include <stdio.h>
a!=5 || a==6 || a>=56 || a>4 int main()
{
#include <stdio.h>
int incr, a=5,b=3;
int main()
{ incr= (a> b) || (b++);
int a=5; printf("incr, b is:\n %d %d ",
printf("x is: %d", a!=5 || a==6 || a>=56 || a>4); incr, b);
return 0; return 0;
} }
x is: 1
incr, b is:
13
Module - 2 41
#include <stdio.h>
int main()
{
int incr,a=5,b=3;
incr= (a> b) && (b++);
printf("incr, b is:\n %d %d ", incr, b);
return 0;
}
incr, b is:
14
Module - 2 42
TYPE CONVERSION AND TYPE CASTING
• Type conversion and type casting of variables refers to changing a variable of one
data type into another.
• While type conversion is done implicitly, casting has to be done explicitly by the
programmer.
• Type conversion is done when the expression has variables of different data types.
So to evaluate the expression, the data type is promoted from lower to higher level
where the hierarchy of data types can be given as: double, float, long, int, short and
char.
• For example, type conversion is automatically done when we assign an integer
value to a floating point variable. For ex,
#include <stdio.h>
int main()
{ float x;
int y = 3;
x = y;
printf("x is %.4f",x);
return 0;
} Module - 2 43
Output is x is 3.0000
• Type casting is also known as forced conversion.
int sal;
Module - 2 44
// C program to illustrate the use of //example of adding a character decoded
// typecasting //in ASCII with an integer
#include <stdio.h> #include <stdio.h>
main()
// Driver Code {
int main() int number = 1;
{ char character = 'k';
// Given a & b /*ASCII value is 107 */
int a = 15, b = 2; int sum;
float div; sum = number + character;
// Division of a and b printf("Value of sum : %d\n", sum );
div = float(a / b); }
printf("The result is %f\n", div);
return 0;
} Value of sum : 108
Module - 2 45
Decision control statements
(PROGRAMMING CONSTRUCTS)
Module - 2 46
DECISION CONTROL STATEMENTS
{
statement 1; TRUE
statement n;
}
statement x; Statement x
/* Program to demonstrate
the use of if-statement
*/
#include<stdio.h>
int main()
{
int x=10;
if (x>0)
x++;
printf("\n x = %d", x);
}
X= 11
Module - 2 49
// PROGRAM TO FIND WHETHER A NUMBER IS EVEN OR ODD
#include<stdio.h>
main()
{int a;
printf("\n Enter the value of a : ");
scanf("%d", &a);
if(a%2==0)
printf("\n %d is even", a);
else
printf("\n %d is odd", a);
}
Module - 2 50
IF -ELSE
STATEMENT
● In the if-else construct, first the test expression is evaluated. If the expression is true, statement
block 1 is executed and statement block 2 is skipped. Otherwise, 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.
SYNTAX OF IF STATEMENT
if (test expression) FALSE
{
Test
statement_block 1; TRUE
Expression
}
else Statement Block 1 Statement Block 2
{
statement_block 2;
}
statement x; Statement x
// 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;
}
Module - 2 52
// PROGRAM TO CHECK IF A PERSON IS ELIGIBLE FOR VOTING
#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
printf("You are eligible for voting");
}
else
{
printf("You are not eligible for voting");
}
return 0;
}
Module - 2 53
SYNTAX OF IF-ELSE IF-ELSE-IF STATEMENT
STATEMENT
C language supports if else if statements to
if ( test expression 1) test additional conditions apart from the initial
{ test expression. The if-else-if construct works
statement block 1;
in the same way as a normal if statement.
}
else if ( test
expression 2)
{
statement block 2; TRUE FALSE
Test
} Expression
....................... 1
.... FALSE
Statement Block 1
else if (test Test
Expression
TRUE
expression N) 2
{ Statement Block 2 Statement Block X
statement block N;
}
Statement Y
else
{
Statement Block X;
}
Statement Y;
// PROGRAM TO CLASSIFY A NUMBER AS POSITIVE, NEGATIVE OR ZERO
#include<stdio.h>
main()
{
int num;
printf("\n Enter any number : ");
scanf("%d", &num);
if(num==0)
printf("\n The value is equal to zero");
else if(num>0)
printf("\n The number is positive"); Enter any number : 0
else The value is equal to zero
printf("\n The number is negative");
Enter any number : -100
} The number is negative
Selection
Simple Multiple
Multi-
One Way Two Way Nested way
Module - 2 59
SELECTION
if(condition)
If(condition) SYNTAX Statement 1;
SYNTAX Statement; else
Statement 2;
FLOWCHART
FLOWCHART
condition
condition
Statement;
Statement 1; Statement 2;
Module - 2 60
// TO FIND LARGER NUMBER
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
Module - 2 61
//TO FIND LARGEST AMONG THREE NUMBERS
#include<stdio.h>
void main()
{ int a,b,c;
printf("Enter the values of a,b,c\n");
scanf("%d %d %d", &a, &b, &c);
if(a>b)
{
if(a>c)
printf("A=%d is largest",a);
else
printf("C=%d is largest",c);
}
else
{
if(b>c)
printf("B=%d is largest",b);
else
printf("C=%d is largest",c);
}
Module - 2 62
}
//PROGRAM TO FIND NATURE OF NUMBER- ZERO, POSITIVE OR NEGATIVE
#include <stdio.h>
void main()
{ int a;
printf(“Enter a number : “);
scanf(“%d”,&a);
if(a > 0)
{
printf(“\nThe number is positive “);
}
else if(a<0)
{ printf(“\n The number is negative”);
}
else
{
printf(“Number is zero”);
}
}
Module - 2 63
Pascal triangle What is Pascal Triangle?
Pascal Triangle starts with row n = 0 where
there is only one entry 1.
And it grows row wise toward right by adding
previous and next item of the previous row.
For example:
•The initial number in the first row is 1 (the sum
of 0 and 1),
•In second row, addition of 0+1 = 1 and 1+0 =
1. So 1 1 in second row.
•When we move on 3rd row then 0+1 = 1,
1+1=2 and 1+0 = 1. So elements of triangle in
3rd row is 1 2 1.
Module - 2 64
#include <stdio.h>
void main()
{
int nbr, space, i, j, p=1;
printf("Enter the number of lines: ");
scanf("%d",&nbr);
for(i = 0; i < nbr; i++)
{
for(space = 1; space <= nbr-i; space++)
printf(" "); //add space
for(j = 0; j <= i; j++)
{
if ( i==0 || j==0 )
p = 1;
else
p = p*(i-j+1)/j;
printf("% 4d",p);
}
printf("\n");
}
Module - 2 65
}
SELECTION
FLOWCHART Switch Statement
SYNTAX
switch(expression)
Expression==Constant 1 StatementList 1
{
case constant1:StatementList1;
break;
case constant2:StatementList2;
Expression==Constant 2 StatementList 2
break;
case constant3:StatementList3;
break;
…………………………
Expression==Constant 2 StatementList 3
default :StatementList N;
Default StatementList N
Module - 2 66
SWITCH CASE
● A switch case statement is a multi-way decision statement.
● Each value is called a case, and the variable being switched on
is checked for each switch case.
● Switch statements are used: When there is only one variable to
evaluate in the expression When many conditions are being
tested for Switch case statement advantages include:
● Easy to debug,
● Read,
● Understand and
● Maintain
● Execute faster than its equivalent if-else construct
Syntax of switch
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of
case statements */
default : /* Optional */
statement(s);
}
Module - 2 68
#include <stdio.h> case 'C' :
int main () printf("Good\n" );
{ break;
char grade;
printf("Enter your grade %c "); case 'D' :
scanf("%c", &grade); printf("You passed\n" );
switch(grade) break;
{
case 'A' : case 'F' :
printf("Excellent!\n" ); printf("Better try again\n" );
break; break;
default :
case 'B' : printf("Invalid grade\n" );
printf("Well done\n" ); }
break; return 0;
}
Module - 2 69
/ /PROGRAM TO PRINT THE DAY OF THE WEEK
#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”);
Module - 2 70
break;
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”);
}
}
Module - 2 71
ITERATIVE STATEMENTS
Iterative statements are used to repeat the execution of a list
of statements, depending on the value of an integer
expression.
1. While loop
2. Do-while loop
3. For loop
while (condition)
{
Statement x
statement_block;
Update the
condition
} TRUE
statement x; expression
Conditio
n
Statement Block FALSE
Statement y
WHILE LOOP
• The while loop is used to repeat one or more statements
while a particular condition is true.
• In the 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 statements will be
executed otherwise the control will jump to the immediate
statement outside the while loop block.
• We must constantly update the condition of the while loop.
Module - 2 73
while loop:
A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
Module - 2 74
Programs using While Construct
Version 1 Version 2 Version 3
#include <stdio.h> #include <stdio.h> #include <stdio.h>
int main() int main() int main()
{ { {
int times = 0; int times = 1; int times = 50;
while (times < 50) while (times <= 50) while (times > 50)
{ { {
printf( “*”); printf( “*”); printf( “*”);
times++; times++; times--;
} } }
return 0; return 0; return 0;
} } }
Statement x
Statement x; do
Statement Block
{
Update the condition expression
statement_block;
TRUE
} while (condition);
Condition
FALSE
statement y;
Statement y
do-while loop:
do while loop is similar to while loop with the only difference that it
checks for the condition after executing the statements, and therefore is
an example of Exit Control Loop.
Module - 2 77
Program to demonstrate the use of while loop and do while loop
#include<stdio.h> #include<stdio.h>
int main() int main()
Output
{int i = 0; { 0
while(i<=10) int i = 0; 1
{ printf(“\n %d”, i); do 2
i = i + 1; { 3
} printf(“\n %d”, i); 4
5
} i = i + 1; 6
} 7
while(i<=10); 8
} 9
10
Differentiate between while and do while loop. Explain the syntax with an example
while do-while
Statement(s) is executed atleast
Condition is checked first then
once, thereafter condition is
statement(s) is executed.
checked.
It might occur statement(s) is
At least once the statement(s) is
executed zero times, If condition is
executed.
false.
No semicolon at the end of while. Semicolon at the end of while.
while(condition) while(condition);
If there is a single statement,
Brackets are always required.
brackets are not required.
Variable in condition is initialized variable may be initialized before or
before the execution of loop. within the loop.
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition)
{ do- {2 statement(s);
Module } 79
statement(s); while(condition);
#include <stdio.h> #include <stdio.h>
int main()
int main() {
{ int i = 5;
int i = 5; while (i < 10)
do { {
printf(“Hi\n"); printf(“%d Hi\n" , i);
i++; i++;
} while (i < 10); }
return 0; return 0; O/p
} } 5 Hi
6 Hi
7 Hi
8 Hi
9 Hi
Module - 2 80
Write a program to check given integer is palindrome or not (Jan. 2020, VTU)
Module - 2 82
//C Program to check whether a number is {
prime or not if(n % i == 0)
#include <stdio.h> count++;
int main() }
{ if(count == 0) //Check it is Prime or not
int n; //Declare the number {
printf("Enter the number: "); printf("%d is a prime number.", n);
scanf("%d",&n); //Initialize the number }
if(n == 1) else
{ {
printf("1 is neither prime nor composite."); printf("%d is not a prime number.", n);
return 0; }
} return 0;
int count = 0; //Declare a count variable }
for(int i = 2; i < n; i++) //Check for factors
Version-1
#include <stdio.h>
int main()
{
int c, s, n;
printf(“\n Enter the No. of terms ”);
scanf(“%d”, &n);
for(c=1, s=0; c<=n; c++)
s+=c; Enter the No. of terms 5
Sum is 15
printf(“\n Sum is %d ”, s);
return 0; Enter the No. of terms 10
Sum is 55
}
Module - 2 86
3. For Construct
Version-2 Version-3
Program to find sum of digits #include <stdio.h>
#include <stdio.h> int main()
int main() {
{ int n, s=0, r;
int n, s=0, r; printf(“Enter the Number”);
printf(“\n Enter the Number”); scanf(“%d”, &n);
scanf(“%d”, &n); while(n>0)
for (n>0; n/=10) {
{ r=n%10;
r=n%10; s=s+r; n=n/10;
s=s+r; }
} printf(“\nSum of digits%d”,s);
printf(“\n Sum of digits %d”, s); return 0;
return 0; }
}
Module - 2 87
A program that computes factorial of a number
int main()
{
int n, c; long int f=1;
printf(“\n Enter the number: ”);
scanf(“%d”,&n);
for(c=1;c<=n;++c)
f*=c; //Compound multiplication i.e., f = f * c
printf(“\n Factorial is %ld”,f);
return 0;
Enter the number: 5
} Factorial is 120
Module - 2 88
BREAK STATEMENT
• The break statement is used to terminate the execution of the
nearest enclosing loop in which it appears.
• When compiler encounters a break statement, the control passes
to the statement that follows the loop in which the break
statement appears.
• Its syntax is quite simple, just type keyword break followed with a
semi-colon.
break;
● In switch statement if the break statement is missing then every
case from the matched case label to the end of the switch,
{
including the default, is executed.
// SWITCH USING CHARACTER CONSTANT
#include <stdio.h>
int main()
{
char ch;
printf("Enter your choice A/B?");
scanf("%c",&ch);
switch(ch)
{
case 'A': printf("You entered an A");
break;
case 'B': printf("You entered a B");
break;
default: printf("Illegal entry");
break;
}
return 0;
}
Module - 2 90
// SWITCH WITHOUT BREAK
#include <stdio.h>
int main() For i=2
{
int i=2; switch (i)
{
case 1: printf("Case1 ");
case 2: printf("Case2 "); Try changing the value of i in program
case 3: printf("Case3 "); (1) i=3
case 4: printf("Case4 "); (2) i=4
default: printf("Default ");
}
return 0;
}
Module - 2 91
CONTINUE STATEMENT
• The continue statement can only appear in the body of a loop.
• When the compiler encounters a continue statement then the rest
of the statements in the loop are skipped and the control is
unconditionally transferred to the loop-continuation portion of the
nearest enclosing loop.
• Its syntax is quite simple, just type keyword continue followed
with a semi-colon.
continue;
If placed within a for loop, the continue statement causes a branch to
the code that updates the loop variable. For example,
int i;
for(i=0; i<= 10; i++)
if (i==5)
continue.
printf(“\t %d”, i);
Module - 2 92
continue statement
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i)
{
printf("Enter a n%d: ", i);
scanf("%lf", &number);
if (number < 0.0)
{ continue;
}
sum += number; // compound sum sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
Module - 2 93
GOTO STATEMENT
• The goto statement is used to transfer control to a specified label.
• Here label is an identifier that specifies the place where the branch is to be
made. Label can be any valid variable name that is followed by a colon (:).
• Note that label can be placed anywhere in the program either before or
after the goto statement.
• Whenever the goto statement is encountered the control is immediately
transferred to the statements following the label.
• Goto statement breaks the normal sequential execution of the program.
• If the label is placed after the goto statement then it is called a forward
jump and in case it is located before the goto statement, it is said to be a
backward jump.
#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; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf("\n Sum of the numbers entered by the user is = %d", sum);
return 0;
}
Module - 2 95
continue statement
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result
#include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
for (i = 1; i <= 10; ++i)
{ printf("Enter a n%d: ", i);
scanf("%lf", &number);
if (number < 0.0)
{ continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf", sum);
return 0;
}
Module - 2 96
1) Simulation of a Simple Calculator case '*': result=a*b;
#include<stdio.h> printf("result is %f\n",result);
void main() break;
{ case '/': if(b!=0)
float a,b,result; {
char ch; result=a/b;
printf("enter an operator\n"); printf("result is %f\n",result);
scanf("%c",&ch); }
printf("enter two integer values\n"); else
scanf("%f %f", &a, &b); {
switch(ch) printf("division by zero not
{ possible\n");
case '+': result= a+b; }
printf("result is %f\n",result); break;
break; case '%': result=(int)a % (int)b; // mod
case '-': result=a-b; division allowed only for integer operands
printf("result is %f\n",result); printf("result is %f\n", result);
break; break;
default: printf("not a valid operator\n");
}
Module - 2 } 97
Write a C program for Simulation of a Simple Calculator (if ..else if…)
#include <stdio.h>
int main()
{
char Operator;
float num1, num2, result = 0;
printf("\n Please Enter an Operator (+, -, *, /) : ");
scanf("%c", &Operator);
printf("\n Please Enter the Values for two Operands: num1 and num2 : ");
scanf("%f%f", &num1, &num2);
if(Operator == '+')
{
printf("\n The result of %.2f + %.2f = %.2f", num1, num2, num1 + num2);
}
else if(Operator == '-')
{
printf("\n The result of %.2f - %.2f = %.2f", num1, num2, num1 - num2);
}
else if(Operator == '*')
Module - 2 98
{
printf("\n The result of %.2f * %.2f = %.2f", num1, num2, num1 * num2);
}
else if(Operator == '/')
{
printf("\n The result of %.2f / %.2f = %.2f", num1, num2, num1 / num2);
}
else
{
printf("\n You have entered an Invalid Operator ");
}
return 0;
}
Module - 2 99
Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,disc,root1,root2, real,img;
printf("enter the values of a,b and c\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
printf("it is not a quadratic equation\n");
return 0;
}
disc = b*b-4*a*c;
Module - 2 100
if(disc>0)
{
printf("\n roots are real and distinct\n");
root1= (-b+sqrt(disc))/(2*a);
root2= (-b-sqrt(disc))/(2*a);
printf("\n root1= %f\n root2= %f\n",root1,root2);
}
else if(disc==0)
{
printf("roots are equal\n");
root1=root2= -b/(2*a);
printf("root1 = root2= %f\n",root1);
}
else
Module - 2 101
{
printf("roots are real and imaginary\n");
real= -b/(2*a);
img= sqrt(fabs(disc))/(2*a);
printf("Root1= %f+i%f\n Root2= %f-i%f\n", real, img, real, img);
}
return 0;
}
Module - 2 102
An electricity board charges
the following rates for the
use of electricity: for the
first 200 units 80 paise per
unit: for the next 100 units
90 paise per unit: beyond
300 units Rs 1 per unit. All
users are charged a
minimum of Rs. 100 as
meter charge. If the total
amount is more than Rs
400, then an additional
surcharge of 15% of total
amount is charged. Write a
program to read the name of
the user, number of units
consumed and print out the Module - 2 103
charges.
#include<stdio.h>
void main()
{
char name[20];
float unit, metercharge=100.0, amt;
printf("Enter the name of the customer\n");
scanf("%s", name);
printf("Enter the number of units consumed\n");
scanf("%f", &unit);
if (unit<=200)
amt= metercharge+(unit*0.8);
else if(unit<=300)
amt= metercharge+ (200*0.8)+ ((unit-200)*0.9);
else
amt=metercharge+ (200*0.8)+ (100*0.9)+((unit-300)*1.0);
Module - 2 104
if(amt>400)
amt= amt+ (amt*0.15);
printf("customer name is:%s\n",name);
printf("No. of units consumed is:%f\n",unit);
printf("Bill amount is Rs %f\n",amt);
}
Module - 2 105
#include <stdio.h> Electricity bill using Ternary operator
int main()
{
char name[20];
float unit, mt=100.0, amt;
printf("Enter the name of the customer\n");
scanf("%s", name);
printf("Enter the number of units consumed\n");
scanf("%f", &unit);
amt= (unit <= 200 ? mt+unit*0.8 :(unit>200 && unit<300 ?
mt+(200*0.8)+(unit-200)*0.9:
mt+(200*0.8)+(100*0.9)+(unit-300)*1.0));
if(amt>400) Enter the name of the customer
amt= amt+ (amt*0.15); shivani
printf("customer name is:%s\n",name); Enter the number of units consumed
printf("No. of units consumed is:%0.1f\n",unit); 300
printf("Bill amount is Rs %0.2f\n",amt); customer name is:shivani
return 0; No. of units consumed is:300.0
} Bill amount is Rs 350.00
Module - 2 106
An electric power distribution company charges its domestic
consumers as follows:
Consumption units Rates of Charge
0-200 Rs.0.50 per unit
201-400 Rs.100 plus Rs.0.65 per unit excess of 200
401-600 Rs.230 plus Rs.0.80 per unit excess of 400
601 and above Rs.390 plus Rs1.00 per unit excess of 600
Module - 2 107
Write a C program to get the triangle of numbers as result: (VTU 2019 July)
1
12 #include <stdio.h>
123 int main()
1234 void main()
{
int n, i;
for(i=1 ;i<=4; i++)
{
for(n=1; n<=i; n++)
{
printf("%d",n);
}
printf("\n");
}
return 0;
}
Module - 2 108
// C program to print a triangle
#include <stdio.h>
// Driver code
int main() *
{ **
int n = 6; ***
****
// ith row has i elements *****
for (int i = 1; i <= n; i++) ******
{
for (int j = 1; j <= i; j++)
{
printf("*");
}
printf("\n");
}
return 0;
Module - 2 109
}
Write program to print Floyd’s triangle
(It is a triangle with first natural numbers)
#include <stdio.h>
Enter the number of rows: 5
int main() {
1
int rows, i, j, number = 1;
23
printf("Enter the number of rows: ");
456
scanf("%d", &rows);
7 8 9 10
for (i = 1; i <= rows; i++) {
11 12 13 14 15
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
Module - 2 110
Write a C program to compute all the roots of a quadratic equation
and print them with appropriate messages. (VTU 2020 Aug./Sept.)
Module - 2 111
#include<stdio.h> else if(disc==0)
#include<math.h> {
int main() printf("roots are equal\n");
{ root1=root2= -b/(2*a);
float a,b,c,disc,root1,root2, real,img; printf("root1 = root2= %f\n",root1);
printf("enter the values of a,b and c\n"); }
scanf("%f%f%f",&a,&b,&c); else
if(a==0) {
{ printf("roots are real and imaginary\n");
printf("it is not a quadratic equation\n"); real= -b/(2*a);
return 0; img= sqrt(fabs(disc))/(2*a);
} printf("Root1= %f+i%f\n Root2=
disc = b*b-4*a*c; %f-i%f\n",real,img,real,img);
if(disc>0) }
{ return 0;
printf("\n roots are real and distinct\n"); }
root1= (-b+sqrt(disc))/(2*a);
root2= (-b-sqrt(disc))/(2*a);
printf("\n root1= %f\n root2= %f\n",root1,root2);
}
Module - 2 112
a=1,b= -5, c=3 a =0,b=2,c= 8 a =1,b=6,c= 9
roots are real and it is not a roots are equal
distinct quadratic root1 = root2=
root1= 4.302776 equation -3.000000
root2= 0.697224
a=1,b= 4, c=7 a=0,b=0, c=0 a = 2,b= -7,c=8
roots are real and ? ?
imaginary
Root1=
-2.000000+i1.732051
Root2=
-2.000000-i1.732051
Module - 2 113