C Programming 2 | PDF | Control Flow | Computing
0% found this document useful (0 votes)
27 views30 pages

C Programming 2

The document discusses different types of decision control statements in C programming language including if, if-else, if-else-if ladder, and nested if statements. It provides examples and syntax for each statement and explains how they are used to control program flow based on conditions being true or false.

Uploaded by

Deep Samanta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views30 pages

C Programming 2

The document discusses different types of decision control statements in C programming language including if, if-else, if-else-if ladder, and nested if statements. It provides examples and syntax for each statement and explains how they are used to control program flow based on conditions being true or false.

Uploaded by

Deep Samanta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 30

DECISION CONTROL

&
LOOP CONTROL
&
PROGRAMS

Dr. Prasenjit Choudhury


&
Rajib kumar Chatterjee
Dept. of Computer Science and Engineering
National Institute of Technology, Durgapur
West Bengal, India
DECISION CONTROL STATEMENTS
• Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of
statements until certain specified conditions are met.
• Decision making statement checks the given condition and then executes the sub block.
• The decision statement decides which statement to execute after the success or failure of a given condition.
• The conditional statements use relational operators.
• Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the
program, along with a statement or statements to be executed.
• Using decision control statements we can control the flow of program in such a way so that it executes certain statements
based on the outcome of a condition (i.e. true or false).
• C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed
as false value.
• C language handles decision-making by supporting the following statements,
•if statement
•switch statement
•conditional operator statement (? : operator)
•goto statement
C if else Statement
• The if-else statement in C is used to perform the • Let's see a simple example of C language if statement.
operations based on some specific condition. The operations Program to find the largest number of the three.
#include<stdio.h>
specified in if block are executed if and only if the given int main(){ #include <stdio.h>
condition is true. int number=0; int main()
• There are the following variants of if statement in C language. printf("Enter a number:"); {
• If statement scanf("%d",&number); int a, b, c;
• If-else statement if(number%2==0){ printf("Enter three numbers?");
• If else-if ladder scanf("%d %d %d",&a,&b,&c);
printf("%d is even number",number);
• Nested if if(a>b && a>c)
}
• If Statement return 0;
{
• The if statement is used to check some given condition and perform printf("%d is largest",a);
} }
some operations depending upon the correctness of that condition.
• The if statement is mostly used in the scenario where we need to Output if(b>a && b > c)
perform the different operations for the different conditions. Enter a number:4
{
4 is even number
printf("%d is largest",b);
enter a number:5 }
The syntax of the if statement if(c>a && c>b)
if(expression){ {
//code to be executed printf("%d is largest",c);
statement inside }
} if(a == b && a == c)
statement outside {
printf("All are equal");
Flowchart of }
. }
if statement in
C
Output
Enter three numbers?
12 23 34
34 is largest
If-else Statement
• If – else statement
Example to check whether a number is even or odd using if-else statement
• The if-else statement is used to perform two operations for a single
condition.
• The if-else statement is an extension to the if statement using which, #include<stdio.h>
we can perform two different operations, int main(){
• i.e., one is for the correctness of that condition, int number=0;
• and the other is for the incorrectness of the condition. printf("enter a number:");
• Here, we must notice that if and else block cannot be executed scanf("%d",&number);
simultaneously. if(number%2==0){
• Using if-else statement is always preferable since it always invokes printf("%d is even number",number);
an otherwise case with every if condition. }
The syntax of the if-else statement is given below. else{
printf("%d is odd number",number);
}
if(expression){ return 0;
//code to be executed }
if condition is true Output
}else{ enter a number:4
//code to be executed 4 is even number
if condition is false enter a number:5
} 5 is odd number

Flowchart of the
if-else statement in C
If else-if ladder Statement
• If else-if ladder Statement Example of an if-else-if statement in C language is given below.
• The if-else-if ladder statement is an extension to the if-else statement.
• It is used in the scenario where there are multiple cases to be performed for different
conditions. #include<stdio.h>
• In if-else-if ladder statement, if a condition is true then the statements defined in the if int main(){
block will be executed, int number=0;
• otherwise if some other condition is true then the statements defined in the else-if block will printf("enter a number:");
be executed, scanf("%d",&number);
• At the last if none of the condition is true then the statements defined in the else block will
be executed. if(number==10){
• There are multiple else-if blocks possible. printf("number is equals to 10");
• It is similar to the switch case statement where the default is executed instead of else block if }
none of the cases is matched. else if(number==50){
The syntax printf("number is equal to 50");
if(condition1){ }
//code to be executed if condition1 is true
}else if(condition2){
else if(number==100){
//code to be executed if condition2 is true printf("number is equal to 100");
} }
else if(condition3){ else{
//code to be executed if condition3 is true
} printf("number is not equal to 10, 50 or 100");
... }
else{ return 0;
//code to be executed if all the
conditions are false }
}
Output
enter a number:4
Flowchart of number is not equal to 10, 50 or 100
Else-if ladder statement in enter a number:50
C number is equal to 50
Nested if....else statement
The general form of a nested if...else statement is • Example

if expression is false then statement-block3 will be executed,


otherwise the execution continues and enters inside the
first if to perform the check for the next if block, where
if expression 1 is true the statement-block1 is executed
otherwise statement-block2 is executed.
SWITCH CASE STATEMENT
switch statement
• A switch statement allows a variable to be tested for equality
against a list of values.
• The switch statement in C is an alternate to if-else-if ladder
statement.
• It allows us to execute multiple operations for the different
possible values of a single variable called switch variable.
Here, We can define various statements in the multiple cases
for the different values of a single variable.

• The syntax of switch statement in c language is given


below:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
SWITCH CASE STATEMENT
• Rules for switch statement in C language • Functioning of switch case statement
• The switch expression must be of an integer or character type. • First, the integer expression specified in the switch statement is evaluated.
• The case value must be an integer or character constant. • Secondly this value is then matched one by one with the constant values given in the
different cases.
• The case value can be used only inside the switch statement. • If a match is found, then all the statements specified in that case are executed along
• The expression (after switch keyword) must yield an integer value i.e with the all the cases present after that case including the default statement.
the expression should be an integer or a variable or an expression that • If the matched case contains a break statement, then all the cases present after that
evaluates to an integer. will be skipped, and the control comes out of the switch.
• Otherwise, all the cases following the matched case will be executed.
• The case label values must be unique. • default case is executed when none of the mentioned case matches
• The case label must end with a colon(:) the switch expression. The default case can be placed anywhere in the switch case.
Even if we don't include the default case, switch statement works.
• The next line, after the case statement, can be any valid C statement. • No two cases can have similar values
• The break statement in switch case is not must. It is optional. • Let's see a simple example of c language switch statement.
• If there is no break statement found in the case, all the cases will be
executed present after the matched case. It is known as fall #include<stdio.h>
through the state of C switch statement. int main(){
int number=0;
• Let's try to understand it by the examples. We are assuming that there printf("enter a number:");
are following variables. scanf("%d",&number);
int x,y,z; switch(number){
char a,b; case 10:
float f; printf("number is equals to 10");
break;
Valid Switch Invalid Switch Valid Case Invalid Case case 50:
printf("number is equal to 50");
break; Output
case 100: enter a number:4
switch(x) switch(f) case 3; case 2.5; printf("number is equal to 100"); number is not equal to 10, 50 or 100
break; enter a number:50
switch(x>y) switch(x+2.5) case 'a'; case x; default: number is equal to 50
printf("number is not equal to 10, 50 or 100");
switch(a+b-2) case 1+2; case x+2; }
return 0;
switch(func(x,y)) case 'x'>'y'; case 1,2,3; }
SWITCH CASE STATEMENT
• C Switch statement is fall-through • Nested switch case statement
• We can use as many switch statement as we want inside a switch statement. Such type of
• In C language, the switch statement is fall through; it means if we don't use a statements is called nested switch case statements.
break statement in the switch case, all the cases after the matching case will be
• Nesting of switch statements are allowed, which means you can have switch statements inside
executed.
another switch block.
• Let's try to understand the fall through state of switch statement by the example • However, nested switch statements should be avoided as it makes the program more complex
given below. and less readable.
#include<stdio.h> • Consider the following example.
• .
int main(){
int number=0; #include <stdio.h>
printf("enter a number:"); int main () {
scanf("%d",&number); int i = 10;
switch(number){ int j = 20;
case 10: switch(i) {
printf("number is equal to 10\n"); case 10:
case 50: printf("the value of i evaluated in outer switch: %d\n",i);
printf("number is equal to 50\n"); case 20:
case 100: switch(j) {
printf("number is equal to 100\n"); case 20:
default: printf("The value of j evaluated in nested switch: %d\n",j);
printf("number is not equal to 10, 50 or 100"); }
} }
Output
return 0; printf("Exact value of i is : %d\n", i );
} enter a number:10
printf("Exact value of j is : %d\n", j );
number is equal to10
number is equal to 50 return 0;
number is equal to 100 }
number is not equal to 10, 50 or 100
Output
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 2
0
Exact value of i is : 10
Exact value of j is : 20
if-else vs switch
• Let's summarize the differences between if – else and switch in a tabular form.

If-else switch
Definition Depending on the condition in the 'if' statement, The user will decide which statement is to be executed.
'if' and 'else' blocks are executed.

Expression It contains either logical or equality expression. It contains a single expression which can be either a character or integer
variable.

Evaluation It evaluates all types of data, such as integer, It evaluates either an integer, or character.
floating-point, character or Boolean.

Sequence of First, the condition is checked. If the condition is It executes one case after another till the break keyword is not found, or
execution true then 'if' block is executed otherwise 'else' the default statement is executed.
block

Default If the condition is not true, then by default, else If the value does not match with any case, then by default, default
execution block will be executed. statement is executed.

Editing Editing is not easy in the 'if-else' statement. Cases in a switch statement are easy to maintain and modify. Therefore,
we can say that the removal or editing of any case will not interrupt the
execution of other cases.

Speed If there are multiple choices implemented If we have multiple choices then the switch statement is the best option as
through 'if-else', then the speed of the execution the speed of the execution will be much higher than 'if-else'.
will be slow.
LOOP CONTROL STATEMENTS
• The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
• The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of
writing the same code again and again, we can repeat the same code for a finite number of times.
• Statements with which when a block of code needs to be executed several number of times.
• Advantage with looping statement
• Reduce length of Code
• Take less memory space.
• Burden on the developer is reducing.
• Time consuming process to execute the program is reduced.

• The diagram depicts a loop execution.


• As per the diagram, if the Test Condition is true, then the loop is executed,
• and if it is false then the execution breaks out of the loop.
• After the loop is successfully executed the execution again starts from the Loop entry
• and again checks for the Test condition, and this keeps on repeating.
• The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body.
• After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check
returns false, the loop body is not executed, and execution breaks out of the loop.

• Types of C Loops
• There are three types of loops in C language that is given below:
• do while
• while
• for
C do...while Loop
• The do..while loop is similar to the while loop with one
important difference.
• The body of do...while loop is executed at least once. Only
then, the test expression is evaluated.
• A do while loop is a control flow statement that executes a
block of code at least once, and then repeatedly executes
the block, or not, depending on a given condition at the
end of the block (in while).
• When use do..while Loop
• When we need to repeat the statement block at least 1
time then we use do-while loop.
• The syntax of the do...while loop is:
do
{ // statements inside the body of the loop
}
while (testExpression);
• How do...while loop works? Flow Chart of
• The body of do...while loop is executed once. Only then, the do….while Loop
test expression is evaluated.
• If the test expression is true, the body of the loop is executed
again and the test expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop ends.
C do...while Loop
• Example : do...while loop • While vs do..while loop in C
• Using while loop:
#include <stdio.h>
int main()
// Program to add numbers until the user enters zero {
int i=0;
while(i==1)
#include <stdio.h> { printf("while vs do-while"); }
int main() printf("Out of loop");
}
{
double number, sum = 0;
Output:
// the body of the loop is executed at least once Out of loop
do
{
printf("Enter a number: "); • Same example using do-while loop
scanf("%lf", &number); #include <stdio.h>
sum += number; int main()
} { int i=0;
while(number != 0.0); OUTPUT
Enter a number: 1.5 do { printf("while vs do-while\n");
Enter a number: 2.4 }
printf("Sum = %.2lf",sum); while(i==1);
Enter a number: -3.4
Enter a number: 4.2 printf("Out of loop");
return 0; Enter a number: 0 }
} Sum = 4.70

Output:
while vs do-while
Out of loop

• Explanation: As mentioned in the beginning that do-while runs


at least once even if the condition is false because the condition
is evaluated, after the execution of the body of loop.
C while Loop
• While loop is also known as a pre-tested loop. How while loop works?
• In general, a while loop allows a part of the code to be executed • The while loop evaluates the test expression inside the
multiple times depending upon a given boolean condition. It can
be viewed as a repeating if statement.
parenthesis ().
• If the test expression is true, statements inside the body
• The while loop is mostly used in the case where the number of of while loop are executed. Then, the test expression is
iterations is not known in advance. evaluated again.
• The block of statements is executed in the while loop until the • The process goes on until the test expression is evaluated to
condition specified in the while loop is satisfied. It is also called a false.
pre-tested loop. • If the test expression is false, the loop terminates (ends).
• The syntax of while loop in • To learn more about test expression (when the test expression
c language is given below:
is evaluated to true and false),
while(condition){ Example 1: while loop • Here, we have initialized i to 1.
//code to be executed // Print numbers from 1 to 5 • When i is 1, the test expression i <=
5 is true. Hence, the body of
} #include <stdio.h> the while loop is executed. This
int main() { prints 1 on the screen and the value
int i = 1; of i is increased to 2.
• Flowchart of while (i <= 5) • Now, i is 2, the test expression i <= 5 is
again true. The body of the while loop
while loop { printf("%d\n", i); is executed again. This prints 2 on
++i; }
the screen and the value of i is
return 0; } increased to 3.
• This process goes on until i becomes
Output 6. When i is 6, the test expression i
12345 <= 5 will be false and the loop
terminates.
C for Loop
• How for loop works?
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test
expression is evaluated to false, the for loop is
terminated.
• However, if the test expression is evaluated to true,
statements inside the body of for loop are executed, and
the update expression is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false.
When the test expression is false, the loop terminates.

• The syntax of the for loop is:


for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
C for Loop
• Example 1: for loop

// Print numbers from 1 to 10


#include <stdio.h>
int main()
{
int i;
for (i = 1; i < 11; ++i)
{ printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
• i is initialized to 1.
• The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is executed. This
will print the 1 (value of i) on the screen.
• The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is
evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the screen.
• Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This process goes
on until i becomes 11.
• When i becomes 11, i < 11 will be false, and the for loop terminates.
CONDITIONAL OPERATOR
• The conditional operator is also known as a ternary operator.
• The conditional statements are the decision-making statements
which depends upon the output of the expression. \
• It is represented by two symbols, i.e., '?' and ':'. As conditional
operator works on three operands, so it is also known as
the ternary operator.
Syntax:

The conditional operator is of the form


variable = Expression1 ? Expression2 : Expression3

It can be visualized into if-else statement as:


If (Expression1){
variable = Expression2;}
else{
variable = Expression3;}

Working:
Here, Expression1 is the condition to be evaluated. If the
condition (Expression1) is True then Expression2 will be
executed and the result will be returned.
Otherwise, if the condition (Expression1) is false
then Expression3 will be executed and the result will be
returned.
Conditional OperatorVS if then…else
Conditional Operator if then…else
• Programmers use the ternary operator for decision making in • if-else statement’s short hand way is ternary operator.
place of longer if and else conditional statements. • Here’s a simple decision-making example using if and else:
Syntax
condition ? value_if_true : value_if_false int a = 10, b = 20, c;
if (a < b) { c = a; }
• The ternary operator take three arguments: else { c = b; } printf("%d", c);
• The first is a comparison argument • This example takes more than 10 lines, but that isn’t necessary. We
• The second is the result upon a true comparison
• The third is the result upon a false comparison.
can write the above program in just 3 lines of code using a ternary
operator.
int a = 10, b = 20, c; • Nested if-else statements just like the following code:
c = (a < b) ? a : b; printf("%d", c);
int a = 1, b = 2, ans;
• c is set equal to a, because the condition a < b was true. if (a == 1)
• Remember that the arguments value_if_true and value_if_false must be { if (b == 2)
of the same type, and they must be simple expressions rather than full { ans = 3; }
statements. else { ans = 5; }
} else { ans = 0; } printf ("%d\n", ans);
• Here's the nested if- else code can be rewritten using a nested
ternary operator:
Here output will be 3
int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);

Here output will be 3


Break and Continue Statement
break continue
• break is used for immediate termination of loop. • ‘Continue' terminate the current iteration and causes the next
• The break statement in C programming has the following two iteration of the loop to run immediately.
usages − • The continue statement in C programming works somewhat like
• When a break statement is encountered inside a loop, the loop the break statement. Instead of forcing termination, it forces the
is immediately terminated and the program control resumes at next iteration of the loop to take place, skipping any code in
the next statement following the loop. between.
• It can be used to terminate a case in the switch statement • For the for loop, continue statement causes the conditional test
• If we are using nested loops, the break statement will stop the and increment portions of the loop to execute. For
execution of the innermost loop and start executing the next line of the while and do...while loops, continue statement causes the
code after the block. program control to pass to the conditional tests.
Syntax Syntax
The syntax for a break statement Flow Diagram The syntax for a continue statement
break; continue;
#include <stdio.h> Flow Diagram
int main () { #include <stdio.h>
int a = 10; int main() { value of a: 10
while( a < 20 ) int a = 10; value of a: 11
{ printf("value of a: %d\n", a); do { value of a: 12
a++; if( a == 15) value of a: 13
if( a > 15) { /* skip the iteration */ value of a: 14
{ /* terminate the loop using break a = a + 1; value of a: 16
statement */ continue; value of a: 17
Output is : value of a: 18
break; }
value of a: 10 value of a: 19
} value of a: 11
printf("value of a: %d\n", a);
} return 0; value of a: 12 a++; }
} value of a: 13 while( a < 20 );
value of a: 14 return 0;
value of a: 15 }
goto statement in C
• A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function.
• Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of
a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid
them.
Syntax
The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;
• Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below
to goto statement.
#include <stdio.h>
Flow Diagram int main () {
int a = 10; OUTPUT
/* do loop execution */ value of a: 10
LOOP:do { value of a: 11
if( a == 15) value of a: 12
{ value of a: 13
/* skip the iteration */ value of a: 14
a = a + 1; value of a: 16
goto LOOP; value of a: 17
} value of a: 18
printf("value of a: %d\n", a); value of a: 19
a++;
}
while( a < 20 );
return 0;
}
nested loops in C
• C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept.
Syntax The syntax for a nested do...while loop statement in C
The syntax for a nested for loop statement in C is as is as follows −
The syntax for a nested while loop statement in C
follows − do
programming language is as follows −
for ( init; condition; increment ) {
while(condition)
{ statement(s);
{ while(condition)
for ( init; condition; increment ) do
{ statement(s);
{statement(s); {
} statement(s);
} statement(s);
}
statement(s); }while( condition );
} }while( condition );
• We can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.

The following program uses a nested for loop to find the


prime numbers from 2 to 100 −

#include <stdio.h>
int main ()
{
int i, j;
for(i = 2; i<100; i++)
{
for(j = 2; j <= (i/j); j++)
{
if(!(i%j))
break;
// if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
}
return 0;
}
INFINITE LOOP
• The Infinite Loop
• A loop becomes an infinite loop if a condition never becomes false.
• The for loop is traditionally used for this purpose.
• Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the
conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{ printf("This loop will run forever.\n");
}
return 0;
}
• When the conditional expression is absent, it is assumed to be true. We may have an initialization and increment expression, but
C programmers more commonly use the for(;;) construct to signify an infinite loop.
• We can terminate an infinite loop by pressing Ctrl + C keys.
C Program to Reverse a Number (for loop)
Reverse an Integer
C program to reverse a number using for loop
#include <stdio.h>
int main()
{
int n, reverse_Number = 0,
int rem,Original_number=0;
printf("Enter a number to get reverse number ");
scanf("%d", &n);
Original_number=n;
for(;n != 0;)
{
rem = n%10;
reverse_Number = reverse_Number*10 + rem;
n /= 10;
}
printf("Reversed Number of %d is = %d",Original_number,reverse_Number);
getch();
}
Input: num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder
of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
C Program to Reverse a Number
• Example:
num = 4562
rev_num = 0
• rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456
• rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45
• rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4
• rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0
C Program to Reverse a Number (while loop)
• Reverse an Integer #include <stdio.h>
• This program takes an integer input from the int main() {
int n, rev = 0, remainder;
user. Then the while loop is used until n !=
printf("Enter an integer: ");
0 is false (0). scanf("%d", &n);
• In each iteration of the loop, the remainder while (n != 0) {
when n is divided by 10 is calculated and the remainder = n % 10;
rev = rev * 10 + remainder;
value of n is reduced by 10 times. n /= 10;
• Inside the loop, the reversed number is }
printf("Reversed number = %d", rev);
computed using:
return 0;
• rev = rev*10 + remainder; }

Output
Enter an integer: 2345
Reversed number = 5432
Program code for Factorial of a Number in C
#include<stdio.h> • Working:
#include<conio.h> • First the computer reads the number to find the factorial of
void main() the number from the user.
{ • Then using while loop the value of ‘i’ is multiplied with the value of
int n,i=1,f=1; ‘f’.
clrscr(); • The loop continues till the value of ‘i’ is less than or equal to ‘n’.
printf("\n Enter The Number:"); • Finally the factorial value of the given number is printed.
scanf("%d",&n);
• Step by Step working of the above Program Code:
• Let us assume that the number entered by the user is 6.
//LOOP TO CALCULATE FACTORIAL OF A NUMBER • It assigns the value of n=6 , i=1 , f=1
while(i<=n) • Then the loop continues till the condition of the while loop is true.
{ • 2.1. i<=n (1<=6) , while loop condition is true.
f=f*i; • f=f*i (f=1*1) So f=1
• i++ (i=i+1) So i=2
i++; • 2.2. i<=n (2<=6) , while loop condition is true.
} • f=f*i (f=1*2) So f=2
printf("\n The Factorial of %d is %d",n,f); • i++ (i=i+1) So i=3
• 2.3. i<=n (3<=6) , while loop condition is true.
getch(); • f=f*i (f=2*3) So f=6
} • i++ (i=i+1) So i=4
• 2.4. i<=n (4<=6) , while loop condition is true.
• f=f*i (f=6*4) So f=24
• i++ (i=i+1) So i=5
• 2.5. i<=n (5<=6) , while loop condition is true.
• f=f*i (f=24*5) So f=120
• i++ (i=i+1) So i=6
• 2.6. i<=n (6<=6) , while loop condition is true.
• f=f*i (f=120*6) So f=720
• i++ (i=i+1) So i=7
• 2.7. i<=n (7<=6) , while loop condition is false.
• It comes out of the while loop.
• Finally it prints as given below
• The Factorial of 6 is 720
• Thus the program execution is completed.
C program to check Least Significant Bit (LSB) of a
number is set or not
Logic to check Least Significant Bit (LSB) of a number
• To check the status of Least Significant Bit (LSB) of any /** * C program to check Least Significant Bit
number we will use bitwise AND & operator. (LSB) of a number using bitwise operator
• Even for checking the current status of any bit we use bitwise */ #include <stdio.h>
AND operator. int main()
• We know that bitwise AND operator evaluates each bit of the {
result to 1 if the corresponding bits of both operands are 1. int num;
• Now to check the LSB of any number we are going to perform // Input a number from user
bitwise AND operation with the number and 1. printf("Enter any number: ");
• The bitwise AND operation number & 1 will evaluate to 1 if and scanf("%d", &num);
only if the LSB of number is 1 otherwise will evaluate to 0. //If (num & 1) evaluates to 1
if(num & 1)
printf("LSB of %d is set (1).", num);
else
printf("LSB of %d is unset (0).", num);
return 0;}
C program to swap two numbers using bitwise operator
• Logic to swap two numbers using bitwise • Program to swap two numbers
operator #include <stdio.h>
• We can perform swapping of two numbers using int main()
bitwise XOR ^operator. { int num1, num2;
• Bitwise XOR operator evaluates each bit of the result printf("Enter any two numbers: ");
to 1 if each corresponding bits of the two operands scanf("%d%d",&num1,&num2);
differ else evaluates to 0. printf("Original value of num1 = %d\n", num1);
• Suppose two integer values a and b printf("Original value of num2 = %d\n", num2);
num1 ^= num2;
Let's suppose x = a ^ b
num2 ^= num1;
Then again x ^ b will evaluate to a and x ^ a will num1 ^= num2;
evaluate to b. printf("Num1 after swapping = %d\n", num1);
printf("Num2 after swapping = %d\n", num2);
return 0;}
C program to check even or odd using bitwise operator
• Logic to check even or odd numbers using bitwise • Program to check even or odd using bitwise operator

operator. #include <stdio.h>


• We can use bitwise ‘AND’ ’&’ operator. int main()
{ int num;
• Bitwise operator operates on bit level, hence to check a // Input a number from user
number is odd we only need to check if its Least printf("Enter any number: ");
scanf("%d", &num);
Significant Bit (LSB) is set or not. if(num & 1)
• If 0 bit of a number is set (1) then the number is odd
th {
printf("%d is odd.", num);
otherwise even. }
else
{
printf("%d is even.", num);
}
return 0;
}
• Program to check even or odd using conditional and bitwise operator

#include <stdio.h>
• In the above image we can see that if the number is even int main()
then its LSB is 0 otherwise LSB is 1. {
• To check the status of any bit we can use bitwise AND int num;
operator. If num & 1 evaluates to 1 then the number is // Input a number from user
odd otherwise even. printf("Enter any number: ");
scanf("%d", &num); (num & 1) ?
printf("%d is odd.", num) : printf("%d is even.", num);
return 0;
}
THANK YOU!!

You might also like